mindreader 0.7.0

Selective durable graph memory MCP server for AI agents, backed by Neo4j
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
//! Validated domain values for layer ids, nodes, literals, spikes, and withdrawal width.
//!
//! These types run before Neo4j work: kebab-case layer ids, `node`/`literal`
//! object shapes, predicate IRIs, Spike ranks, and withdrawal scopes. Graph
//! adapters turn the validated values into Cypher parameters.

use crate::iri::{default_lower_for_kind, is_iri, kind_for_label, mint_iri, slugify};
use chrono::{DateTime, SecondsFormat, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use std::fmt;
use thiserror::Error;

/// Caller-facing domain failure: bad input versus violated graph precondition.
#[derive(Debug, Error)]
pub enum DomainError {
    /// Wire or argument validation failed before any graph write.
    #[error("{0}")]
    InvalidInput(String),
    /// The graph exists but the requested handle, membership, or closure is unusable.
    #[error("{0}")]
    Precondition(String),
}

/// Caller-facing half-open world-time interval on an ordinary state fact.
///
/// Presence of the object means the fact is time-qualified. Missing bounds are
/// open; an absent/null object means the fact's effective time is unknown.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct EffectiveInterval {
    /// Inclusive RFC 3339 lower bound.
    #[serde(default)]
    pub from: Option<String>,
    /// Exclusive RFC 3339 upper bound.
    #[serde(default)]
    pub to: Option<String>,
}

/// Canonical UTC effective interval used for identity, persistence, and queries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct NormalizedEffectiveInterval {
    pub(crate) from: Option<String>,
    pub(crate) to: Option<String>,
}

/// Parse one timezone-qualified RFC 3339 instant and canonicalize it to UTC.
pub(crate) fn normalize_rfc3339(value: &str, field: &str) -> Result<String, DomainError> {
    let value = value.trim();
    if value.is_empty() {
        return Err(DomainError::InvalidInput(format!(
            "{field} must be a timezone-qualified RFC 3339 timestamp"
        )));
    }
    let parsed = DateTime::parse_from_rfc3339(value).map_err(|_| {
        DomainError::InvalidInput(format!(
            "{field} must be a timezone-qualified RFC 3339 timestamp"
        ))
    })?;
    Ok(parsed
        .with_timezone(&Utc)
        .to_rfc3339_opts(SecondsFormat::AutoSi, true))
}

impl EffectiveInterval {
    /// Canonicalize both optional bounds and enforce half-open `from < to`.
    pub(crate) fn normalize(self, field: &str) -> Result<NormalizedEffectiveInterval, DomainError> {
        let from = self
            .from
            .as_deref()
            .map(|value| normalize_rfc3339(value, &format!("{field}.from")))
            .transpose()?;
        let to = self
            .to
            .as_deref()
            .map(|value| normalize_rfc3339(value, &format!("{field}.to")))
            .transpose()?;
        if let (Some(from), Some(to)) = (&from, &to) {
            let from_value =
                DateTime::parse_from_rfc3339(from).expect("normalized effective.from must parse");
            let to_value =
                DateTime::parse_from_rfc3339(to).expect("normalized effective.to must parse");
            if from_value >= to_value {
                return Err(DomainError::InvalidInput(format!(
                    "{field}.from must be earlier than {field}.to"
                )));
            }
        }
        Ok(NormalizedEffectiveInterval { from, to })
    }
}

/// Revision-specific effective-time update: omission inherits, null clears, object replaces.
#[derive(Debug, Clone, Default, JsonSchema)]
pub enum EffectiveUpdate {
    /// Field omitted: preserve the selected fact's complete interval.
    #[default]
    Inherit,
    /// Explicit JSON null: make effective time unknown.
    Clear,
    /// Explicit interval object: replace the complete interval.
    Set(EffectiveInterval),
}

impl<'de> Deserialize<'de> for EffectiveUpdate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Option::<EffectiveInterval>::deserialize(deserializer)
            .map(|value| value.map_or(Self::Clear, Self::Set))
    }
}

/// A validated graph visibility layer identifier.
///
/// Layer identifiers consist of lowercase kebab-case segments separated by
/// colons, for example `project:mindreader` or `team:platform:graph-memory`.
/// Global visibility is represented by an empty membership list.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, JsonSchema)]
#[schemars(transparent)]
pub struct LayerId(String);

impl LayerId {
    /// Parse a kebab-case colon-namespaced id; the token `global` is invalid (use `[]`).
    pub fn parse(value: impl Into<String>) -> Result<Self, DomainError> {
        let value = value.into();
        if value == "global" || !is_valid_layer_id(&value) {
            return Err(DomainError::InvalidInput(format!(
                "invalid layer {value:?}: expected lowercase kebab-case segments separated by colons; use an empty layer list for global visibility"
            )));
        }
        Ok(Self(value))
    }

    /// Borrow the validated kebab-case colon-namespaced id.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the wrapper and return the validated id string.
    pub fn into_string(self) -> String {
        self.0
    }
}

/// True when every colon-separated segment is lowercase kebab-case (no empty, edge, or double dashes).
fn is_valid_layer_id(value: &str) -> bool {
    value.split(':').all(|segment| {
        !segment.is_empty()
            && !segment.starts_with('-')
            && !segment.ends_with('-')
            && !segment.contains("--")
            && segment
                .bytes()
                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
    })
}

impl fmt::Display for LayerId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl AsRef<str> for LayerId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl TryFrom<String> for LayerId {
    type Error = DomainError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl TryFrom<&str> for LayerId {
    type Error = DomainError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl Serialize for LayerId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for LayerId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::parse(value).map_err(serde::de::Error::custom)
    }
}

/// Canonical property IRI for a fact predicate (accepts local names or full IRIs).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PredicateRef(String);

impl PredicateRef {
    /// Canonicalize a local name or IRI into a property IRI with a nonempty local name.
    pub fn parse(value: impl Into<String>) -> Result<Self, DomainError> {
        let value = value.into();
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Err(DomainError::InvalidInput(
                "predicate cannot be empty".into(),
            ));
        }
        if trimmed.contains(':') && !is_iri(trimmed) {
            return Err(DomainError::InvalidInput(format!(
                "predicate must be a local name or complete scheme-qualified IRI, not {trimmed:?}"
            )));
        }
        let iri = crate::iri::property_iri(trimmed);
        if crate::iri::name_from_iri(&iri).trim().is_empty() {
            return Err(DomainError::InvalidInput(format!(
                "predicate has no local name: {trimmed:?}"
            )));
        }
        Ok(Self(iri))
    }

    /// Canonical `mindreader:property/…` IRI (or the caller-supplied qualified IRI).
    pub fn iri(&self) -> &str {
        &self.0
    }
}

/// Pasteable node handle used by `unify`.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NodeHandle {
    /// Must be `"node"`; relationship IRIs are rejected by [`Self::iri`].
    pub kind: String,
    /// Scheme-qualified node IRI (not `mindreader:relationship/…`).
    pub iri: String,
}

impl NodeHandle {
    /// Build a `{kind: node, iri}` handle; IRI checks happen in [`Self::iri`].
    #[cfg(feature = "developer-tools")]
    pub fn from_iri(iri: impl Into<String>) -> Self {
        Self {
            kind: "node".into(),
            iri: iri.into(),
        }
    }

    /// Return the node IRI after rejecting non-node kinds and relationship IRIs.
    pub fn iri(&self) -> Result<&str, DomainError> {
        if self.kind != "node" {
            return Err(DomainError::InvalidInput(
                "unify source and target kind must be \"node\"".into(),
            ));
        }
        let iri = self.iri.trim();
        if iri.is_empty() || !is_iri(iri) || iri.starts_with("mindreader:relationship/") {
            return Err(DomainError::InvalidInput(format!(
                "unify requires a node IRI, not {:?}",
                self.iri
            )));
        }
        Ok(iri)
    }
}

/// Wire-shape subject for writes: `kind` must be `"node"`, plus `iri` or `name`.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct EntityInput {
    /// Must be `"node"`; literals use [`ObjectInput`].
    pub kind: String,
    /// Optional scheme-qualified node IRI; when omitted, `name` is minted.
    #[serde(default)]
    pub iri: Option<String>,
    /// Display name used to mint an IRI when `iri` is absent.
    #[serde(default)]
    pub name: Option<String>,
    /// Extra Neo4j labels; identity kind still prefers Class/Property/Element.
    #[serde(default)]
    pub labels: Vec<String>,
}

/// Wire-shape object: one tagged bag (`node` or `literal`) without schema unions.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ObjectInput {
    /// `"node"` or `"literal"`; mixed fields fail during input validation.
    pub kind: String,
    /// Node IRI when `kind=node`; forbidden on literals.
    #[serde(default)]
    pub iri: Option<String>,
    /// Node display name when `kind=node`; forbidden on literals.
    #[serde(default)]
    pub name: Option<String>,
    /// Extra Neo4j labels when `kind=node`; forbidden on literals.
    #[serde(default)]
    pub labels: Vec<String>,
    /// Literal lexical form; forbidden on `kind=node`.
    #[serde(default)]
    pub value: Option<String>,
    /// Literal datatype; defaults to `xsd:string` when omitted.
    #[serde(default)]
    pub datatype: Option<String>,
}

/// Validated node reference after `kind=node` and IRI/name checks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntityRef {
    /// Explicit scheme-qualified IRI when the caller supplied one.
    pub iri: Option<String>,
    /// Display name used to mint an IRI when `iri` is absent.
    pub name: Option<String>,
    /// Extra Neo4j labels; identity kind still prefers Class/Property/Element.
    pub labels: Vec<String>,
}

impl EntityRef {
    /// Require `kind=node` and at least one of `iri` or `name`.
    pub fn from_input(input: EntityInput) -> Result<Self, DomainError> {
        if input.kind != "node" {
            return Err(DomainError::InvalidInput(
                "node input kind must be \"node\"".into(),
            ));
        }
        validate_entity_parts(input.iri, input.name, input.labels)
    }

    /// Prefer an explicit IRI; otherwise mint from name, labels, and kind defaults.
    pub fn resolved_iri(&self, fallback_kind: &str) -> String {
        if let Some(iri) = &self.iri {
            return iri.clone();
        }
        let kind = crate::iri::identity_kind_from_labels(&self.labels)
            .and_then(kind_for_label)
            .unwrap_or(fallback_kind);
        mint_iri(
            kind,
            self.name.as_deref().expect("validated entity has a name"),
            default_lower_for_kind(kind),
        )
    }
}

/// Validated fact object: a node reference or a typed literal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ObjectValue {
    /// Validated node object after `kind=node` checks.
    Entity(EntityRef),
    /// Typed literal; identity is the deterministic literal IRI.
    Literal { value: String, datatype: String },
}

impl ObjectValue {
    /// Accept a tagged `node` or `literal` bag and reject mixed fields.
    pub fn from_input(input: ObjectInput) -> Result<Self, DomainError> {
        match input.kind.as_str() {
            "node" => {
                if input.value.is_some() || input.datatype.is_some() {
                    return Err(DomainError::InvalidInput(
                        "node objects cannot contain value or datatype".into(),
                    ));
                }
                Ok(Self::Entity(validate_entity_parts(
                    input.iri,
                    input.name,
                    input.labels,
                )?))
            }
            "literal" => {
                if input.iri.is_some() || input.name.is_some() || !input.labels.is_empty() {
                    return Err(DomainError::InvalidInput(
                        "literal objects cannot contain iri, name, or labels".into(),
                    ));
                }
                let value = input.value.ok_or_else(|| {
                    DomainError::InvalidInput("literal objects require value".into())
                })?;
                let datatype = input.datatype.unwrap_or_else(|| "xsd:string".into());
                if datatype.trim().is_empty() {
                    return Err(DomainError::InvalidInput(
                        "literal datatype cannot be empty".into(),
                    ));
                }
                Ok(Self::Literal { value, datatype })
            }
            other => Err(DomainError::InvalidInput(format!(
                "object kind must be node or literal, got {other:?}"
            ))),
        }
    }

    /// Entity IRI via [`EntityRef::resolved_iri`], or a deterministic literal IRI.
    pub fn resolved_iri(&self) -> String {
        match self {
            Self::Entity(entity) => entity.resolved_iri("element"),
            Self::Literal { value, datatype } => literal_iri(value, datatype),
        }
    }
}

/// Require a non-empty IRI or name, a scheme-qualified IRI when present, and ASCII label tokens.
fn validate_entity_parts(
    iri: Option<String>,
    name: Option<String>,
    labels: Vec<String>,
) -> Result<EntityRef, DomainError> {
    let iri = iri.filter(|value| !value.trim().is_empty());
    let name = name.filter(|value| !value.trim().is_empty());
    if iri.is_none() && name.is_none() {
        return Err(DomainError::InvalidInput(
            "node input requires iri or name".into(),
        ));
    }
    if let Some(value) = &iri {
        if !is_iri(value) {
            return Err(DomainError::InvalidInput(format!(
                "invalid entity IRI: {value}"
            )));
        }
    }
    for label in &labels {
        let Some(first) = label.chars().next() else {
            return Err(DomainError::InvalidInput(
                "entity labels cannot be empty".into(),
            ));
        };
        if !first.is_ascii_alphabetic()
            || !label
                .chars()
                .all(|character| character.is_ascii_alphanumeric() || character == '_')
        {
            return Err(DomainError::InvalidInput(format!(
                "invalid entity label: {label:?}"
            )));
        }
    }
    Ok(EntityRef { iri, name, labels })
}

/// Deterministic `mindreader:literal/…` IRI from datatype and value content.
pub fn literal_iri(value: &str, datatype: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(format!("{datatype}:{value}").as_bytes());
    let digest = hasher.finalize();
    let hex: String = digest
        .iter()
        .take(6)
        .map(|byte| format!("{byte:02x}"))
        .collect();
    let slug = slugify(value, true);
    let slug = if slug.len() > 40 { &slug[..40] } else { &slug };
    format!("mindreader:literal/{slug}-{hex}")
}

/// Epistemic fact classification used in retrieval ranking (Knowledge highest).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpikeRank {
    /// Lowest ranked ordinary assertion.
    Signal,
    /// Recurring observation above a lone signal.
    Pattern,
    /// Interpreted finding above a pattern.
    Insight,
    /// Highest ranked asserted knowledge.
    Knowledge,
}

impl SpikeRank {
    /// Parse an optional Spike label; omitted means the fact is unranked.
    pub fn parse(value: Option<String>) -> Result<Option<Self>, DomainError> {
        value
            .map(|value| match value.as_str() {
                "Signal" => Ok(Self::Signal),
                "Pattern" => Ok(Self::Pattern),
                "Insight" => Ok(Self::Insight),
                "Knowledge" => Ok(Self::Knowledge),
                _ => Err(DomainError::InvalidInput(
                    "spike must be one of Signal|Pattern|Insight|Knowledge".into(),
                )),
            })
            .transpose()
    }

    /// Stored fact value used in ranking (`Knowledge` highest).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Signal => "Signal",
            Self::Pattern => "Pattern",
            Self::Insight => "Insight",
            Self::Knowledge => "Knowledge",
        }
    }
}

/// Soft-withdrawal width for `withdraw`: one fact, a predicate slice, or a subject.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WithdrawalScope {
    /// Soft-withdraw only the selected fact handle (`validTo`).
    Fact,
    /// Soft-withdraw every current fact for that subject and predicate.
    Predicate,
    /// Soft-withdraw every current ordinary fact for that subject.
    Subject,
}

impl WithdrawalScope {
    /// Parse withdrawal width: `fact`, `predicate`, or `subject`.
    pub fn parse(value: &str) -> Result<Self, DomainError> {
        match value {
            "fact" => Ok(Self::Fact),
            "predicate" => Ok(Self::Predicate),
            "subject" => Ok(Self::Subject),
            _ => Err(DomainError::InvalidInput(
                "withdrawal target kind must be fact, predicate, or subject".into(),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        literal_iri, normalize_rfc3339, EffectiveInterval, EntityInput, EntityRef, LayerId,
        NodeHandle, ObjectInput, ObjectValue, PredicateRef,
    };

    #[test]
    fn layer_ids_use_lowercase_colon_separated_kebab_case() {
        for valid in [
            "project:mindreader",
            "project:graph-memory",
            "team2:platform-7:memory",
        ] {
            assert_eq!(LayerId::parse(valid).unwrap().as_str(), valid);
        }

        for invalid in [
            "",
            "global",
            "Global",
            "project:",
            ":project",
            "project::memory",
            "project:graph_memory",
            "project:graph memory",
            "project:-graph",
            "project:graph-",
            "project:graph--memory",
        ] {
            assert!(LayerId::parse(invalid).is_err(), "accepted {invalid:?}");
        }
    }

    #[test]
    fn layer_ids_validate_during_deserialization() {
        assert_eq!(
            serde_json::from_str::<LayerId>(r#""project:graph-memory""#)
                .unwrap()
                .as_str(),
            "project:graph-memory"
        );
        assert!(serde_json::from_str::<LayerId>(r#""project:Graph""#).is_err());
    }

    #[test]
    fn tagged_inputs_reject_ambiguous_shapes() {
        assert!(EntityRef::from_input(EntityInput {
            kind: "literal".into(),
            iri: None,
            name: Some("x".into()),
            labels: vec![],
        })
        .is_err());
        assert!(serde_json::from_value::<EntityInput>(serde_json::json!({
            "kind": "node",
            "name": "x",
            "weight": 0
        }))
        .is_err());
        assert!(serde_json::from_value::<ObjectInput>(serde_json::json!({
            "kind": "literal",
            "value": "x",
            "relationship": {"iri": "legacy"}
        }))
        .is_err());
        assert!(serde_json::from_value::<NodeHandle>(serde_json::json!({
            "kind": "node",
            "iri": "mindreader:element/x",
            "name": "x"
        }))
        .is_err());
        assert!(ObjectValue::from_input(ObjectInput {
            kind: "literal".into(),
            iri: Some("mindreader:element/x".into()),
            name: None,
            labels: vec![],
            value: Some("x".into()),
            datatype: None,
        })
        .is_err());
    }

    #[test]
    fn literal_identity_is_stable_and_datatype_sensitive() {
        assert_eq!(
            literal_iri("42", "xsd:integer"),
            literal_iri("42", "xsd:integer")
        );
        assert_ne!(
            literal_iri("42", "xsd:integer"),
            literal_iri("42", "xsd:string")
        );
    }

    #[test]
    fn predicates_are_nonempty_and_canonical() {
        assert!(PredicateRef::parse("   ").is_err());
        assert_eq!(
            PredicateRef::parse(" worksOn ").unwrap().iri(),
            "mindreader:property/worksOn"
        );
        assert!(PredicateRef::parse("mindreader:").is_err());
    }

    #[test]
    fn effective_intervals_are_canonical_half_open_rfc3339_ranges() {
        let interval = EffectiveInterval {
            from: Some("2024-01-01T01:00:00+01:00".into()),
            to: Some("2025-01-01T00:00:00Z".into()),
        }
        .normalize("effective")
        .unwrap();
        assert_eq!(interval.from.as_deref(), Some("2024-01-01T00:00:00Z"));
        assert_eq!(interval.to.as_deref(), Some("2025-01-01T00:00:00Z"));
        assert!(EffectiveInterval {
            from: Some("2025-01-01T00:00:00Z".into()),
            to: Some("2025-01-01T00:00:00Z".into()),
        }
        .normalize("effective")
        .is_err());
        assert!(normalize_rfc3339("2025-01-01", "effectiveAt").is_err());
        assert!(EffectiveInterval {
            from: None,
            to: None,
        }
        .normalize("effective")
        .is_ok());
    }
}