relate-core 1.5.0

Core values, errors, and IDs for Relate
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
//! Preview-feature gating for the Cypher dialect (ADR-0371).
//!
//! A preview feature is a Cypher language feature accepted into a CIP but
//! not yet part of the pinned dialect floor (the openCypher TCK pin).
//! `RELATE_PREVIEW` is the global opt-in: a comma-separated list of
//! kebab-case feature names, read once at `Database::open`. Unset or empty
//! means no preview features; an unknown name fails open with a loud usage
//! error naming the known names — never a silent ignore.
//!
//! Only syntax-extending features gate: a purely additive function name
//! never needs the opt-in, so it never lands in this registry. Four
//! gate classes are recorded exceptions. (a) ADR-0378, widened by
//! ADR-0593 and ADR-0741: a built-in surface whose contract tracks a
//! non-final external spec — the `ontology` row gates the
//! `db.ontology.*` procedure family, the `dbms.listCapabilities` row
//! `ontology.supported.version`, and, through the namespace registry's
//! one fixed-namespace → feature mapping, the `system_ontologies`
//! namespace's visibility. (b) ADR-0497: a
//! *name admission* gate — a function name an approved CIP adds that no
//! reference release ships, or one the corpus records as unreachable
//! (`coll-zip`, `coll-has`, `gql-stddev-aliases`). A name
//! gate hides a name; it never widens grammar, and its disabled form is the
//! registry's ordinary unknown-function rejection rather than the authored
//! error below: a name that must not exist cannot be named in an error
//! without advertising it. (c) ADR-0593: a fixed namespace's visibility —
//! the name-gate rule in namespace form, so a hidden database is
//! indistinguishable from an unknown one at every resolution site: listed
//! by no catalog, rejected by the site's own unknown-database path, never
//! the authored error. (d) ADR-0703: a *storage representation* — the
//! `vortex-store` row gates an experimental property store's attach at
//! `Database::open` itself, so its disabled form is not an error at all:
//! the default compact records answer unchanged, and no statement can ask
//! for the store by name. None of the exceptions is general — additive
//! function names and surfaces on our own pinned contract still never
//! gate. Each gated feature checks the gate where it would otherwise be
//! parsed or dispatched; while disabled a syntax or procedure-family check
//! fails with [`preview_feature_disabled`]'s authored error.
//!
//! The registry macro is the single source: variant, doc, and name are
//! declared once, and the macro emits every derivation — the enum, the
//! exhaustive `kebab_name`/`from_kebab_name` matches (coverage is a
//! compile guarantee), and [`PREVIEW_FEATURE_TABLE`], the registry view
//! the fail-closed known-names list renders from. A later feature PR adds
//! its row here and gates its syntax; nothing else names the feature.

use crate::error_kinds::TckErrorClass;

use crate::Error;

/// One declaration list per closed payload vocabulary: the macro emits
/// the enum and its `ALL` enumeration from the same list, so a variant
/// cannot exist without its row in `ALL` and vice versa — the compile
/// guarantee the site audits rest on.
macro_rules! closed_vocabulary {
    ($name:ident, $doc:literal, [$($variant:ident),* $(,)?]) => {
        #[doc = $doc]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum $name {
            $($variant,)*
        }

        impl $name {
            /// Every variant, declaration order — derived from the same
            /// list as the enum, so a new variant joins it without a
            /// second edit.
            pub const ALL: &'static [$name] = &[$($name::$variant),*];
        }
    };
}

closed_vocabulary!(
    ParseOption,
    "The `ParseOptions` field a parse-site feature switches on, one \
     variant per option. The front applies each through one total `match`.",
    [
        ObfuscatedLiterals,
        MixedLabelSyntax,
        CypherAnnotations,
        PathConstruction
    ]
);

closed_vocabulary!(
    DetectorKind,
    "The front's AST detector a detected feature is checked by, one \
     variant per distinct detector. The front dispatches through one \
     total `match`.",
    [
        HybridSearch,
        LocalCallables,
        Float16,
        PathConstruction,
        Chronological,
    ]
);

/// Where in the pipeline a preview feature's gate is checked, for the
/// sites whose consumers a test can read. A feature gated where this
/// vocabulary cannot name the site (statement validation, run-time
/// evaluation, the executor's graph-type layer) declares
/// [`GateSite::GatedElsewhere`]; a row never declares no site.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GateSite {
    /// The lexer or parser decides it, through this parse option.
    ParseOption(ParseOption),
    /// The front's AST detector loop rejects the feature's syntax.
    AstDetector(DetectorKind),
    /// The graph-type family: the front's one graph-type walk reports the
    /// features a statement's graph-type bodies use, checked in the same
    /// admission loop.
    GraphTypeMembership,
    /// A function name is admitted or hidden by the function registry.
    NameAdmission,
    /// Procedure dispatch gates a built-in procedure family.
    ProcedureDispatch,
    /// The namespace registry hides a fixed namespace.
    Namespace,
    /// A `dbms.listCapabilities` row lists only while the opt-in is set —
    /// a row-content gate, not a call gate: the procedure stays callable
    /// and its always-on rows are unchanged.
    CapabilityListing,
    /// Gated at a site this vocabulary does not name; the row's own doc says
    /// where. Distinct from "ungated": an empty site list is rejected.
    GatedElsewhere,
}

/// Where a [`GateSite`]'s gate is checked — the closed owner vocabulary
/// each consumer matches once, so a new site names its consumer where
/// the site is declared and no consumer re-lists the sites it does not
/// own. The front owns the parse options, the AST detectors and the one
/// graph-type walk; everything else belongs to a consumer outside the
/// front (function admission, procedure dispatch, the namespace
/// mapping, the capability-row producer, the evaluator, the open-time
/// attach).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GateOwner {
    /// [`GateSite::ParseOption`]'s owner.
    Parse(ParseOption),
    /// [`GateSite::AstDetector`]'s owner.
    Detect(DetectorKind),
    /// [`GateSite::GraphTypeMembership`]'s owner.
    GraphTypeWalk,
    /// An owner outside the front (the enum's doc names them).
    External,
}

impl GateSite {
    /// The site's owner: the one classification every consumer matches,
    /// so the front's totals and the facade's audits hold one stable
    /// match over this small vocabulary instead of re-listing the site
    /// subsets they do not act on.
    pub fn owner(self) -> GateOwner {
        match self {
            GateSite::ParseOption(option) => GateOwner::Parse(option),
            GateSite::AstDetector(kind) => GateOwner::Detect(kind),
            GateSite::GraphTypeMembership => GateOwner::GraphTypeWalk,
            GateSite::NameAdmission
            | GateSite::ProcedureDispatch
            | GateSite::Namespace
            | GateSite::CapabilityListing
            | GateSite::GatedElsewhere => GateOwner::External,
        }
    }

    /// Every payload-less site, one row per variant — the enumerable
    /// subset the audits iterate. The payload-carrying sites — those
    /// whose [`owner`](Self::owner) is `Parse` or `Detect` — enumerate
    /// through their own payload vocabularies
    /// ([`ParseOption::ALL`], [`DetectorKind::ALL`]); a new payload-less
    /// variant joins this list, and the registry's gate-site audit fails
    /// if a declared site is missing from it.
    pub const ALL: &'static [GateSite] = &[
        GateSite::GraphTypeMembership,
        GateSite::NameAdmission,
        GateSite::ProcedureDispatch,
        GateSite::Namespace,
        GateSite::CapabilityListing,
        GateSite::GatedElsewhere,
    ];
}

/// The one registry: each preview feature's variant, doc comment,
/// kebab-case `RELATE_PREVIEW` name, and gate sites are declared from this single
/// list, so a variant cannot exist without its name and vice versa — a
/// forgotten row is a compile error, not a runtime `expect`. Every other
/// spelling of a feature name derives from [`PREVIEW_FEATURE_TABLE`].
macro_rules! preview_feature_registry {
    ($(($variant:ident, $doc:literal, $name:literal, [$($site:expr),* $(,)?])),* $(,)?) => {
        /// A gated preview Cypher feature. The table order is the
        /// registry order; rows are never renumbered, only appended.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum PreviewFeature {
            $(
                #[doc = $doc]
                $variant,
            )*
        }

        /// The one registry: each preview feature with its kebab-case
        /// `RELATE_PREVIEW` name. The table order is the registry
        /// order; rows are never renumbered, only appended.
        pub const PREVIEW_FEATURE_TABLE: &[(PreviewFeature, &str)] =
            &[$((PreviewFeature::$variant, $name)),*];

        /// Every registered feature, registry order — the enumeration
        /// callers iterate instead of re-spelling the vocabulary.
        pub const PREVIEW_FEATURES: &[PreviewFeature] = &[$(PreviewFeature::$variant),*];

        /// The registry width bound: the bitset's `u32` holds every
        /// registered feature — a 33rd row is a compile error, not a
        /// runtime wrap.
        const _: () = assert!([$(stringify!($variant)),*].len() <= 32);

        // A row never declares no gate site: an empty list would conflate
        // "gated where the vocabulary cannot name it" (`GatedElsewhere`)
        // with "not gated".
        $(
            const _: () = assert!(
                ![$(stringify!($site)),*].is_empty(),
                concat!(stringify!($variant), " declares no gate site")
            );
        )*

        impl PreviewFeature {
            /// The feature's kebab-case `RELATE_PREVIEW` name. The
            /// exhaustive match is the compile guarantee the registry
            /// exists for — coverage cannot drift from the table.
            pub fn kebab_name(self) -> &'static str {
                match self {
                    $(PreviewFeature::$variant => $name,)*
                }
            }

            /// The pipeline sites that check this feature's gate.
            pub fn gate_sites(self) -> &'static [GateSite] {
                match self {
                    $(PreviewFeature::$variant => &[$($site),*],)*
                }
            }

            /// The feature for a kebab-case `RELATE_PREVIEW` name.
            /// `None` when `name` is not a registered feature.
            pub fn from_kebab_name(name: &str) -> Option<Self> {
                match name {
                    $($name => Some(PreviewFeature::$variant),)*
                    _ => None,
                }
            }
        }
    };
}

preview_feature_registry! {
    (HybridSearch, "CIP-278 hybrid search `COMBINE` (reserved; lands later).", "hybrid-search", [GateSite::AstDetector(DetectorKind::HybridSearch)]),
    (LocalCallables, "CIP-231 local callables: DEFINE PROCEDURE/FUNCTION, ADR-0382.", "local-callables", [GateSite::AstDetector(DetectorKind::LocalCallables)]),
    (GraphTypeOptProps, "CIP-283 graph-type optional properties (`prop :: ANY` in element types).", "graph-type-opt-props", [GateSite::GraphTypeMembership]),
    (GraphTypeDefaultValues, "CIP-262 graph-type property default values (`DEFAULT ON COMMIT <value expression>`).", "graph-type-default-values", [GateSite::GraphTypeMembership]),
    (GraphTypeImpliedLabels, "CIP-266 graph-type implied labels that identify node element types (inheritance).", "graph-type-implied-labels", [GateSite::GraphTypeMembership]),
    (
        Ontology,
        "The ontology feature's whole dialect surface: the `db.ontology.*` procedures \
         (ADR-0378: the first non-syntax extension of ADR-0371's scope policy — the \
         family's contract tracks the non-final Ontology Graph Spec and CIP-287), the \
         `system_ontologies` namespace's visibility through the namespace registry's \
         mapping (ADR-0593 — the namespace exists to host this feature's stored \
         document, so its listing advertises the same non-final surface the procedures \
         do), and the `dbms.listCapabilities` row `ontology.supported.version` \
         (ADR-0741 — the supported-spec-version fact ontology tooling reads, absent \
         while the opt-in is off like every other surface of the feature). Row, \
         mapping and gates are removed once the spec and CIP-287 are final.",
        "ontology",
        [GateSite::ProcedureDispatch, GateSite::Namespace, GateSite::CapabilityListing]
    ),
    (
        ObfuscatedLiterals,
        "The Neo4j obfuscated literal `******`: parsed to a dummy `false` \
         for semantic analysis, never executed. Gates at the lexer, the one point the two \
         behaviors differ: enabled it lexes as a literal, disabled the stream is the ordinary \
         `*` tokens and the parser's own syntax error -- Neo4j's disabled form is a syntax \
         error, not ADR-0371's authored preview error, so the gate never reaches the front \
         detector loop (the registry names no detector site for it).",
        "obfuscated-literals",
        [GateSite::ParseOption(ParseOption::ObfuscatedLiterals)]
    ),
    (
        MixedLabelSyntax,
        "Neo4j's mixed-label-syntax extra semantic feature: legacy \
         colon-conjunction, GQL label-expression symbols and the `IS` introducer may mix \
         across the label expressions of one clause (gates at parse, threaded to the parser \
         as `ParseOptions`; mixing inside ONE label expression stays rejected).",
        "mixed-label-syntax",
        [GateSite::ParseOption(ParseOption::MixedLabelSyntax)]
    ),
    (
        Float16CoordinateTypes,
        "The FLOAT16/BFLOAT16 vector coordinate types (CIP-280, ADR-0464), mirroring \
         Neo4j's own configuration toggle: the types in a \
         `VECTOR<…>` type expression and the `vector(<list>, <dim>, <type>)` constructor. \
         Detected on the parsed AST; the disabled form is ADR-0371's authored error.",
        "float16-coordinate-types",
        [GateSite::AstDetector(DetectorKind::Float16)]
    ),
    (
        ChronologicalComparisons,
        "Cypher 25's four chronological comparison operators \
         (`a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME REPRESENTATION b`), mirroring \
         Neo4j's own toggle. Detected on the \
         parsed AST; the disabled form is ADR-0371's authored error.",
        "chronological-comparisons",
        [GateSite::AstDetector(DetectorKind::Chronological)]
    ),
    (
        CollectionZip,
        "CIP-274: the `coll.zip` collection function, callable and \
         `SHOW`-listed only under this opt-in (ADR-0497). A live Neo4j probe \
         records the name as front-end registered but unreachable \
         -- no `SHOW FUNCTIONS` row, 42N48 under CYPHER 5 and 25 -- so the default dialect must \
         not advertise it. Row and gate are deleted when a Neo4j release ships the function.",
        "coll-zip",
        [GateSite::NameAdmission]
    ),
    (
        CollectionHas,
        "CIP-286: the `coll.hasAnyOf`/`coll.hasAllOf`/\
         `coll.hasNoneOf` collection functions, callable and `SHOW`-listed only under this \
         opt-in (ADR-0497). One row for the three-name family; deleted when CIP-286 ships.",
        "coll-has",
        [GateSite::NameAdmission]
    ),
    (
        CypherAnnotations,
        "CIP-281 Cypher annotations: clause-level `@name(params)` markers before a \
         clause, parsed and semantically checked, then discarded (no runtime effect). \
         Gates at the lexer, the one point the two behaviors differ: enabled, `@` lexes \
         as the annotation introducer; disabled, it is the ordinary `unexpected \
         character: @` syntax error. Row and gate are deleted when the CIP ships in a \
         release.",
        "cypher-annotations",
        [GateSite::ParseOption(ParseOption::CypherAnnotations)]
    ),
    (
        GqlStddevAliases,
        "CIP-245's `stddev_samp`/`stddev_pop` spellings (ADR-0497): the corpus catalogue lists \
         only the canonical `stdev_samp`/`stdev_pop`, and Neo4j 2026.05 answers 42N48 for the \
         GQL spellings, so the default dialect advertises and dispatches only the `stdev_*` \
         rows. The gate keeps the `@doc`-derived 78/78 reachable. Deleted when a release \
         registers the spellings (or the scenarios are re-pinned).",
        "gql-stddev-aliases",
        [GateSite::NameAdmission]
    ),
    (
        GraphTypeShowVariants,
        "CIP-275 graph-type display variants of SHOW CURRENT GRAPH TYPE: consolidated and flattened.",
        "graph-type-show-variants",
        [GateSite::GraphTypeMembership]
    ),
    (
        PathConstruction,
        "The `PATH [n1, r1, n2, ...]` path constructor: builds a path value from an \
         alternating node, relationship, ... list. Detected at the parse point (the \
         `PATH` word before `[`); the disabled form is ADR-0371's authored error.",
        "path-construction",
        [GateSite::ParseOption(ParseOption::PathConstruction), GateSite::AstDetector(DetectorKind::PathConstruction)]
    ),
    (
        PathConcatenation,
        "The `p1 || p2` path concatenation: joins two paths that share a boundary \
         node. Gates the `||` operator over path operands at evaluation; the disabled \
         form is the existing `||` operand type error, not the authored error.",
        "path-concatenation",
        [GateSite::GatedElsewhere]
    ),
    (
        VortexStore,
        "The Vortex columnar property store (ADR-0665), experimental: an \
         alternative storage representation behind the executor's PropStore \
         seam. The registry's first storage-representation row (ADR-0703): \
         the gate is at `Database::open`, not at a parse or dispatch site — \
         the row attaches the store for every open in the process (the typed \
         `OpenOptions::vortex_store` field opts in one open), and a build \
         without the `vortex-store` cargo feature fails the open closed \
         naming the feature. While disabled nothing changes: the default \
         compact records answer, and no statement can ask for the store, so \
         there is no authored disabled-error.",
        "vortex-store",
        [GateSite::GatedElsewhere]
    ),
}

/// The registered feature names, comma-separated, for the fail-closed
/// unknown-name error. The table's order, the registry's order.
fn known_feature_names() -> String {
    PREVIEW_FEATURE_TABLE
        .iter()
        .map(|(_, name)| *name)
        .collect::<Vec<_>>()
        .join(", ")
}

/// The set of preview features enabled by `RELATE_PREVIEW` for one
/// open store. Empty ([`PreviewFeatures::none`]) disables every gated
/// feature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PreviewFeatures(u32);

/// The fail-closed empty set: the value a store-level service bundle
/// carries until open installs the resolved `RELATE_PREVIEW` set
/// (ADR-0371, ADR-0378), so an executor-only `Graph::default()` gates every
/// preview feature closed.
impl Default for PreviewFeatures {
    fn default() -> Self {
        Self::none()
    }
}

impl PreviewFeatures {
    /// No preview features: every gate fails closed.
    pub fn none() -> Self {
        Self(0)
    }

    /// Parse one opt-in value — the single grammar every preview
    /// source shares (ADR-0719): the `RELATE_PREVIEW` environment
    /// variable, the store-committed `relate.yaml` `preview:` list,
    /// and the typed `OpenOptions.preview` field all resolve through
    /// here, each naming its own `source` in a failure. A
    /// comma-separated list of kebab-case feature names, whitespace
    /// tolerated around each name. An empty or blank value enables
    /// nothing. An unknown name (including an empty list segment) is a
    /// loud usage error naming the known names — fail-closed, never
    /// silently ignored.
    pub fn parse_named(source: &str, raw: &str) -> Result<Self, Error> {
        if raw.trim().is_empty() {
            return Ok(Self::none());
        }
        Self::from_names(source, raw.split(',').map(str::trim))
    }

    /// Resolve already-separated feature names — the per-name half of
    /// the one grammar, for a source whose names arrive as a typed list
    /// (the store-committed `relate.yaml` `preview:` sequence, ADR-0719)
    /// rather than one comma string. Every name resolves against the
    /// registry or the whole call fails naming `source` and the known
    /// names; an empty name is an unknown name, never a silent skip. No
    /// names enables nothing.
    pub fn from_names<'a>(
        source: &str,
        names: impl IntoIterator<Item = &'a str>,
    ) -> Result<Self, Error> {
        names.into_iter().try_fold(Self::none(), |enabled, name| {
            let feature = PreviewFeature::from_kebab_name(name).ok_or_else(|| {
                Error::semantic(format!(
                    "{}: invalid {source} value: unknown preview feature \
                     '{name}' (known features: {})",
                    TckErrorClass::SemanticError.as_str(),
                    known_feature_names(),
                ))
            })?;
            Ok(enabled.with_feature(feature))
        })
    }

    /// An optional surface parameter — absent opts into nothing, present
    /// parses with [`Self::parse_named`]. The one statement of the
    /// "optional opt-in" rule the binding surfaces (the wasm and Python
    /// parameters) share; each keeps only its own error mapping.
    pub fn parse_optional(source: &str, raw: Option<&str>) -> Result<Self, Error> {
        raw.map_or(Ok(Self::none()), |raw| Self::parse_named(source, raw))
    }

    /// Parse one `RELATE_PREVIEW` value: a comma-separated list of
    /// kebab-case feature names, whitespace tolerated around each name.
    /// An empty or blank value enables nothing. An unknown name (including
    /// an empty list segment) is a loud usage error naming the known
    /// names — fail-closed, never silently ignored.
    pub fn parse(raw: &str) -> Result<Self, Error> {
        Self::parse_named(PREVIEW_ENV_VAR, raw)
    }

    /// Whether `feature` is enabled for this store — the typed gate
    /// predicate a gated feature checks where it would otherwise be parsed
    /// or dispatched.
    pub fn enabled(self, feature: PreviewFeature) -> bool {
        self.0 & (1 << (feature as u32)) != 0
    }

    /// The set enabling every feature one by one, over an existing value:
    /// the fixture constructor the gate tests build from the tables that own
    /// the rows, so a new gated name is added in one place.
    pub fn with_feature(self, feature: PreviewFeature) -> Self {
        Self(self.0 | (1 << (feature as u32)))
    }

    /// The union of two resolved sets (ADR-0719): every preview source
    /// is additive — the environment variable, the store-committed
    /// config and the typed open option stack through here, and none
    /// removes. Order is irrelevant.
    pub fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// The gate check: `Ok(())` when `feature` is enabled, otherwise the
    /// authored fail-closed error of [`preview_feature_disabled`].
    pub fn require(self, feature: PreviewFeature) -> Result<(), Error> {
        if self.enabled(feature) {
            Ok(())
        } else {
            Err(preview_feature_disabled(feature))
        }
    }
}

/// The preview opt-in's environment variable (ADR-0371) — the one
/// spelling of its name: the open reads it, and its parse failure cites
/// it.
pub const PREVIEW_ENV_VAR: &str = "RELATE_PREVIEW";

/// The store-committed config file's one spelling (ADR-0719 decision 1:
/// no JSON twin, no second name) — the store-committed preview carrier's
/// name, here beside the variable's so every layer that names a carrier
/// (the storage reader, the `SHOW SETTINGS` provenance) reads one fact.
pub const STORE_CONFIG_FILE: &str = "relate.yaml";

/// One of the preview opt-in's three additive carriers (ADR-0719
/// decision 3) — the typed vocabulary of [`PreviewSources`]. It carries
/// no display text: each layer that names a carrier (a parse failure, the
/// `SHOW SETTINGS` provenance) spells it where that text belongs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PreviewSource {
    /// The `RELATE_PREVIEW` environment variable — the machine's local
    /// extra, where an environment exists.
    Env,
    /// The store-committed `relate.yaml` `preview:` list — the store's
    /// declared contract.
    Config,
    /// The typed `OpenOptions.preview` field — the embedder's choice,
    /// each surface's own opt-in spelling (the CLI's `--preview`, the
    /// wasm parameter, the Python keyword).
    Option,
}

/// The preview opt-in's resolved sources (ADR-0719 decision 3): the
/// three additive carriers, kept per-set so the resolved surface can
/// report which source enabled each feature. The union is derived —
/// never stored beside its parts — so the parts and the whole cannot
/// drift: every gate reads [`Self::union`], and `SHOW SETTINGS`
/// (ADR-0719 decision 6) reads [`Self::carriers`] for the provenance it
/// reports.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PreviewSources {
    /// [`PreviewSource::Env`]'s set.
    pub env: PreviewFeatures,
    /// [`PreviewSource::Config`]'s set.
    pub config: PreviewFeatures,
    /// [`PreviewSource::Option`]'s set.
    pub option: PreviewFeatures,
}

impl PreviewSources {
    /// Every carrier with its set, in the fixed order the provenance
    /// reports them — the one table [`Self::union`] and
    /// [`Self::carriers`] read. Built by an exhaustive destructure, so a
    /// new carrier field is a compile error here, never a source silently
    /// left out of the union.
    fn parts(&self) -> [(PreviewSource, PreviewFeatures); 3] {
        let Self {
            env,
            config,
            option,
        } = *self;
        [
            (PreviewSource::Env, env),
            (PreviewSource::Config, config),
            (PreviewSource::Option, option),
        ]
    }

    /// The three sources' additive union (ADR-0719 decision 3) — the
    /// resolved set every gate reads, derived here so it is never
    /// stored beside the parts it comes from.
    pub fn union(&self) -> PreviewFeatures {
        self.parts()
            .into_iter()
            .fold(PreviewFeatures::none(), |set, (_, part)| set.union(part))
    }

    /// The carriers that enabled `feature`, in [`Self::parts`]' order —
    /// the provenance `SHOW SETTINGS` reports. Empty exactly when the
    /// union has the feature off.
    pub fn carriers(&self, feature: PreviewFeature) -> impl Iterator<Item = PreviewSource> {
        self.parts()
            .into_iter()
            .filter(move |(_, part)| part.enabled(feature))
            .map(|(source, _)| source)
    }
}

/// The authored fail-closed gate text for a preview feature invoked while
/// disabled, already prefixed with its `SemanticError` class — the single
/// source of the gate message. [`PreviewFeatures::require`] wraps it in an
/// [`Error`]; layers outside this crate (the executor's graph-type
/// semantic layer, which fails closed on the same constructs its
/// statement-admission gate already checked when they only materialize
/// against stored graph-type state) render it through their own error
/// type without re-spelling it.
pub fn preview_feature_disabled_text(feature: PreviewFeature) -> String {
    let name = feature.kebab_name();
    format!(
        "{}: preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}",
        TckErrorClass::SemanticError.as_str(),
    )
}

/// The authored fail-closed gate error for a preview feature invoked while
/// disabled (the house style of the ADR-0229 §2 authored text): the
/// engine renders `semantic error: SemanticError: preview feature
/// '<name>' is not enabled: set RELATE_PREVIEW=<name>`.
pub(crate) fn preview_feature_disabled(feature: PreviewFeature) -> Error {
    Error::semantic(preview_feature_disabled_text(feature))
}

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

    #[test]
    fn registry_names_are_unique_and_round_trip() {
        // The macro single-sources the variant list and the rows, so
        // exhaustiveness is a compile guarantee; these pin the rest: no
        // name spelled twice, and every row's name parses back to its
        // variant.
        let mut seen = std::collections::HashSet::new();
        for (feature, name) in PREVIEW_FEATURE_TABLE {
            assert_eq!(feature.kebab_name(), *name);
            assert!(seen.insert(*name), "duplicate name {name}");
            assert_eq!(PreviewFeature::from_kebab_name(name), Some(*feature));
        }
        assert_eq!(PreviewFeature::from_kebab_name("nope"), None);
    }

    #[test]
    fn gate_sites_never_repeat_within_a_row() {
        for feature in PREVIEW_FEATURES {
            let mut seen = std::collections::HashSet::new();
            for site in feature.gate_sites() {
                assert!(
                    seen.insert(*site),
                    "{} repeats {site:?}",
                    feature.kebab_name()
                );
            }
        }
    }

    #[test]
    fn every_declared_payload_less_site_is_enumerated() {
        // `GateSite::ALL` is the hand-maintained enumeration the audits
        // iterate; a declared payload-less site missing from it would
        // silently escape them. The payload-carrying sites are excluded —
        // their owner is `Parse` or `Detect` and they enumerate through
        // their own payload vocabularies.
        for feature in PREVIEW_FEATURES {
            for site in feature.gate_sites() {
                if matches!(site.owner(), GateOwner::Parse(_) | GateOwner::Detect(_)) {
                    continue;
                }
                assert!(
                    GateSite::ALL.contains(site),
                    "{} declares {site:?}, which GateSite::ALL does not enumerate",
                    feature.kebab_name()
                );
            }
        }
    }

    #[test]
    fn parse_empty_and_unset_value_enable_nothing() {
        assert_eq!(PreviewFeatures::parse("").unwrap(), PreviewFeatures::none());
        assert_eq!(
            PreviewFeatures::parse("   ").unwrap(),
            PreviewFeatures::none()
        );
        for feature in PREVIEW_FEATURES {
            assert!(!PreviewFeatures::none().enabled(*feature));
        }
    }

    #[test]
    fn parse_comma_lists_and_whitespace() {
        let features =
            PreviewFeatures::parse(" hybrid-search,graph-type-implied-labels , local-callables ")
                .unwrap();
        assert!(features.enabled(PreviewFeature::HybridSearch));
        assert!(features.enabled(PreviewFeature::GraphTypeImpliedLabels));
        assert!(features.enabled(PreviewFeature::LocalCallables));
        assert!(!features.enabled(PreviewFeature::GraphTypeOptProps));
        assert!(!features.enabled(PreviewFeature::GraphTypeDefaultValues));
        // A repeated name stays a plain enable, not an error.
        assert_eq!(
            PreviewFeatures::parse("hybrid-search, hybrid-search").unwrap(),
            PreviewFeatures::parse("hybrid-search").unwrap(),
        );
    }

    #[test]
    fn parse_unknown_name_fails_closed_naming_known_names() {
        let error = PreviewFeatures::parse("hybrid-search,bogus").unwrap_err();
        assert!(matches!(error, Error::Semantic(_)), "{error}");
        let display = error.to_string();
        assert!(
            display.contains("unknown preview feature 'bogus'"),
            "{display}"
        );
        for (_, name) in PREVIEW_FEATURE_TABLE {
            assert!(display.contains(name), "{display} misses {name}");
        }
        // An empty segment is an unknown name, not a silent skip.
        let error = PreviewFeatures::parse("hybrid-search,,local-callables").unwrap_err();
        assert!(
            error.to_string().contains("unknown preview feature ''"),
            "{}",
            error
        );
    }

    #[test]
    fn parse_each_registered_name_enables_exactly_that_feature() {
        // Table-driven over the one registry: every row's name parses to a
        // set with exactly that row enabled, so a new row is covered
        // without a new test. (The `ontology` row is ADR-0378's
        // procedure-family exception to ADR-0371's syntax-only scope
        // policy; it needs no special case.)
        for feature in PREVIEW_FEATURES {
            let enabled = PreviewFeatures::parse(feature.kebab_name()).unwrap();
            assert!(enabled.enabled(*feature), "{}", feature.kebab_name());
            for other in PREVIEW_FEATURES {
                if other != feature {
                    assert!(
                        !enabled.enabled(*other),
                        "{} also enabled {}",
                        feature.kebab_name(),
                        other.kebab_name()
                    );
                }
            }
        }
    }

    #[test]
    fn require_gates_with_the_authored_disabled_error() {
        let features = PreviewFeatures::parse("local-callables").unwrap();
        assert!(features.require(PreviewFeature::LocalCallables).is_ok());
        let error = features.require(PreviewFeature::HybridSearch).unwrap_err();
        assert_eq!(
            error.to_string(),
            "semantic error: SemanticError: preview feature 'hybrid-search' is not enabled: \
             set RELATE_PREVIEW=hybrid-search"
        );
        // The disabled text is stable for every registered feature.
        for (feature, name) in PREVIEW_FEATURE_TABLE {
            let error = preview_feature_disabled(*feature);
            assert!(
                error.to_string().ends_with(&format!(
                    "preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}"
                )),
                "{}",
                error
            );
        }
    }

    #[test]
    fn the_sources_union_derives_additively_from_its_parts() {
        // ADR-0719: the parts are the stored fact and the union
        // derives — one feature per source stacks, and a part's
        // removal narrows the derived union the same open would
        // otherwise resolve.
        let sources = PreviewSources {
            env: PreviewFeatures::parse("hybrid-search").unwrap(),
            config: PreviewFeatures::parse("ontology").unwrap(),
            option: PreviewFeatures::parse("local-callables").unwrap(),
        };
        let union = sources.union();
        for feature in [PreviewFeature::HybridSearch, PreviewFeature::Ontology] {
            assert!(union.enabled(feature), "{}", feature.kebab_name());
        }
        // A feature no source carries is off, and an empty set of
        // sources derives nothing.
        assert!(!union.enabled(PreviewFeature::Float16CoordinateTypes));
        assert_eq!(PreviewSources::default().union(), PreviewFeatures::none());
        // The parts stay separable: each source reports only its own.
        assert!(sources.env.enabled(PreviewFeature::HybridSearch));
        assert!(!sources.env.enabled(PreviewFeature::Ontology));
        assert!(sources.config.enabled(PreviewFeature::Ontology));
    }

    #[test]
    fn the_carriers_report_every_enabling_source_in_order() {
        // ADR-0719 decision 6: the provenance names exactly the enabling
        // carriers, in order — and none for a feature no source carries.
        let stacked = PreviewSources {
            env: PreviewFeatures::parse("ontology").unwrap(),
            option: PreviewFeatures::parse("ontology").unwrap(),
            ..PreviewSources::default()
        };
        assert_eq!(
            stacked
                .carriers(PreviewFeature::Ontology)
                .collect::<Vec<_>>(),
            [PreviewSource::Env, PreviewSource::Option]
        );
        assert_eq!(stacked.carriers(PreviewFeature::HybridSearch).count(), 0);
    }

    #[test]
    fn from_names_resolves_each_name_without_the_comma_grammar() {
        // A list item is one name: a comma inside it is an unknown name,
        // never two features (ADR-0719 — the config's typed list).
        let error = PreviewFeatures::from_names("src", ["ontology,coll-zip"]).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("unknown preview feature 'ontology,coll-zip'"),
            "{error}"
        );
        // An empty name is unknown, not skipped; no names enable nothing.
        assert!(PreviewFeatures::from_names("src", [""]).is_err());
        assert_eq!(
            PreviewFeatures::from_names("src", []).unwrap(),
            PreviewFeatures::none()
        );
        assert!(PreviewFeatures::from_names("src", ["ontology", "coll-zip"])
            .unwrap()
            .enabled(PreviewFeature::CollectionZip));
    }
}