aecr-sync 0.1.0

ISO 19650 Workset CDE and element-borrow synchronization
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
//! ISO 19650 Common Data Environment container naming, states, suitability codes, and metadata.

use std::fmt;
use std::str::FromStr;

use aecr_pig::{ActorId, ContentHash, RevisionId};
use serde::{Deserialize, Serialize};

use crate::error::SyncError;

/// ISO 19650 information container lifecycle state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum CdeState {
    /// Work in Progress (discipline-private authoring with element borrowing).
    WorkInProgress,
    /// Shared across disciplines after passing automated verification checks.
    Shared,
    /// Authorized and published for submission, tender, or construction.
    Published,
    /// Immutable historical record after publication.
    Archived,
}

impl fmt::Display for CdeState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::WorkInProgress => f.write_str("WorkInProgress"),
            Self::Shared => f.write_str("Shared"),
            Self::Published => f.write_str("Published"),
            Self::Archived => f.write_str("Archived"),
        }
    }
}

/// ISO 19650 suitability code governing allowed container usage within each CDE state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum SuitabilityCode {
    /// Initial Work in Progress status.
    S0,
    /// Suitable for multi-discipline coordination (`Shared`).
    S1,
    /// Suitable for information (`Shared`).
    S2,
    /// Suitable for review and comment (`Shared`).
    S3,
    /// Suitable for stage approval (`Shared`).
    S4,
    /// Authorized and accepted stage 1 (`Published`).
    A1,
    /// Authorized and accepted stage 2 (`Published`).
    A2,
    /// Authorized and accepted stage 3 (`Published`).
    A3,
    /// Authorized and accepted stage 4 (`Published`).
    A4,
    /// As-constructed / archived record (`Archived`).
    Cr,
}

impl fmt::Display for SuitabilityCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let code = match self {
            Self::S0 => "S0",
            Self::S1 => "S1",
            Self::S2 => "S2",
            Self::S3 => "S3",
            Self::S4 => "S4",
            Self::A1 => "A1",
            Self::A2 => "A2",
            Self::A3 => "A3",
            Self::A4 => "A4",
            Self::Cr => "Cr",
        };
        f.write_str(code)
    }
}

/// ISO 19650-2 / JKR BIM 7-field information container identifier (`PRJ1-ARC-ZZ-01-M3-A-0001`).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ContainerId {
    /// Project code token.
    pub project: String,
    /// Authoring organization or originator code token.
    pub originator: String,
    /// Spatial volume or system code token.
    pub volume_system: String,
    /// Storey level or location code token.
    pub level_location: String,
    /// Information container type code token (for example, `M3` or `DR`).
    pub doc_type: String,
    /// Authoring discipline or role code token (for example, `A`, `S`, `M`, `E`).
    pub discipline: String,
    /// Sequential document or model number token.
    pub number: String,
}

impl ContainerId {
    /// Constructs and validates a 7-token ISO 19650-2 container identifier.
    pub fn new(
        project: impl Into<String>,
        originator: impl Into<String>,
        volume_system: impl Into<String>,
        level_location: impl Into<String>,
        doc_type: impl Into<String>,
        discipline: impl Into<String>,
        number: impl Into<String>,
    ) -> Result<Self, SyncError> {
        let id = Self {
            project: project.into(),
            originator: originator.into(),
            volume_system: volume_system.into(),
            level_location: level_location.into(),
            doc_type: doc_type.into(),
            discipline: discipline.into(),
            number: number.into(),
        };
        id.validate()?;
        Ok(id)
    }

    /// Parses and validates a hyphen-separated ISO 19650-2 container code string.
    pub fn parse(raw: &str) -> Result<Self, SyncError> {
        let mut iter = raw.split('-');
        let (
            Some(project),
            Some(originator),
            Some(volume_system),
            Some(level_location),
            Some(doc_type),
            Some(discipline),
            Some(number),
        ) = (
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
        )
        else {
            let count = raw.split('-').count();
            return Err(SyncError::InvalidContainerId(format!(
                "expected 7 hyphen-delimited tokens in '{raw}', got {count}"
            )));
        };
        let extra = iter.count();
        if extra > 0 {
            return Err(SyncError::InvalidContainerId(format!(
                "expected 7 hyphen-delimited tokens in '{raw}', got {}",
                7 + extra
            )));
        }
        Self::new(
            project,
            originator,
            volume_system,
            level_location,
            doc_type,
            discipline,
            number,
        )
    }

    /// Checks that all seven fields are non-empty ASCII uppercase alphanumeric tokens.
    pub fn validate(&self) -> Result<(), SyncError> {
        validate_token("project", &self.project)?;
        validate_token("originator", &self.originator)?;
        validate_token("volume_system", &self.volume_system)?;
        validate_token("level_location", &self.level_location)?;
        validate_token("doc_type", &self.doc_type)?;
        validate_token("discipline", &self.discipline)?;
        validate_token("number", &self.number)
    }

    /// Formats the canonical hyphen-delimited ISO 19650-2 container code.
    pub fn canonical_code(&self) -> String {
        self.to_string()
    }
}

impl fmt::Display for ContainerId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}-{}-{}-{}-{}-{}-{}",
            self.project,
            self.originator,
            self.volume_system,
            self.level_location,
            self.doc_type,
            self.discipline,
            self.number
        )
    }
}

impl FromStr for ContainerId {
    type Err = SyncError;

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

impl TryFrom<&str> for ContainerId {
    type Error = SyncError;

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

fn validate_token(field: &str, value: &str) -> Result<(), SyncError> {
    if value.is_empty() {
        return Err(SyncError::InvalidContainerId(format!(
            "{field} token must not be empty"
        )));
    }
    if !value
        .bytes()
        .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
    {
        return Err(SyncError::InvalidContainerId(format!(
            "{field} token '{value}' must contain only ASCII uppercase alphanumeric characters"
        )));
    }
    Ok(())
}

/// Immutable audit record appended on every CDE lifecycle state transition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionRecord {
    /// Lifecycle state prior to this transition.
    pub from_state: CdeState,
    /// Lifecycle state entered by this transition.
    pub to_state: CdeState,
    /// Suitability code assigned on transition.
    pub suitability: SuitabilityCode,
    /// Container revision string recorded at transition time.
    pub revision: String,
    /// Actor authorizing or executing the transition.
    pub actor: ActorId,
    /// UTC transition timestamp in nanoseconds.
    pub timestamp_utc_ns: u64,
    /// PIG Merkle root hash bound to this transition.
    pub root_hash: ContentHash,
    /// Human-readable audit note or transmittal summary.
    pub note: String,
}

/// ISO 19650 Common Data Environment metadata and transition history for one container.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContainerMetadata {
    /// Validated ISO 19650-2 / JKR container identifier.
    pub id: ContainerId,
    /// Current CDE lifecycle state.
    pub state: CdeState,
    /// Current ISO 19650 suitability code.
    pub suitability: SuitabilityCode,
    /// Container revision string (for example, `P01.01` in WIP or `C01` when Published).
    pub revision: String,
    /// Monotonic PIG graph revision bound to the current container state.
    pub graph_revision: RevisionId,
    /// Deterministic PIG SHA-256 root hash bound to the current container state.
    pub root_hash: ContentHash,
    /// Chronological audit trail of lifecycle state transitions.
    pub audit_trail: Vec<TransitionRecord>,
}

impl ContainerMetadata {
    /// Creates a new container in [`CdeState::WorkInProgress`] with [`SuitabilityCode::S0`].
    pub fn new_wip(
        id: ContainerId,
        revision: impl Into<String>,
        graph_revision: RevisionId,
        root_hash: ContentHash,
    ) -> Self {
        Self {
            id,
            state: CdeState::WorkInProgress,
            suitability: SuitabilityCode::S0,
            revision: revision.into(),
            graph_revision,
            root_hash,
            audit_trail: Vec::new(),
        }
    }

    /// Returns `true` once the container is [`CdeState::Published`] or [`CdeState::Archived`].
    #[inline]
    pub const fn is_immutable(&self) -> bool {
        matches!(self.state, CdeState::Published | CdeState::Archived)
    }

    /// Returns `true` if `(state, suitability)` is legal under the ISO 19650 suitability matrix.
    #[inline]
    pub const fn is_valid_state_suitability(state: CdeState, suitability: SuitabilityCode) -> bool {
        matches!(
            (state, suitability),
            (CdeState::WorkInProgress, SuitabilityCode::S0)
                | (
                    CdeState::Shared,
                    SuitabilityCode::S1
                        | SuitabilityCode::S2
                        | SuitabilityCode::S3
                        | SuitabilityCode::S4
                )
                | (
                    CdeState::Published,
                    SuitabilityCode::A1
                        | SuitabilityCode::A2
                        | SuitabilityCode::A3
                        | SuitabilityCode::A4
                )
                | (CdeState::Archived, SuitabilityCode::Cr)
        )
    }

    /// Validates that the container's current `(state, suitability)` pair satisfies the matrix.
    pub fn validate_state_suitability(&self) -> Result<(), SyncError> {
        if Self::is_valid_state_suitability(self.state, self.suitability) {
            Ok(())
        } else {
            Err(SyncError::InvalidTransition {
                from: self.state,
                to: self.state,
                suitability: self.suitability,
            })
        }
    }

    /// Validates whether transitioning from `self.state` to `to` with `suitability` is legal.
    pub fn validate_transition(
        &self,
        to: CdeState,
        suitability: SuitabilityCode,
    ) -> Result<(), SyncError> {
        if self.state == CdeState::Archived {
            return Err(SyncError::ContainerLocked(CdeState::Archived));
        }
        if self.state == CdeState::Published && to != CdeState::Archived {
            return Err(SyncError::ContainerLocked(CdeState::Published));
        }
        if !Self::is_valid_state_suitability(to, suitability) {
            return Err(SyncError::InvalidTransition {
                from: self.state,
                to,
                suitability,
            });
        }
        let legal_edge = matches!(
            (self.state, to),
            (CdeState::WorkInProgress, CdeState::Shared)
                | (
                    CdeState::Shared,
                    CdeState::WorkInProgress | CdeState::Published
                )
                | (CdeState::Published, CdeState::Archived)
        );
        if !legal_edge {
            return Err(SyncError::InvalidTransition {
                from: self.state,
                to,
                suitability,
            });
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use aecr_pig::{ContentHash, RevisionId};

    use super::{CdeState, ContainerId, ContainerMetadata, SuitabilityCode};
    use crate::error::SyncError;

    #[test]
    fn container_id_validates_iso19650_naming_rules() -> Result<(), SyncError> {
        let id = ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A-0001")?;
        assert_eq!(id.project, "PRJ1");
        assert_eq!(id.originator, "ARC");
        assert_eq!(id.volume_system, "ZZ");
        assert_eq!(id.level_location, "01");
        assert_eq!(id.doc_type, "M3");
        assert_eq!(id.discipline, "A");
        assert_eq!(id.number, "0001");
        assert_eq!(id.canonical_code(), "PRJ1-ARC-ZZ-01-M3-A-0001");
        assert_eq!(id.to_string(), "PRJ1-ARC-ZZ-01-M3-A-0001");

        // Lowercase, empty token, wrong segment count, and punctuation are rejected.
        assert!(matches!(
            ContainerId::parse("prj1-ARC-ZZ-01-M3-A-0001"),
            Err(SyncError::InvalidContainerId(_))
        ));
        assert!(matches!(
            ContainerId::parse("PRJ1-ARC--01-M3-A-0001"),
            Err(SyncError::InvalidContainerId(_))
        ));
        assert!(matches!(
            ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A"),
            Err(SyncError::InvalidContainerId(_))
        ));
        assert!(matches!(
            ContainerId::new("PRJ1", "ARC", "ZZ", "01", "M3", "A_1", "0001"),
            Err(SyncError::InvalidContainerId(_))
        ));
        Ok(())
    }

    #[test]
    fn state_suitability_matrix_and_transition_locks() -> Result<(), SyncError> {
        assert!(ContainerMetadata::is_valid_state_suitability(
            CdeState::WorkInProgress,
            SuitabilityCode::S0
        ));
        assert!(!ContainerMetadata::is_valid_state_suitability(
            CdeState::WorkInProgress,
            SuitabilityCode::S1
        ));
        assert!(ContainerMetadata::is_valid_state_suitability(
            CdeState::Shared,
            SuitabilityCode::S3
        ));
        assert!(!ContainerMetadata::is_valid_state_suitability(
            CdeState::Shared,
            SuitabilityCode::A1
        ));
        assert!(ContainerMetadata::is_valid_state_suitability(
            CdeState::Published,
            SuitabilityCode::A2
        ));
        assert!(!ContainerMetadata::is_valid_state_suitability(
            CdeState::Published,
            SuitabilityCode::Cr
        ));
        assert!(ContainerMetadata::is_valid_state_suitability(
            CdeState::Archived,
            SuitabilityCode::Cr
        ));

        let id = ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A-0001")?;
        let mut meta =
            ContainerMetadata::new_wip(id, "P01.01", RevisionId::ZERO, ContentHash::ZERO);
        assert!(!meta.is_immutable());
        meta.validate_state_suitability()?;

        // Skipping Shared or mismatched suitability fails.
        assert!(matches!(
            meta.validate_transition(CdeState::Published, SuitabilityCode::A1),
            Err(SyncError::InvalidTransition { .. })
        ));
        assert!(matches!(
            meta.validate_transition(CdeState::Shared, SuitabilityCode::S0),
            Err(SyncError::InvalidTransition { .. })
        ));
        meta.validate_transition(CdeState::Shared, SuitabilityCode::S1)?;

        // Published allows only Archived(Cr) and blocks other transitions via ContainerLocked.
        meta.state = CdeState::Published;
        meta.suitability = SuitabilityCode::A1;
        assert!(meta.is_immutable());
        assert!(matches!(
            meta.validate_transition(CdeState::WorkInProgress, SuitabilityCode::S0),
            Err(SyncError::ContainerLocked(CdeState::Published))
        ));
        assert!(matches!(
            meta.validate_transition(CdeState::Shared, SuitabilityCode::S1),
            Err(SyncError::ContainerLocked(CdeState::Published))
        ));
        meta.validate_transition(CdeState::Archived, SuitabilityCode::Cr)?;

        // Archived locks every transition permanently.
        meta.state = CdeState::Archived;
        meta.suitability = SuitabilityCode::Cr;
        assert!(meta.is_immutable());
        assert!(matches!(
            meta.validate_transition(CdeState::Archived, SuitabilityCode::Cr),
            Err(SyncError::ContainerLocked(CdeState::Archived))
        ));
        Ok(())
    }
}