eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
//! Memory revision tracking (EE-067).
//!
//! Types for tracking memory revisions, supersession chains, and
//! legal hold constraints. These enable:
//!
//! * **Revision groups**: Multiple versions of the same logical memory
//!   share a group ID, enabling history queries and rollback.
//! * **Supersession links**: Explicit pointers from a new memory to
//!   the one it replaces, forming a directed acyclic graph.
//! * **Idempotency keys**: Prevent duplicate imports from external
//!   sources (CASS sessions, agent hooks).
//! * **Legal holds**: Mark memories that must not be deleted or
//!   modified, with audit trail.
//!
//! The revision model follows these invariants:
//! - A revision group ID is stable across all versions of a memory.
//! - Supersession forms a DAG (no cycles allowed).
//! - At most one memory in a group can be "current" (not superseded).
//! - Legal holds are append-only; they can only be released, not modified.

use std::{convert::Infallible, fmt};

use serde::{Deserialize, Serialize};

fn normalized_supersession_reason_token(input: &str) -> String {
    let trimmed = input.trim();
    let mut normalized = String::with_capacity(trimmed.len());
    let mut previous_was_lowercase = false;
    let mut previous_was_separator = false;

    for character in trimmed.chars() {
        match character {
            '-' | '_' => {
                if !normalized.is_empty() && !previous_was_separator {
                    normalized.push('_');
                }
                previous_was_lowercase = false;
                previous_was_separator = true;
            }
            character if character.is_ascii_uppercase() => {
                if previous_was_lowercase && !previous_was_separator {
                    normalized.push('_');
                }
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = false;
                previous_was_separator = false;
            }
            character => {
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = character.is_ascii_lowercase();
                previous_was_separator = false;
            }
        }
    }

    normalized
}

/// Prefix for revision group IDs.
pub const REVISION_GROUP_PREFIX: &str = "rev_";

/// Expected length for revision group IDs (prefix + 25 chars = 29 total).
pub const REVISION_GROUP_ID_LEN: usize = 29;

/// Prefix for legal hold IDs.
pub const LEGAL_HOLD_PREFIX: &str = "hold_";

/// Expected length for legal hold IDs (prefix + 25 chars = 30 total).
pub const LEGAL_HOLD_ID_LEN: usize = 30;

/// Opaque content/index corpus revision stamp.
///
/// Unlike [`RevisionGroupId`], this is not a memory-history identifier. It is
/// a caller-supplied or derived stamp for the corpus a cache, prefetch history,
/// or derived index was measured against. Consumers compare it for exact
/// equality only; the inner string intentionally has no semantics outside the
/// producer that minted it.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub struct CorpusRevision(String);

impl CorpusRevision {
    /// Sentinel for legacy or not-yet-measured data. Revision-aware gates treat
    /// this as incoherent with any non-empty live corpus revision.
    pub const UNKNOWN: &'static str = "unknown";

    #[must_use]
    pub fn new(raw: impl Into<String>) -> Self {
        let raw = raw.into();
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            Self::unknown()
        } else {
            Self(trimmed.to_owned())
        }
    }

    #[must_use]
    pub fn unknown() -> Self {
        Self(Self::UNKNOWN.to_owned())
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    pub fn is_unknown(&self) -> bool {
        self.0 == Self::UNKNOWN
    }

    #[must_use]
    pub fn is_coherent_with(&self, current: &Self) -> bool {
        !self.is_unknown() && !current.is_unknown() && self == current
    }
}

impl Default for CorpusRevision {
    fn default() -> Self {
        Self::unknown()
    }
}

impl From<&str> for CorpusRevision {
    fn from(raw: &str) -> Self {
        Self::new(raw)
    }
}

impl From<String> for CorpusRevision {
    fn from(raw: String) -> Self {
        Self::new(raw)
    }
}

impl From<CorpusRevision> for String {
    fn from(revision: CorpusRevision) -> Self {
        revision.0
    }
}

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

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

/// Error validating a revision or hold ID.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RevisionIdError {
    /// ID has wrong prefix.
    WrongPrefix {
        input: String,
        expected: &'static str,
    },
    /// ID has wrong length.
    WrongLength {
        input: String,
        expected: usize,
        actual: usize,
    },
}

impl fmt::Display for RevisionIdError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::WrongPrefix { input, expected } => {
                write!(f, "ID `{input}` must start with `{expected}`")
            }
            Self::WrongLength {
                input,
                expected,
                actual,
            } => {
                write!(f, "ID `{input}` has length {actual}, expected {expected}")
            }
        }
    }
}

impl std::error::Error for RevisionIdError {}

/// A validated revision group ID.
///
/// All versions of a memory share the same revision group ID, enabling
/// history queries ("show me all versions of this memory") and rollback.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct RevisionGroupId(String);

impl RevisionGroupId {
    /// Parse and validate a revision group ID.
    ///
    /// # Errors
    ///
    /// Returns error if the ID doesn't match `rev_*` pattern with correct length.
    pub fn parse(input: impl Into<String>) -> Result<Self, RevisionIdError> {
        let id = input.into();
        if !id.starts_with(REVISION_GROUP_PREFIX) {
            return Err(RevisionIdError::WrongPrefix {
                input: id,
                expected: REVISION_GROUP_PREFIX,
            });
        }
        if id.len() != REVISION_GROUP_ID_LEN {
            return Err(RevisionIdError::WrongLength {
                input: id.clone(),
                expected: REVISION_GROUP_ID_LEN,
                actual: id.len(),
            });
        }
        Ok(Self(id))
    }

    /// Create from a string that's already been validated.
    ///
    /// # Panics
    ///
    /// Panics in debug mode if the ID is invalid. Use `parse` for untrusted input.
    #[must_use]
    pub fn from_trusted(id: impl Into<String>) -> Self {
        let id = id.into();
        debug_assert!(
            id.starts_with(REVISION_GROUP_PREFIX) && id.len() == REVISION_GROUP_ID_LEN,
            "invalid revision group ID: {id}"
        );
        Self(id)
    }

    /// The raw ID string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

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

/// A validated legal hold ID.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct LegalHoldId(String);

impl LegalHoldId {
    /// Parse and validate a legal hold ID.
    pub fn parse(input: impl Into<String>) -> Result<Self, RevisionIdError> {
        let id = input.into();
        if !id.starts_with(LEGAL_HOLD_PREFIX) {
            return Err(RevisionIdError::WrongPrefix {
                input: id,
                expected: LEGAL_HOLD_PREFIX,
            });
        }
        if id.len() != LEGAL_HOLD_ID_LEN {
            return Err(RevisionIdError::WrongLength {
                input: id.clone(),
                expected: LEGAL_HOLD_ID_LEN,
                actual: id.len(),
            });
        }
        Ok(Self(id))
    }

    /// Create from a trusted string.
    #[must_use]
    pub fn from_trusted(id: impl Into<String>) -> Self {
        let id = id.into();
        debug_assert!(
            id.starts_with(LEGAL_HOLD_PREFIX) && id.len() == LEGAL_HOLD_ID_LEN,
            "invalid legal hold ID: {id}"
        );
        Self(id)
    }

    /// The raw ID string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

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

/// Supersession relationship between memories.
///
/// Records that a newer memory supersedes an older one, preserving
/// the full history chain for audit and rollback.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SupersessionLink {
    /// Memory ID being superseded (older version).
    pub superseded_id: String,
    /// Memory ID doing the superseding (newer version).
    pub superseding_id: String,
    /// Why this supersession happened.
    pub reason: SupersessionReason,
    /// Timestamp when the supersession was recorded.
    pub created_at: String,
}

impl SupersessionLink {
    /// Create a new supersession link.
    #[must_use]
    pub fn new(
        superseded_id: impl Into<String>,
        superseding_id: impl Into<String>,
        reason: SupersessionReason,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            superseded_id: superseded_id.into(),
            superseding_id: superseding_id.into(),
            reason,
            created_at: created_at.into(),
        }
    }
}

/// Why one memory supersedes another.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum SupersessionReason {
    /// User explicitly updated the memory.
    #[default]
    UserUpdate,
    /// Memory was refined through curation.
    Curation,
    /// Memory was consolidated with others.
    Consolidation,
    /// Memory was corrected due to feedback.
    Correction,
    /// Memory was imported from an external source.
    Import,
    /// Memory was auto-generated by the system.
    SystemGenerated,
}

impl SupersessionReason {
    /// Stable string representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::UserUpdate => "user_update",
            Self::Curation => "curation",
            Self::Consolidation => "consolidation",
            Self::Correction => "correction",
            Self::Import => "import",
            Self::SystemGenerated => "system_generated",
        }
    }

    /// Parse from string.
    #[must_use]
    pub fn parse_lossy(s: &str) -> Self {
        match normalized_supersession_reason_token(s).as_str() {
            "user_update" | "update" => Self::UserUpdate,
            "curation" => Self::Curation,
            "consolidation" => Self::Consolidation,
            "correction" => Self::Correction,
            "import" => Self::Import,
            "system_generated" => Self::SystemGenerated,
            _ => Self::UserUpdate,
        }
    }
}

impl std::str::FromStr for SupersessionReason {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::parse_lossy(s))
    }
}

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

/// Idempotency key for preventing duplicate imports.
///
/// External sources (CASS sessions, hooks) provide a key that uniquely
/// identifies the import operation. Re-importing with the same key is
/// a no-op rather than creating duplicate memories.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct IdempotencyKey(String);

impl IdempotencyKey {
    /// Maximum length for an idempotency key.
    pub const MAX_LEN: usize = 128;

    /// Create a new idempotency key.
    ///
    /// # Errors
    ///
    /// Returns error if key is empty or exceeds max length.
    pub fn new(key: impl Into<String>) -> Result<Self, IdempotencyKeyError> {
        let key = key.into();
        if key.is_empty() {
            return Err(IdempotencyKeyError::Empty);
        }
        if key.len() > Self::MAX_LEN {
            return Err(IdempotencyKeyError::TooLong {
                len: key.len(),
                max: Self::MAX_LEN,
            });
        }
        Ok(Self(key))
    }

    /// The raw key string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

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

/// Errors validating an idempotency key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IdempotencyKeyError {
    /// Key is empty.
    Empty,
    /// Key exceeds maximum length.
    TooLong { len: usize, max: usize },
}

impl fmt::Display for IdempotencyKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "idempotency key cannot be empty"),
            Self::TooLong { len, max } => {
                write!(f, "idempotency key too long: {len} bytes (max {max})")
            }
        }
    }
}

impl std::error::Error for IdempotencyKeyError {}

/// Legal hold on a memory.
///
/// Prevents deletion or modification of a memory for compliance,
/// audit, or litigation purposes. Legal holds are append-only:
/// they can be released but not modified.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LegalHold {
    /// Unique ID for this hold.
    pub hold_id: LegalHoldId,
    /// Memory ID under hold.
    pub memory_id: String,
    /// Reason for the hold (free text, auditable).
    pub reason: String,
    /// Who placed the hold.
    pub placed_by: String,
    /// When the hold was placed.
    pub placed_at: String,
    /// When the hold was released (if released).
    pub released_at: Option<String>,
    /// Who released the hold.
    pub released_by: Option<String>,
}

impl LegalHold {
    /// Create a new active legal hold.
    #[must_use]
    pub fn new(
        hold_id: LegalHoldId,
        memory_id: impl Into<String>,
        reason: impl Into<String>,
        placed_by: impl Into<String>,
        placed_at: impl Into<String>,
    ) -> Self {
        Self {
            hold_id,
            memory_id: memory_id.into(),
            reason: reason.into(),
            placed_by: placed_by.into(),
            placed_at: placed_at.into(),
            released_at: None,
            released_by: None,
        }
    }

    /// Whether this hold is currently active.
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.released_at.is_none()
    }

    /// Release this hold.
    #[must_use]
    pub fn release(
        mut self,
        released_by: impl Into<String>,
        released_at: impl Into<String>,
    ) -> Self {
        self.released_by = Some(released_by.into());
        self.released_at = Some(released_at.into());
        self
    }
}

/// Memory revision metadata.
///
/// Tracks version history for a memory, enabling history queries
/// and rollback operations.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RevisionMeta {
    /// Revision group ID (stable across versions).
    pub group_id: RevisionGroupId,
    /// Version number within the group (1 = first version).
    pub version: u32,
    /// Memory ID this version supersedes (if any).
    pub supersedes: Option<String>,
    /// Whether this is the current (active) version.
    pub is_current: bool,
    /// Idempotency key for this revision (if imported).
    pub idempotency_key: Option<IdempotencyKey>,
}

impl RevisionMeta {
    /// Create metadata for the first version of a memory.
    #[must_use]
    pub fn first(group_id: RevisionGroupId) -> Self {
        Self {
            group_id,
            version: 1,
            supersedes: None,
            is_current: true,
            idempotency_key: None,
        }
    }

    /// Create metadata for a subsequent version.
    #[must_use]
    pub fn subsequent(
        group_id: RevisionGroupId,
        version: u32,
        supersedes: impl Into<String>,
    ) -> Self {
        Self {
            group_id,
            version,
            supersedes: Some(supersedes.into()),
            is_current: true,
            idempotency_key: None,
        }
    }

    /// Builder: set idempotency key.
    #[must_use]
    pub fn with_idempotency_key(mut self, key: IdempotencyKey) -> Self {
        self.idempotency_key = Some(key);
        self
    }

    /// Builder: mark as not current (superseded).
    #[must_use]
    pub fn as_superseded(mut self) -> Self {
        self.is_current = false;
        self
    }
}

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

    type TestResult = Result<(), String>;

    #[test]
    fn corpus_revision_is_opaque_and_unknown_is_incoherent() {
        let revision = CorpusRevision::new(" corpus:v1 ");
        assert_eq!(revision.as_str(), "corpus:v1");
        assert!(revision.is_coherent_with(&CorpusRevision::from("corpus:v1")));
        assert!(!revision.is_coherent_with(&CorpusRevision::from("corpus:v2")));
        assert!(!CorpusRevision::unknown().is_coherent_with(&revision));
        assert!(!revision.is_coherent_with(&CorpusRevision::unknown()));
        assert!(CorpusRevision::new("").is_unknown());
    }

    fn ensure_equal<T: std::fmt::Debug + PartialEq>(
        actual: &T,
        expected: &T,
        context: &str,
    ) -> TestResult {
        if actual == expected {
            Ok(())
        } else {
            Err(format!("{context}: expected {expected:?}, got {actual:?}"))
        }
    }

    #[test]
    fn revision_group_id_validates_format() -> TestResult {
        let valid = RevisionGroupId::parse("rev_test000000000000000000000");
        assert!(valid.is_ok(), "valid ID should parse");

        let wrong_prefix = RevisionGroupId::parse("mem_test000000000000000000000");
        assert!(wrong_prefix.is_err(), "wrong prefix should fail");

        let too_short = RevisionGroupId::parse("rev_abc");
        assert!(too_short.is_err(), "too short should fail");

        Ok(())
    }

    #[test]
    fn legal_hold_id_validates_format() -> TestResult {
        let valid = LegalHoldId::parse("hold_test000000000000000000000");
        assert!(valid.is_ok(), "valid ID should parse");

        let wrong_prefix = LegalHoldId::parse("rev_test0000000000000000000");
        assert!(wrong_prefix.is_err(), "wrong prefix should fail");

        Ok(())
    }

    #[test]
    fn supersession_reason_strings_are_stable() -> TestResult {
        ensure_equal(
            &SupersessionReason::UserUpdate.as_str(),
            &"user_update",
            "user_update",
        )?;
        ensure_equal(
            &SupersessionReason::Curation.as_str(),
            &"curation",
            "curation",
        )?;
        ensure_equal(
            &SupersessionReason::Consolidation.as_str(),
            &"consolidation",
            "consolidation",
        )?;
        ensure_equal(
            &SupersessionReason::Correction.as_str(),
            &"correction",
            "correction",
        )?;
        ensure_equal(&SupersessionReason::Import.as_str(), &"import", "import")?;
        ensure_equal(
            &SupersessionReason::SystemGenerated.as_str(),
            &"system_generated",
            "system_generated",
        )
    }

    #[test]
    fn supersession_reason_round_trips() {
        for reason in [
            SupersessionReason::UserUpdate,
            SupersessionReason::Curation,
            SupersessionReason::Consolidation,
            SupersessionReason::Correction,
            SupersessionReason::Import,
            SupersessionReason::SystemGenerated,
        ] {
            let parsed = SupersessionReason::parse_lossy(reason.as_str());
            assert_eq!(reason, parsed, "round trip failed for {reason:?}");
        }
    }

    #[test]
    fn supersession_reason_parse_lossy_normalizes_external_values() {
        assert_eq!(
            SupersessionReason::parse_lossy("user-update"),
            SupersessionReason::UserUpdate
        );
        assert_eq!(
            SupersessionReason::parse_lossy(" update "),
            SupersessionReason::UserUpdate
        );
        assert_eq!(
            SupersessionReason::parse_lossy(" Correction "),
            SupersessionReason::Correction
        );
        assert_eq!(
            SupersessionReason::parse_lossy("system-generated"),
            SupersessionReason::SystemGenerated
        );
        assert_eq!(
            SupersessionReason::parse_lossy(" SYSTEM_GENERATED "),
            SupersessionReason::SystemGenerated
        );
        assert_eq!(
            SupersessionReason::parse_lossy("systemGenerated"),
            SupersessionReason::SystemGenerated
        );
        assert_eq!(
            SupersessionReason::parse_lossy("UserUpdate"),
            SupersessionReason::UserUpdate
        );
    }

    #[test]
    fn idempotency_key_validates_length() {
        let valid = IdempotencyKey::new("import-session-abc123");
        assert!(valid.is_ok(), "valid key should work");

        let empty = IdempotencyKey::new("");
        assert!(
            matches!(empty, Err(IdempotencyKeyError::Empty)),
            "empty key should fail"
        );

        let too_long = IdempotencyKey::new("x".repeat(200));
        assert!(
            matches!(too_long, Err(IdempotencyKeyError::TooLong { .. })),
            "too long key should fail"
        );
    }

    #[test]
    fn legal_hold_lifecycle() {
        let hold_id = LegalHoldId::from_trusted("hold_test000000000000000000000");
        let hold = LegalHold::new(
            hold_id,
            "mem_test000000000000000000000",
            "Litigation hold",
            "legal@example.com",
            "2026-01-01T00:00:00Z",
        );

        assert!(hold.is_active(), "new hold should be active");

        let released = hold.release("legal@example.com", "2026-02-01T00:00:00Z");
        assert!(!released.is_active(), "released hold should not be active");
        assert_eq!(
            released.released_at,
            Some("2026-02-01T00:00:00Z".to_string())
        );
    }

    #[test]
    fn revision_meta_version_tracking() {
        let group_id = RevisionGroupId::from_trusted("rev_test000000000000000000000");

        let first = RevisionMeta::first(group_id.clone());
        assert_eq!(first.version, 1);
        assert!(first.is_current);
        assert!(first.supersedes.is_none());

        let second = RevisionMeta::subsequent(group_id.clone(), 2, "mem_v1");
        assert_eq!(second.version, 2);
        assert!(second.is_current);
        assert_eq!(second.supersedes, Some("mem_v1".to_string()));

        let superseded = first.as_superseded();
        assert!(!superseded.is_current);
    }

    #[test]
    fn revision_meta_with_idempotency_key() -> TestResult {
        let group_id = RevisionGroupId::from_trusted("rev_test000000000000000000000");
        let key = IdempotencyKey::new("import-xyz")
            .map_err(|error| format!("valid key should parse: {error}"))?;

        let meta = RevisionMeta::first(group_id).with_idempotency_key(key);
        assert!(meta.idempotency_key.is_some());
        ensure_equal(
            &meta.idempotency_key.as_ref().map(IdempotencyKey::as_str),
            &Some("import-xyz"),
            "idempotency key",
        )
    }

    #[test]
    fn supersession_link_creation() {
        let link = SupersessionLink::new(
            "mem_old",
            "mem_new",
            SupersessionReason::Curation,
            "2026-01-01T00:00:00Z",
        );

        assert_eq!(link.superseded_id, "mem_old");
        assert_eq!(link.superseding_id, "mem_new");
        assert_eq!(link.reason, SupersessionReason::Curation);
    }
}