KiThe 0.3.24

A numerical suite for chemical kinetics and thermodynamics, combustion, TGA, heat and mass transfer,chemical equilibrium, chemical engeneering
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! Typed metadata contracts for the experimental-kinetics catalog.
//!
//! The catalog indexes experiments, series, immutable processing publications,
//! and external files. It does not own numeric frames or replace typed KiThe
//! documents. Persistence and synchronization are implemented by adapters.

pub mod client;
mod store;
pub use store::{
    ArtifactHashProgress, CatalogStore, CatalogStoreError, LocalArtifactIntegrity,
    LocalArtifactResolution, source_kind_from_lineage,
};

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CatalogId(String);

impl CatalogId {
    pub fn new() -> Self {
        Self(uuid::Uuid::new_v4().to_string())
    }

    pub fn parse(value: impl Into<String>) -> Result<Self, CatalogValidationError> {
        let value = value.into();
        if uuid::Uuid::parse_str(&value).is_err() {
            return Err(CatalogValidationError::InvalidId(value));
        }
        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for CatalogId {
    fn default() -> Self {
        Self::new()
    }
}

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

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceKind {
    Measured,
    Synthetic,
    Reconstructed,
    Mixed,
    Unknown,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CatalogObjectKind {
    Experiment,
    Series,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CatalogArtifactPurpose {
    RawInstrumentData,
    TypedKiTheDocument,
    ProcessedResults,
    PlotImage,
    EditableKiThePlot,
    Other,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CatalogArtifactFile {
    pub path: std::path::PathBuf,
    pub purpose: CatalogArtifactPurpose,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactLocation {
    Local {
        root_id: String,
        relative_path: String,
    },
    Server {
        storage_key: String,
    },
}

/// An immutable reference to one observed file version; file bytes remain outside the catalog DB.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogArtifact {
    pub id: CatalogId,
    pub purpose: CatalogArtifactPurpose,
    pub format: String,
    pub file_name: String,
    pub size_bytes: u64,
    pub sha256: String,
    pub locations: Vec<ArtifactLocation>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CatalogExperiment {
    pub id: CatalogId,
    /// KiThe's immutable experiment identity, not its editable display name.
    pub source_identity: String,
    pub display_name: String,
    pub source_kind: SourceKind,
    #[serde(default)]
    pub date: Option<String>,
    /// Optional free-text label only; structured sample identity is linked by `experiment_samples`.
    pub sample: Option<String>,
    pub instrument: Option<String>,
    pub operator: Option<String>,
    pub thermal_mode: Option<CatalogThermalMode>,
    pub temperature_k: Option<f64>,
    pub heating_rate_k_per_min: Option<f64>,
    pub comment: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CatalogThermalMode {
    Isothermal,
    NonIsothermal,
    Unspecified,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogSeries {
    pub id: CatalogId,
    pub display_name: String,
    pub description: Option<String>,
}

/// A research campaign grouping related substances and their experimental series.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogStudy {
    pub id: CatalogId,
    pub display_name: String,
    pub description: Option<String>,
}

/// Chemical identity. Preparation-specific information belongs to `CatalogSample`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogSubstance {
    pub id: CatalogId,
    pub display_name: String,
    pub formula: Option<String>,
    pub cas_number: Option<String>,
    pub inchi_key: Option<String>,
    pub description: Option<String>,
}

/// A prepared material or batch measured in one or more experiments.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogSample {
    pub id: CatalogId,
    pub substance_id: CatalogId,
    pub display_name: String,
    pub batch_label: Option<String>,
    pub preparation_note: Option<String>,
}

/// Portable metadata-only view of a study and its independent kinetic series.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CatalogStudyManifest {
    pub schema_version: u32,
    pub study: CatalogStudy,
    pub substances: Vec<CatalogSubstance>,
    pub samples: Vec<CatalogSample>,
    pub series: Vec<CatalogStudySeriesManifest>,
}

/// A series stays a distinct kinetic input; publications are referenced, not copied.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CatalogStudySeriesManifest {
    pub series: CatalogSeries,
    pub substance_id: Option<CatalogId>,
    pub current_members: Vec<PublishedSeriesMember>,
    pub experiment_samples: Vec<CatalogExperimentSample>,
    pub publications: Vec<CatalogPublication>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogExperimentSample {
    pub experiment_id: CatalogId,
    pub sample_id: CatalogId,
}

#[derive(Debug, thiserror::Error)]
pub enum CatalogStudyManifestError {
    #[error("study manifest JSON is invalid: {0}")]
    Serialization(#[from] serde_json::Error),
    #[error("study manifest validation failed: {0}")]
    Validation(#[from] CatalogValidationError),
}

/// Ordered membership is captured by a publication, so later edits do not
/// rewrite the historical scope of a published analysis.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PublishedSeriesMember {
    pub experiment_id: CatalogId,
    pub ordinal: u32,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CatalogPublication {
    pub id: CatalogId,
    pub object_kind: CatalogObjectKind,
    pub object_id: CatalogId,
    pub parent_publication_id: Option<CatalogId>,
    pub created_at_rfc3339: String,
    pub author: Option<String>,
    pub description: Option<String>,
    pub series_members: Vec<PublishedSeriesMember>,
    pub artifact_ids: Vec<CatalogId>,
    /// Metadata as it was published, independent of later edits to catalog search cards.
    #[serde(default)]
    pub snapshot: Option<CatalogPublicationSnapshot>,
    /// Compact scientific summary extracted from attached typed documents.
    #[serde(default)]
    pub typed_documents: Vec<CatalogTypedDocumentSummary>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CatalogTypedDocumentSummary {
    pub file_name: String,
    #[serde(default)]
    pub analysis_results:
        Vec<crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultRecord>,
    #[serde(default)]
    pub kinetic_method_outputs: Vec<CatalogKineticMethodOutput>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CatalogKineticMethodOutput {
    pub experiment_identity: String,
    pub experiment_id_snapshot: String,
    pub output_column: String,
    pub method: String,
    pub model: Option<String>,
    pub solver: Option<String>,
    pub output_unit: String,
    pub parameters: Vec<(String, f64)>,
    pub sources: Vec<crate::Kinetics::experimental_kinetics::column_provenance::KineticSourceRef>,
    pub value_range: Option<(String, f64, f64)>,
    pub diagnostics: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CatalogPublicationSnapshot {
    Experiment(CatalogExperiment),
    Series {
        series: CatalogSeries,
        experiments: Vec<CatalogExperiment>,
    },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CatalogValidationError {
    InvalidId(String),
    EmptySourceIdentity,
    EmptyDisplayName,
    EmptySubstanceName,
    EmptySampleName,
    InvalidDate(String),
    DuplicateSeriesMember(CatalogId),
    DuplicateMemberOrder(u32),
    InvalidMemberOrder { expected: u32, actual: u32 },
    DuplicateArtifact(CatalogId),
    PublicationSnapshotMismatch,
    UnsupportedStudyManifestVersion(u32),
    DuplicateStudyManifestSubstance(CatalogId),
    DuplicateStudyManifestSample(CatalogId),
    DuplicateStudyManifestExperimentSample(CatalogId),
    DuplicateStudyManifestSeries(CatalogId),
    DuplicateStudyManifestPublication(CatalogId),
    UnknownStudyManifestSubstance(CatalogId),
    UnknownStudyManifestSample(CatalogId),
    StudyManifestSampleSubstanceMismatch(CatalogId),
    StudyManifestSampleNotInSeries(CatalogId),
    InvalidSha256(String),
    InvalidRelativePath(String),
}

impl std::fmt::Display for CatalogValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidId(value) => write!(f, "invalid catalog UUID '{value}'"),
            Self::EmptySourceIdentity => write!(f, "source experiment identity is empty"),
            Self::EmptyDisplayName => write!(f, "catalog display name is empty"),
            Self::EmptySubstanceName => write!(f, "substance name is empty"),
            Self::EmptySampleName => write!(f, "sample name is empty"),
            Self::InvalidDate(value) => {
                write!(f, "invalid date '{value}'; expected ISO format YYYY-MM-DD")
            }
            Self::DuplicateSeriesMember(id) => write!(f, "duplicate series member {id:?}"),
            Self::DuplicateMemberOrder(order) => write!(f, "duplicate series member order {order}"),
            Self::InvalidMemberOrder { expected, actual } => {
                write!(f, "series member order is {actual}, expected {expected}")
            }
            Self::DuplicateArtifact(id) => write!(f, "duplicate artifact reference {id:?}"),
            Self::PublicationSnapshotMismatch => {
                write!(
                    f,
                    "publication metadata snapshot does not match its target and membership"
                )
            }
            Self::UnsupportedStudyManifestVersion(version) => {
                write!(f, "unsupported study manifest version {version}")
            }
            Self::DuplicateStudyManifestSubstance(id) => {
                write!(f, "duplicate substance {id} in study manifest")
            }
            Self::DuplicateStudyManifestSample(id) => {
                write!(f, "duplicate sample {id} in study manifest")
            }
            Self::DuplicateStudyManifestExperimentSample(id) => {
                write!(
                    f,
                    "experiment {id} has more than one sample link in study manifest"
                )
            }
            Self::DuplicateStudyManifestSeries(id) => {
                write!(f, "duplicate series {id} in study manifest")
            }
            Self::DuplicateStudyManifestPublication(id) => {
                write!(f, "duplicate publication {id} in study manifest")
            }
            Self::UnknownStudyManifestSubstance(id) => {
                write!(
                    f,
                    "series refers to substance {id} absent from study manifest"
                )
            }
            Self::UnknownStudyManifestSample(id) => {
                write!(f, "series refers to sample {id} absent from study manifest")
            }
            Self::StudyManifestSampleSubstanceMismatch(id) => {
                write!(
                    f,
                    "sample {id} belongs to a different substance than its series"
                )
            }
            Self::StudyManifestSampleNotInSeries(id) => {
                write!(
                    f,
                    "sample link refers to experiment {id} outside its series"
                )
            }
            Self::InvalidSha256(value) => write!(f, "invalid SHA-256 digest '{value}'"),
            Self::InvalidRelativePath(value) => {
                write!(f, "invalid relative artifact path '{value}'")
            }
        }
    }
}

impl CatalogStudy {
    pub fn validate(&self) -> Result<(), CatalogValidationError> {
        if self.display_name.trim().is_empty() {
            return Err(CatalogValidationError::EmptyDisplayName);
        }
        Ok(())
    }
}

impl CatalogSubstance {
    pub fn validate(&self) -> Result<(), CatalogValidationError> {
        if self.display_name.trim().is_empty() {
            return Err(CatalogValidationError::EmptySubstanceName);
        }
        Ok(())
    }
}

impl CatalogSample {
    pub fn validate(&self) -> Result<(), CatalogValidationError> {
        if self.display_name.trim().is_empty() {
            return Err(CatalogValidationError::EmptySampleName);
        }
        Ok(())
    }
}

impl CatalogStudyManifest {
    pub fn validate(&self) -> Result<(), CatalogValidationError> {
        if self.schema_version != 1 {
            return Err(CatalogValidationError::UnsupportedStudyManifestVersion(
                self.schema_version,
            ));
        }
        self.study.validate()?;
        let mut substance_ids = std::collections::HashSet::new();
        for substance in &self.substances {
            substance.validate()?;
            if !substance_ids.insert(substance.id.clone()) {
                return Err(CatalogValidationError::DuplicateStudyManifestSubstance(
                    substance.id.clone(),
                ));
            }
        }
        let mut sample_ids = std::collections::HashSet::new();
        for sample in &self.samples {
            sample.validate()?;
            if !substance_ids.contains(&sample.substance_id) {
                return Err(CatalogValidationError::UnknownStudyManifestSubstance(
                    sample.substance_id.clone(),
                ));
            }
            if !sample_ids.insert(sample.id.clone()) {
                return Err(CatalogValidationError::DuplicateStudyManifestSample(
                    sample.id.clone(),
                ));
            }
        }
        let mut series_ids = std::collections::HashSet::new();
        let mut publication_ids = std::collections::HashSet::new();
        for entry in &self.series {
            if entry.series.display_name.trim().is_empty() {
                return Err(CatalogValidationError::EmptyDisplayName);
            }
            if !series_ids.insert(entry.series.id.clone()) {
                return Err(CatalogValidationError::DuplicateStudyManifestSeries(
                    entry.series.id.clone(),
                ));
            }
            if let Some(substance_id) = &entry.substance_id
                && !substance_ids.contains(substance_id)
            {
                return Err(CatalogValidationError::UnknownStudyManifestSubstance(
                    substance_id.clone(),
                ));
            }
            validate_manifest_members(&entry.current_members)?;
            let member_ids = entry
                .current_members
                .iter()
                .map(|member| member.experiment_id.clone())
                .collect::<std::collections::HashSet<_>>();
            let mut linked_experiments = std::collections::HashSet::new();
            for link in &entry.experiment_samples {
                if !member_ids.contains(&link.experiment_id) {
                    return Err(CatalogValidationError::StudyManifestSampleNotInSeries(
                        link.experiment_id.clone(),
                    ));
                }
                if !linked_experiments.insert(link.experiment_id.clone()) {
                    return Err(
                        CatalogValidationError::DuplicateStudyManifestExperimentSample(
                            link.experiment_id.clone(),
                        ),
                    );
                }
                let sample = self
                    .samples
                    .iter()
                    .find(|sample| sample.id == link.sample_id)
                    .ok_or_else(|| {
                        CatalogValidationError::UnknownStudyManifestSample(link.sample_id.clone())
                    })?;
                if entry
                    .substance_id
                    .as_ref()
                    .is_some_and(|substance_id| substance_id != &sample.substance_id)
                {
                    return Err(
                        CatalogValidationError::StudyManifestSampleSubstanceMismatch(
                            sample.id.clone(),
                        ),
                    );
                }
            }
            for publication in &entry.publications {
                publication.validate()?;
                if publication.object_kind != CatalogObjectKind::Series
                    || publication.object_id != entry.series.id
                {
                    return Err(CatalogValidationError::PublicationSnapshotMismatch);
                }
                if !publication_ids.insert(publication.id.clone()) {
                    return Err(CatalogValidationError::DuplicateStudyManifestPublication(
                        publication.id.clone(),
                    ));
                }
            }
        }
        Ok(())
    }

    pub fn to_json(&self) -> Result<String, CatalogStudyManifestError> {
        self.validate()?;
        Ok(serde_json::to_string_pretty(self)?)
    }

    pub fn from_json(json: &str) -> Result<Self, CatalogStudyManifestError> {
        let manifest: Self = serde_json::from_str(json)?;
        manifest.validate()?;
        Ok(manifest)
    }
}

fn validate_manifest_members(
    members: &[PublishedSeriesMember],
) -> Result<(), CatalogValidationError> {
    let mut ids = std::collections::HashSet::new();
    for (index, member) in members.iter().enumerate() {
        if !ids.insert(member.experiment_id.clone()) {
            return Err(CatalogValidationError::DuplicateSeriesMember(
                member.experiment_id.clone(),
            ));
        }
        let expected = u32::try_from(index).unwrap_or(u32::MAX);
        if member.ordinal != expected {
            return Err(CatalogValidationError::InvalidMemberOrder {
                expected,
                actual: member.ordinal,
            });
        }
    }
    Ok(())
}

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

impl CatalogExperiment {
    pub fn validate(&self) -> Result<(), CatalogValidationError> {
        if self.source_identity.trim().is_empty() {
            return Err(CatalogValidationError::EmptySourceIdentity);
        }
        if self.display_name.trim().is_empty() {
            return Err(CatalogValidationError::EmptyDisplayName);
        }
        if let Some(date) = &self.date
            && chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").is_err()
        {
            return Err(CatalogValidationError::InvalidDate(date.clone()));
        }
        Ok(())
    }
}

impl CatalogPublication {
    pub fn validate(&self) -> Result<(), CatalogValidationError> {
        match (&self.snapshot, self.object_kind) {
            (
                Some(CatalogPublicationSnapshot::Experiment(experiment)),
                CatalogObjectKind::Experiment,
            ) if experiment.id == self.object_id
                && experiment.source_identity == self.object_id.as_str() =>
            {
                experiment.validate()?;
            }
            (
                Some(CatalogPublicationSnapshot::Series {
                    series,
                    experiments,
                }),
                CatalogObjectKind::Series,
            ) if series.id == self.object_id => {
                if series.display_name.trim().is_empty() {
                    return Err(CatalogValidationError::EmptyDisplayName);
                }
                if experiments.len() != self.series_members.len() {
                    return Err(CatalogValidationError::PublicationSnapshotMismatch);
                }
                for (experiment, member) in experiments.iter().zip(&self.series_members) {
                    experiment.validate()?;
                    if experiment.id != member.experiment_id
                        || experiment.source_identity != member.experiment_id.as_str()
                    {
                        return Err(CatalogValidationError::PublicationSnapshotMismatch);
                    }
                }
            }
            (Some(_), _) => return Err(CatalogValidationError::PublicationSnapshotMismatch),
            (None, _) => {}
        }
        if self
            .series_members
            .iter()
            .any(|member| member.experiment_id == self.object_id)
        {
            return Err(CatalogValidationError::DuplicateSeriesMember(
                self.object_id.clone(),
            ));
        }
        let mut member_ids = std::collections::HashSet::new();
        let mut ordinals = std::collections::HashSet::new();
        for (index, member) in self.series_members.iter().enumerate() {
            if !member_ids.insert(member.experiment_id.clone()) {
                return Err(CatalogValidationError::DuplicateSeriesMember(
                    member.experiment_id.clone(),
                ));
            }
            if !ordinals.insert(member.ordinal) {
                return Err(CatalogValidationError::DuplicateMemberOrder(member.ordinal));
            }
            if u32::try_from(index).ok() != Some(member.ordinal) {
                return Err(CatalogValidationError::InvalidMemberOrder {
                    expected: u32::try_from(index).unwrap_or(u32::MAX),
                    actual: member.ordinal,
                });
            }
        }
        let mut artifact_ids = std::collections::HashSet::new();
        for artifact_id in &self.artifact_ids {
            if !artifact_ids.insert(artifact_id) {
                return Err(CatalogValidationError::DuplicateArtifact(
                    artifact_id.clone(),
                ));
            }
        }
        Ok(())
    }
}

impl CatalogArtifact {
    pub fn validate(&self) -> Result<(), CatalogValidationError> {
        if self.sha256.len() != 64 || !self.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(CatalogValidationError::InvalidSha256(self.sha256.clone()));
        }
        for location in &self.locations {
            if let ArtifactLocation::Local { relative_path, .. } = location {
                let path = std::path::Path::new(relative_path);
                if path.is_absolute()
                    || path.components().any(|part| {
                        matches!(
                            part,
                            std::path::Component::ParentDir
                                | std::path::Component::RootDir
                                | std::path::Component::Prefix(_)
                        )
                    })
                {
                    return Err(CatalogValidationError::InvalidRelativePath(
                        relative_path.clone(),
                    ));
                }
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn catalog_ids_round_trip_and_reject_non_uuids() {
        let id = CatalogId::new();
        let json = serde_json::to_string(&id).unwrap();
        assert_eq!(serde_json::from_str::<CatalogId>(&json).unwrap(), id);
        assert!(CatalogId::parse("not-an-id").is_err());
    }

    #[test]
    fn experiment_metadata_defaults_new_fields_and_validates_iso_date() {
        let id = CatalogId::new();
        let legacy = serde_json::json!({
            "id": id.as_str(),
            "source_identity": id.as_str(),
            "display_name": "legacy run",
            "source_kind": "unknown",
            "sample": null,
            "instrument": null,
            "operator": null,
            "thermal_mode": null,
            "temperature_k": null,
            "heating_rate_k_per_min": null,
            "comment": null
        });
        let mut experiment: CatalogExperiment = serde_json::from_value(legacy).unwrap();
        assert_eq!(experiment.date, None);
        assert!(experiment.tags.is_empty());
        assert!(experiment.validate().is_ok());

        experiment.date = Some("2026-12-01".into());
        assert!(experiment.validate().is_ok());
        experiment.date = Some("01/12/2026".into());
        assert!(matches!(
            experiment.validate(),
            Err(CatalogValidationError::InvalidDate(_))
        ));
    }

    #[test]
    fn artifact_validation_rejects_path_escape_and_bad_digest() {
        let mut artifact = CatalogArtifact {
            id: CatalogId::new(),
            purpose: CatalogArtifactPurpose::RawInstrumentData,
            format: "txt".into(),
            file_name: "run.txt".into(),
            size_bytes: 10,
            sha256: "a".repeat(64),
            locations: vec![ArtifactLocation::Local {
                root_id: "lab".into(),
                relative_path: "runs/run.txt".into(),
            }],
        };
        assert!(artifact.validate().is_ok());
        artifact.locations[0] = ArtifactLocation::Local {
            root_id: "lab".into(),
            relative_path: "../../outside.txt".into(),
        };
        assert!(matches!(
            artifact.validate(),
            Err(CatalogValidationError::InvalidRelativePath(_))
        ));
    }

    #[test]
    fn publication_rejects_duplicate_members_and_artifacts() {
        let experiment = CatalogId::new();
        let artifact = CatalogId::new();
        let publication = CatalogPublication {
            id: CatalogId::new(),
            object_kind: CatalogObjectKind::Series,
            object_id: CatalogId::new(),
            parent_publication_id: None,
            created_at_rfc3339: "2026-12-01T12:00:00Z".into(),
            author: None,
            description: None,
            series_members: vec![
                PublishedSeriesMember {
                    experiment_id: experiment.clone(),
                    ordinal: 0,
                },
                PublishedSeriesMember {
                    experiment_id: experiment,
                    ordinal: 1,
                },
            ],
            artifact_ids: vec![artifact.clone(), artifact],
            snapshot: None,
            typed_documents: vec![],
        };
        assert!(matches!(
            publication.validate(),
            Err(CatalogValidationError::DuplicateSeriesMember(_))
        ));
    }

    #[test]
    fn legacy_publications_load_without_metadata_snapshot() {
        let json = serde_json::json!({
            "id": CatalogId::new(),
            "object_kind": "experiment",
            "object_id": CatalogId::new(),
            "parent_publication_id": null,
            "created_at_rfc3339": "2026-12-01T10:00:00Z",
            "author": null,
            "description": null,
            "series_members": [],
            "artifact_ids": []
        });
        let publication: CatalogPublication = serde_json::from_value(json).unwrap();
        assert!(publication.snapshot.is_none());
    }

    #[test]
    fn publication_rejects_snapshot_for_another_target() {
        let target_id = CatalogId::new();
        let other_id = CatalogId::new();
        let publication = CatalogPublication {
            id: CatalogId::new(),
            object_kind: CatalogObjectKind::Experiment,
            object_id: target_id,
            parent_publication_id: None,
            created_at_rfc3339: "2026-12-01T10:00:00Z".into(),
            author: None,
            description: None,
            series_members: Vec::new(),
            artifact_ids: Vec::new(),
            snapshot: Some(CatalogPublicationSnapshot::Experiment(CatalogExperiment {
                id: other_id.clone(),
                source_identity: other_id.as_str().into(),
                display_name: "wrong target".into(),
                source_kind: SourceKind::Unknown,
                date: None,
                sample: None,
                instrument: None,
                operator: None,
                thermal_mode: None,
                temperature_k: None,
                heating_rate_k_per_min: None,
                comment: None,
                tags: Vec::new(),
            })),
            typed_documents: vec![],
        };
        assert_eq!(
            publication.validate(),
            Err(CatalogValidationError::PublicationSnapshotMismatch)
        );
    }

    #[test]
    fn study_manifest_validates_sample_links_and_preserves_them_in_json() {
        let substance_id = CatalogId::new();
        let sample_id = CatalogId::new();
        let series_id = CatalogId::new();
        let experiment_id = CatalogId::new();
        let manifest = CatalogStudyManifest {
            schema_version: 1,
            study: CatalogStudy {
                id: CatalogId::new(),
                display_name: "Campaign".into(),
                description: None,
            },
            substances: vec![CatalogSubstance {
                id: substance_id.clone(),
                display_name: "Material A".into(),
                formula: None,
                cas_number: None,
                inchi_key: None,
                description: None,
            }],
            samples: vec![CatalogSample {
                id: sample_id.clone(),
                substance_id: substance_id.clone(),
                display_name: "Batch 1".into(),
                batch_label: None,
                preparation_note: None,
            }],
            series: vec![CatalogStudySeriesManifest {
                series: CatalogSeries {
                    id: series_id,
                    display_name: "Isothermal series".into(),
                    description: None,
                },
                substance_id: Some(substance_id),
                current_members: vec![PublishedSeriesMember {
                    experiment_id: experiment_id.clone(),
                    ordinal: 0,
                }],
                experiment_samples: vec![CatalogExperimentSample {
                    experiment_id: experiment_id.clone(),
                    sample_id: sample_id.clone(),
                }],
                publications: Vec::new(),
            }],
        };
        let encoded = manifest.to_json().unwrap();
        assert_eq!(CatalogStudyManifest::from_json(&encoded).unwrap(), manifest);

        let mut invalid = manifest.clone();
        invalid.series[0].experiment_samples[0].experiment_id = CatalogId::new();
        assert_eq!(
            invalid.validate(),
            Err(CatalogValidationError::StudyManifestSampleNotInSeries(
                invalid.series[0].experiment_samples[0]
                    .experiment_id
                    .clone()
            ))
        );

        let mut invalid = manifest;
        invalid.samples[0].substance_id = CatalogId::new();
        assert!(matches!(
            invalid.validate(),
            Err(CatalogValidationError::UnknownStudyManifestSubstance(_))
        ));

        let mut invalid = CatalogStudyManifest::from_json(&encoded).unwrap();
        let other_substance = CatalogId::new();
        invalid.substances.push(CatalogSubstance {
            id: other_substance.clone(),
            display_name: "Material B".into(),
            formula: None,
            cas_number: None,
            inchi_key: None,
            description: None,
        });
        invalid.samples[0].substance_id = other_substance;
        assert!(matches!(
            invalid.validate(),
            Err(CatalogValidationError::StudyManifestSampleSubstanceMismatch(_))
        ));

        let mut invalid = CatalogStudyManifest::from_json(&encoded).unwrap();
        let duplicate_link = invalid.series[0].experiment_samples[0].clone();
        invalid.series[0].experiment_samples.push(duplicate_link);
        assert!(matches!(
            invalid.validate(),
            Err(CatalogValidationError::DuplicateStudyManifestExperimentSample(_))
        ));
    }
}