chronicle-graph 0.1.0

Event-centric narrative knowledge graphs with temporal verification
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
//! Validation passes: referential integrity, temporal consistency, state tracking, orphan detection.

use std::fmt;

use allen_intervals::{Interval, Meets, NonEmpty, Precedes};
use petgraph::Direction;

use crate::graph::{Chronicle, parse_references};
use crate::model::*;

// ── Report types ───────────────────────────────────────────

/// The result of running all validation passes over a [`Chronicle`].
///
/// Contains collected errors (hard violations that indicate inconsistent data)
/// and warnings (soft issues like orphan entities that may be intentional).
#[derive(Debug, Default)]
pub struct ValidationReport {
    /// Hard validation failures: dangling references, temporal impossibilities,
    /// and state violations (e.g. a dead actor participating in a future event).
    pub errors: Vec<ValidationError>,
    /// Soft issues that do not necessarily indicate broken data, such as
    /// entities with no incoming or outgoing relationships.
    pub warnings: Vec<ValidationWarning>,
}

impl ValidationReport {
    /// Returns `true` if no errors were found. Warnings alone do not cause this to return `false`.
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }
}

/// A hard validation error indicating inconsistent world data.
#[derive(Debug)]
pub enum ValidationError {
    /// A reference from one entity to another that does not exist in the graph.
    DanglingReference {
        /// The ID of the entity that contains the broken reference.
        source_id: String,
        /// The ID that was referenced but not found in the graph.
        target_id: String,
        /// Human-readable label for the kind of reference (e.g. `"location"`, `"participant"`).
        context: String,
    },
    /// A temporal impossibility detected via Allen's Interval Algebra — for example,
    /// an event occurring before a participant's lifespan or after a cause.
    TemporalViolation {
        /// The ID of the entity whose timeline is violated (actor or event).
        entity_id: String,
        /// The ID of the event involved in the violation.
        event_id: String,
        /// Human-readable explanation of the temporal conflict.
        description: String,
    },
    /// An entity is used in an event despite having a terminal status
    /// (e.g. `Dead`, `Destroyed`) from a strictly earlier event.
    StateViolation {
        /// The ID of the entity in a terminal state.
        entity_id: String,
        /// The ID of the event that illegally references the terminal entity.
        event_id: String,
        /// Human-readable explanation including the terminal status and the events involved.
        description: String,
    },
}

/// A soft validation warning that does not indicate broken data but may
/// signal authoring oversights.
#[derive(Debug)]
pub enum ValidationWarning {
    /// An entity with zero incoming and zero outgoing edges — it is completely
    /// disconnected from the rest of the graph.
    OrphanEntity {
        /// The ID of the disconnected entity.
        entity_id: String,
    },
    /// A temporal relationship that is ambiguous (e.g. overlapping intervals
    /// where strict ordering was expected) but not provably wrong.
    TemporalAmbiguity {
        /// Human-readable explanation of the ambiguous temporal relationship.
        description: String,
    },
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DanglingReference { source_id, target_id, context } => {
                write!(f, "dangling reference: {source_id} -> {target_id} ({context})")
            }
            Self::TemporalViolation { entity_id, event_id, description } => {
                write!(f, "temporal violation: {entity_id} in {event_id}: {description}")
            }
            Self::StateViolation { entity_id, event_id, description } => {
                write!(f, "state violation: {entity_id} in {event_id}: {description}")
            }
        }
    }
}

impl fmt::Display for ValidationWarning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OrphanEntity { entity_id } => {
                write!(f, "orphan entity: {entity_id} has no references in or out")
            }
            Self::TemporalAmbiguity { description } => {
                write!(f, "temporal ambiguity: {description}")
            }
        }
    }
}

// ── Validation entry point ─────────────────────────────────

/// Run all four validation passes over the given [`Chronicle`] and return a [`ValidationReport`].
///
/// The passes, executed in order, are:
/// 1. **Referential integrity** — every ID referenced by an entity must exist in the graph.
/// 2. **Temporal consistency** — participant lifespans and causal ordering are checked
///    using Allen's Interval Algebra.
/// 3. **State tracking** — entities with terminal statuses (per [`ValidationConfig`]) cannot
///    appear in events that occur strictly after the status-changing event.
/// 4. **Orphan detection** — entities with no edges in either direction produce warnings.
pub fn validate(chronicle: &Chronicle) -> ValidationReport {
    let mut report = ValidationReport::default();
    validate_referential(chronicle, &mut report);
    validate_temporal(chronicle, &mut report);
    validate_state(chronicle, &chronicle.config, &mut report);
    validate_orphans(chronicle, &mut report);
    report
}

// ── Referential integrity ──────────────────────────────────

fn validate_referential(chronicle: &Chronicle, report: &mut ValidationReport) {
    for nx in chronicle.graph.node_indices() {
        let entity = &chronicle.graph[nx];
        match entity {
            Entity::Actor(actor) => {
                for aff in &actor.affiliations {
                    check_ref(chronicle, &actor.id, aff, "affiliation", report);
                }
                if let Some(ev) = &actor.status_since_event {
                    check_ref(chronicle, &actor.id, ev, "status_since_event", report);
                }
            }
            Entity::Place(place) => {
                if let Some(r) = &place.region {
                    check_ref(chronicle, &place.id, r, "region", report);
                }
                if let Some(ev) = &place.status_since_event {
                    check_ref(chronicle, &place.id, ev, "status_since_event", report);
                }
            }
            Entity::Event(event) => {
                if let Some(loc) = &event.location {
                    check_ref(chronicle, &event.id, loc, "location", report);
                }
                for cause in &event.caused_by {
                    check_ref(chronicle, &event.id, cause, "caused_by", report);
                }
                for p in &event.participants {
                    check_ref(chronicle, &event.id, &p.actor, "participant", report);
                }
                for sc in &event.state_changes {
                    check_ref(chronicle, &event.id, &sc.entity, "state_change target", report);
                }
            }
            Entity::Concept(concept) => {
                if let Some(origin) = &concept.origin_event {
                    check_ref(chronicle, &concept.id, origin, "origin_event", report);
                }
            }
            Entity::Account(account) => {
                check_ref(chronicle, &account.id, &account.source, "source", report);
                for ev in &account.event_refs {
                    check_ref(chronicle, &account.id, ev, "event_ref", report);
                }
                for mention in parse_references(&account.text) {
                    check_ref(chronicle, &account.id, &mention, "text mention", report);
                }
            }
        }
    }
}

fn check_ref(
    chronicle: &Chronicle,
    source_id: &str,
    target_id: &str,
    context: &str,
    report: &mut ValidationReport,
) {
    if !chronicle.index.contains_key(target_id) {
        report.errors.push(ValidationError::DanglingReference {
            source_id: source_id.to_owned(),
            target_id: target_id.to_owned(),
            context: context.to_owned(),
        });
    }
}

// ── Temporal consistency ───────────────────────────────────

fn to_interval(ts: &TimeSpan) -> Option<NonEmpty<Interval<i32>>> {
    // TimeSpan uses inclusive bounds; Allen's discrete intervals use exclusive end.
    Interval { start: ts.start, end: ts.end + 1 }.try_into().ok()
}

/// True if interval `a` ends strictly before `b` starts (precedes or meets in Allen's algebra).
fn strictly_before(a: &NonEmpty<Interval<i32>>, b: &NonEmpty<Interval<i32>>) -> bool {
    a.precedes(b) || a.meets(b)
}

fn validate_temporal(chronicle: &Chronicle, report: &mut ValidationReport) {
    for nx in chronicle.graph.node_indices() {
        if let Entity::Event(event) = &chronicle.graph[nx] {
            let Some(event_iv) = to_interval(&event.time_span) else { continue };

            // Check participants' lifespans
            for p in &event.participants {
                if let Some(&actor_nx) = chronicle.index.get(&p.actor)
                    && let Entity::Actor(actor) = &chronicle.graph[actor_nx]
                    && let Some(lifespan) = &actor.lifespan
                    && let Some(life_iv) = to_interval(lifespan)
                {
                    if strictly_before(&event_iv, &life_iv) {
                        report.errors.push(ValidationError::TemporalViolation {
                            entity_id: actor.id.clone(),
                            event_id: event.id.clone(),
                            description: format!(
                                "event at {}-{} precedes actor lifespan {}-{}",
                                event.time_span.start, event.time_span.end,
                                lifespan.start, lifespan.end,
                            ),
                        });
                    }
                    if strictly_before(&life_iv, &event_iv) {
                        report.errors.push(ValidationError::TemporalViolation {
                            entity_id: actor.id.clone(),
                            event_id: event.id.clone(),
                            description: format!(
                                "actor lifespan {}-{} ends before event at {}-{}",
                                lifespan.start, lifespan.end,
                                event.time_span.start, event.time_span.end,
                            ),
                        });
                    }
                }
            }

            // Check causal ordering: cause must not be after effect
            for cause_id in &event.caused_by {
                if let Some(&cause_nx) = chronicle.index.get(cause_id)
                    && let Entity::Event(cause_event) = &chronicle.graph[cause_nx]
                    && let Some(cause_iv) = to_interval(&cause_event.time_span)
                    && strictly_before(&event_iv, &cause_iv)
                {
                    report.errors.push(ValidationError::TemporalViolation {
                        entity_id: event.id.clone(),
                        event_id: cause_event.id.clone(),
                        description: format!(
                            "effect {}-{} precedes its cause {}-{}",
                            event.time_span.start, event.time_span.end,
                            cause_event.time_span.start, cause_event.time_span.end,
                        ),
                    });
                    // cause precedes/meets effect = valid; overlap/equal = ambiguous, not error
                }
            }
        }
    }
}

// ── State tracking ─────────────────────────────────────────

fn validate_state(chronicle: &Chronicle, config: &ValidationConfig, report: &mut ValidationReport) {
    let state_changes = collect_state_changes(chronicle);

    for nx in chronicle.graph.node_indices() {
        if let Entity::Event(event) = &chronicle.graph[nx] {
            let Some(event_iv) = to_interval(&event.time_span) else { continue };

            // Check participants aren't in a terminal state from a strictly earlier event
            for p in &event.participants {
                for (entity_id, status, change_time, change_event_id) in &state_changes {
                    if *entity_id == p.actor
                        && config.terminal_statuses.contains(status)
                        && let Some(change_iv) = to_interval(change_time)
                        && strictly_before(&change_iv, &event_iv)
                    {
                        report.errors.push(ValidationError::StateViolation {
                            entity_id: p.actor.clone(),
                            event_id: event.id.clone(),
                            description: format!(
                                "actor '{}' has status {:?} as of '{}' (year {}-{}), \
                                 cannot participate in '{}' (year {}-{})",
                                p.actor, status, change_event_id,
                                change_time.start, change_time.end,
                                event.id, event.time_span.start, event.time_span.end,
                            ),
                        });
                    }
                }
            }

            // Check locations aren't in a terminal state
            if let Some(loc) = &event.location {
                for (entity_id, status, change_time, change_event_id) in &state_changes {
                    if entity_id == loc.as_str()
                        && config.terminal_statuses.contains(status)
                        && let Some(change_iv) = to_interval(change_time)
                        && strictly_before(&change_iv, &event_iv)
                    {
                        report.errors.push(ValidationError::StateViolation {
                            entity_id: loc.clone(),
                            event_id: event.id.clone(),
                            description: format!(
                                "location '{}' has status {:?} as of '{}' (year {}-{}), \
                                 cannot host '{}' (year {}-{})",
                                loc, status, change_event_id,
                                change_time.start, change_time.end,
                                event.id, event.time_span.start, event.time_span.end,
                            ),
                        });
                    }
                }
            }
        }
    }
}

// ── Orphan detection ───────────────────────────────────────

fn validate_orphans(chronicle: &Chronicle, report: &mut ValidationReport) {
    for nx in chronicle.graph.node_indices() {
        let in_deg = chronicle.graph.neighbors_directed(nx, Direction::Incoming).count();
        let out_deg = chronicle.graph.neighbors_directed(nx, Direction::Outgoing).count();
        if in_deg == 0 && out_deg == 0 {
            report.warnings.push(ValidationWarning::OrphanEntity {
                entity_id: chronicle.graph[nx].id().to_owned(),
            });
        }
    }
}

// ── Shared helpers ─────────────────────────────────────────

/// Collect all status changes from events: (entity_id, status, time_span, event_id).
fn collect_state_changes(chronicle: &Chronicle) -> Vec<(String, Status, TimeSpan, String)> {
    let mut changes = Vec::new();
    for nx in chronicle.graph.node_indices() {
        if let Entity::Event(event) = &chronicle.graph[nx] {
            for sc in &event.state_changes {
                if let StateChange::StatusChange(status) = &sc.change {
                    changes.push((
                        sc.entity.clone(),
                        status.clone(),
                        event.time_span.clone(),
                        event.id.clone(),
                    ));
                }
            }
        }
    }
    changes
}

// ── can_add_event ──────────────────────────────────────────

/// Check whether a proposed [`Event`] is consistent with the existing graph.
///
/// Runs referential, temporal, and state checks against the current [`Chronicle`]
/// without modifying it. This is the pre-flight check for inserting new narrative content.
///
/// Returns `Ok(())` if the event can be safely added, or `Err` containing every
/// detected [`ValidationError`] (the list is exhaustive, not short-circuited).
pub fn can_add_event(chronicle: &Chronicle, event: &Event) -> Result<(), Vec<ValidationError>> {
    let mut errors = Vec::new();

    // Duplicate ID check
    if chronicle.index.contains_key(&event.id) {
        errors.push(ValidationError::DanglingReference {
            source_id: event.id.clone(),
            target_id: event.id.clone(),
            context: format!("proposed event '{}' has the same ID as an existing entity", event.id),
        });
    }

    // Referential: all referenced entities must exist
    if let Some(loc) = &event.location
        && !chronicle.index.contains_key(loc.as_str())
    {
        errors.push(ValidationError::DanglingReference {
            source_id: event.id.clone(),
            target_id: loc.clone(),
            context: "location".to_owned(),
        });
    }
    for cause_id in &event.caused_by {
        if !chronicle.index.contains_key(cause_id.as_str()) {
            errors.push(ValidationError::DanglingReference {
                source_id: event.id.clone(),
                target_id: cause_id.clone(),
                context: "caused_by".to_owned(),
            });
        }
    }
    for p in &event.participants {
        if !chronicle.index.contains_key(p.actor.as_str()) {
            errors.push(ValidationError::DanglingReference {
                source_id: event.id.clone(),
                target_id: p.actor.clone(),
                context: "participant".to_owned(),
            });
        }
    }
    for sc in &event.state_changes {
        if !chronicle.index.contains_key(sc.entity.as_str()) {
            errors.push(ValidationError::DanglingReference {
                source_id: event.id.clone(),
                target_id: sc.entity.clone(),
                context: "state_change target".to_owned(),
            });
        }
    }

    // Temporal: lifespan checks for participants
    if let Some(event_iv) = to_interval(&event.time_span) {
        for p in &event.participants {
            if let Some(&actor_nx) = chronicle.index.get(&p.actor)
                && let Entity::Actor(actor) = &chronicle.graph[actor_nx]
                && let Some(lifespan) = &actor.lifespan
                && let Some(life_iv) = to_interval(lifespan)
            {
                if strictly_before(&event_iv, &life_iv) {
                    errors.push(ValidationError::TemporalViolation {
                        entity_id: actor.id.clone(),
                        event_id: event.id.clone(),
                        description: format!(
                            "proposed event '{}' (year {}-{}) precedes actor '{}' lifespan ({}-{})",
                            event.id, event.time_span.start, event.time_span.end,
                            actor.id, lifespan.start, lifespan.end,
                        ),
                    });
                }
                if strictly_before(&life_iv, &event_iv) {
                    errors.push(ValidationError::TemporalViolation {
                        entity_id: actor.id.clone(),
                        event_id: event.id.clone(),
                        description: format!(
                            "actor '{}' lifespan ({}-{}) ends before proposed event '{}' (year {}-{})",
                            actor.id, lifespan.start, lifespan.end,
                            event.id, event.time_span.start, event.time_span.end,
                        ),
                    });
                }
            }
        }

        // Temporal: causal ordering
        for cause_id in &event.caused_by {
            if let Some(&cause_nx) = chronicle.index.get(cause_id.as_str())
                && let Entity::Event(cause_event) = &chronicle.graph[cause_nx]
                && let Some(cause_iv) = to_interval(&cause_event.time_span)
                && strictly_before(&event_iv, &cause_iv)
            {
                errors.push(ValidationError::TemporalViolation {
                    entity_id: event.id.clone(),
                    event_id: cause_event.id.clone(),
                    description: format!(
                        "proposed event '{}' (year {}-{}) precedes its cause '{}' (year {}-{})",
                        event.id, event.time_span.start, event.time_span.end,
                        cause_event.id, cause_event.time_span.start, cause_event.time_span.end,
                    ),
                });
            }
        }

        // State: check participants and location against terminal statuses
        let state_changes = collect_state_changes(chronicle);

        for p in &event.participants {
            for (entity_id, status, change_time, change_event_id) in &state_changes {
                if *entity_id == p.actor
                    && chronicle.config.terminal_statuses.contains(status)
                    && let Some(change_iv) = to_interval(change_time)
                    && strictly_before(&change_iv, &event_iv)
                {
                    errors.push(ValidationError::StateViolation {
                        entity_id: p.actor.clone(),
                        event_id: event.id.clone(),
                        description: format!(
                            "actor '{}' has status {:?} as of '{}' (year {}-{}), \
                             cannot participate in proposed event '{}' (year {}-{})",
                            p.actor, status, change_event_id,
                            change_time.start, change_time.end,
                            event.id, event.time_span.start, event.time_span.end,
                        ),
                    });
                }
            }
        }

        if let Some(loc) = &event.location {
            for (entity_id, status, change_time, change_event_id) in &state_changes {
                if entity_id == loc.as_str()
                    && chronicle.config.terminal_statuses.contains(status)
                    && let Some(change_iv) = to_interval(change_time)
                    && strictly_before(&change_iv, &event_iv)
                {
                    errors.push(ValidationError::StateViolation {
                        entity_id: loc.clone(),
                        event_id: event.id.clone(),
                        description: format!(
                            "location '{}' has status {:?} as of '{}' (year {}-{}), \
                             cannot host proposed event '{}' (year {}-{})",
                            loc, status, change_event_id,
                            change_time.start, change_time.end,
                            event.id, event.time_span.start, event.time_span.end,
                        ),
                    });
                }
            }
        }
    }

    if errors.is_empty() { Ok(()) } else { Err(errors) }
}