chronicle-graph 0.1.1

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
//! Typed query API: method chains over the chronicle graph.

use std::collections::HashSet;
use std::ops::RangeInclusive;

use petgraph::Direction;
use petgraph::stable_graph::NodeIndex;
use petgraph::visit::EdgeRef;

use crate::graph::Chronicle;
use crate::model::*;

// ── Edge-filtered neighbor helper ──────────────────────────

impl Chronicle {
    /// Nodes connected to `nx` via edges matching `pred`, in the given direction.
    fn neighbors_by_edge<F>(&self, nx: NodeIndex, dir: Direction, pred: F) -> Vec<NodeIndex>
    where
        F: Fn(&Relationship) -> bool,
    {
        self.graph
            .edges_directed(nx, dir)
            .filter(|e| pred(e.weight()))
            .map(|e| match dir {
                Direction::Outgoing => e.target(),
                Direction::Incoming => e.source(),
            })
            .collect()
    }
}

// ── Entry points on Chronicle ──────────────────────────────

impl Chronicle {
    /// Look up an actor by id and return a query handle for it.
    ///
    /// Returns `None` if the id does not exist or does not refer to an [`Actor`].
    pub fn actor(&self, id: &str) -> Option<ActorQuery<'_>> {
        let &nx = self.index.get(id)?;
        match &self.graph[nx] {
            Entity::Actor(_) => Some(ActorQuery {
                chronicle: self,
                nx,
            }),
            _ => None,
        }
    }

    /// Look up an event by id and return a query handle for it.
    ///
    /// Returns `None` if the id does not exist or does not refer to an [`Event`].
    pub fn event(&self, id: &str) -> Option<EventQuery<'_>> {
        let &nx = self.index.get(id)?;
        match &self.graph[nx] {
            Entity::Event(_) => Some(EventQuery {
                chronicle: self,
                nx,
            }),
            _ => None,
        }
    }

    /// Look up a place by id and return a query handle for it.
    ///
    /// Returns `None` if the id does not exist or does not refer to a [`Place`].
    pub fn place(&self, id: &str) -> Option<PlaceQuery<'_>> {
        let &nx = self.index.get(id)?;
        match &self.graph[nx] {
            Entity::Place(_) => Some(PlaceQuery {
                chronicle: self,
                nx,
            }),
            _ => None,
        }
    }

    /// Look up a concept by id and return a query handle for it.
    ///
    /// Returns `None` if the id does not exist or does not refer to a [`Concept`].
    pub fn concept(&self, id: &str) -> Option<ConceptQuery<'_>> {
        let &nx = self.index.get(id)?;
        match &self.graph[nx] {
            Entity::Concept(_) => Some(ConceptQuery {
                chronicle: self,
                nx,
            }),
            _ => None,
        }
    }

    /// All accounts whose text contains a `{entity_id}` reference to this entity.
    pub fn mentions(&self, entity_id: &str) -> Vec<&Account> {
        let Some(&target_nx) = self.index.get(entity_id) else {
            return vec![];
        };
        let mut seen = HashSet::new();
        self.neighbors_by_edge(target_nx, Direction::Incoming, |r| {
            matches!(r, Relationship::Mentions)
        })
        .iter()
        .filter(|&&nx| seen.insert(nx))
        .filter_map(|&nx| match &self.graph[nx] {
            Entity::Account(a) => Some(a),
            _ => None,
        })
        .collect()
    }

    /// All accounts that reference this event (via AccountOf edges).
    pub fn accounts_of(&self, event_id: &str) -> Vec<&Account> {
        let Some(&target_nx) = self.index.get(event_id) else {
            return vec![];
        };
        let mut seen = HashSet::new();
        self.neighbors_by_edge(target_nx, Direction::Incoming, |r| {
            matches!(r, Relationship::AccountOf)
        })
        .iter()
        .filter(|&&nx| seen.insert(nx))
        .filter_map(|&nx| match &self.graph[nx] {
            Entity::Account(a) => Some(a),
            _ => None,
        })
        .collect()
    }

    /// All accounts authored by a given source.
    pub fn accounts_by(&self, source_id: &str) -> Vec<&Account> {
        let Some(&source_nx) = self.index.get(source_id) else {
            return vec![];
        };
        let mut seen = HashSet::new();
        self.neighbors_by_edge(source_nx, Direction::Incoming, |r| {
            matches!(r, Relationship::AuthoredBy)
        })
        .iter()
        .filter(|&&nx| seen.insert(nx))
        .filter_map(|&nx| match &self.graph[nx] {
            Entity::Account(a) => Some(a),
            _ => None,
        })
        .collect()
    }
}

// ── ActorQuery ─────────────────────────────────────────────

/// Query handle for an [`Actor`] node in the chronicle graph.
///
/// Provides methods to inspect the actor's data, events, interactions,
/// and computed status at a point in time.
pub struct ActorQuery<'a> {
    chronicle: &'a Chronicle,
    nx: NodeIndex,
}

impl<'a> ActorQuery<'a> {
    /// Returns a reference to the underlying [`Actor`] data.
    pub fn data(&self) -> &'a Actor {
        match &self.chronicle.graph[self.nx] {
            Entity::Actor(a) => a,
            _ => unreachable!(),
        }
    }

    /// All events this actor participated in.
    pub fn events(&self) -> Vec<&'a Event> {
        self.chronicle
            .neighbors_by_edge(self.nx, Direction::Incoming, |r| {
                matches!(r, Relationship::ParticipatedIn { .. })
            })
            .iter()
            .filter_map(|&nx| match &self.chronicle.graph[nx] {
                Entity::Event(e) => Some(e),
                _ => None,
            })
            .collect()
    }

    /// Events filtered by time range.
    pub fn events_during(&self, range: RangeInclusive<i32>) -> Vec<&'a Event> {
        self.events()
            .into_iter()
            .filter(|e| e.time_span.start <= *range.end() && e.time_span.end >= *range.start())
            .collect()
    }

    /// Events filtered by location.
    pub fn events_at(&self, place_id: &str) -> Vec<&'a Event> {
        self.events()
            .into_iter()
            .filter(|e| e.location.as_deref() == Some(place_id))
            .collect()
    }

    /// All other actors this actor has co-participated in events with.
    pub fn interactions(&self) -> InteractionResult<'a> {
        let mut actors = Vec::new();
        for event in self.events() {
            for p in &event.participants {
                if p.actor != self.data().id
                    && let Some(q) = self.chronicle.actor(&p.actor)
                    && !actors.iter().any(|a: &&Actor| a.id == q.data().id)
                {
                    actors.push(q.data());
                }
            }
        }
        InteractionResult { actors }
    }

    /// Status at a given point in time, computed from state changes.
    pub fn status_at(&self, year: i32) -> Status {
        status_at_impl(self.chronicle, &self.data().id, year)
    }
}

// ── InteractionResult ──────────────────────────────────────

/// The result of an actor interaction query, containing the set of
/// co-participating actors discovered across shared events.
pub struct InteractionResult<'a> {
    actors: Vec<&'a Actor>,
}

impl<'a> InteractionResult<'a> {
    /// Returns all co-participating actors as a slice.
    pub fn all(&self) -> &[&'a Actor] {
        &self.actors
    }

    /// Returns only actors of type [`ActorType::Character`].
    pub fn people(&self) -> Vec<&'a Actor> {
        self.actors
            .iter()
            .filter(|a| a.actor_type == ActorType::Character)
            .copied()
            .collect()
    }

    /// Returns only actors of type [`ActorType::Faction`].
    pub fn factions(&self) -> Vec<&'a Actor> {
        self.actors
            .iter()
            .filter(|a| a.actor_type == ActorType::Faction)
            .copied()
            .collect()
    }
}

// ── EventQuery ─────────────────────────────────────────────

/// Query handle for an [`Event`] node in the chronicle graph.
///
/// Provides methods to inspect participants, location, causal chains,
/// consequences, and state changes.
pub struct EventQuery<'a> {
    chronicle: &'a Chronicle,
    nx: NodeIndex,
}

impl<'a> EventQuery<'a> {
    /// Returns a reference to the underlying [`Event`] data.
    pub fn data(&self) -> &'a Event {
        match &self.chronicle.graph[self.nx] {
            Entity::Event(e) => e,
            _ => unreachable!(),
        }
    }

    /// All participants in this event.
    pub fn participants(&self) -> Vec<&'a Participant> {
        self.data().participants.iter().collect()
    }

    /// Participants filtered by role.
    pub fn participants_by_role(&self, role: Role) -> Vec<&'a Participant> {
        self.data()
            .participants
            .iter()
            .filter(|p| p.role == role)
            .collect()
    }

    /// The location of this event, if any.
    pub fn location(&self) -> Option<&'a Place> {
        let loc_id = self.data().location.as_ref()?;
        let &nx = self.chronicle.index.get(loc_id.as_str())?;
        match &self.chronicle.graph[nx] {
            Entity::Place(p) => Some(p),
            _ => None,
        }
    }

    /// Direct causes of this event.
    pub fn caused_by(&self) -> Vec<&'a Event> {
        self.data()
            .caused_by
            .iter()
            .filter_map(|id| {
                let &nx = self.chronicle.index.get(id.as_str())?;
                match &self.chronicle.graph[nx] {
                    Entity::Event(e) => Some(e),
                    _ => None,
                }
            })
            .collect()
    }

    /// Full causal chain backward (BFS through caused_by).
    pub fn causal_chain(&self) -> Vec<&'a Event> {
        let mut chain = Vec::new();
        let mut queue = std::collections::VecDeque::new();
        let mut visited = HashSet::new();

        for cause in &self.data().caused_by {
            if let Some(&nx) = self.chronicle.index.get(cause.as_str()) {
                queue.push_back(nx);
            }
        }

        while let Some(nx) = queue.pop_front() {
            if !visited.insert(nx) {
                continue;
            }
            if let Entity::Event(e) = &self.chronicle.graph[nx] {
                chain.push(e);
                for cause_id in &e.caused_by {
                    if let Some(&cause_nx) = self.chronicle.index.get(cause_id.as_str()) {
                        queue.push_back(cause_nx);
                    }
                }
            }
        }
        chain
    }

    /// Events caused by this one (forward consequences via CausedBy edges).
    pub fn consequences(&self) -> Vec<&'a Event> {
        self.chronicle
            .neighbors_by_edge(self.nx, Direction::Incoming, |r| {
                matches!(r, Relationship::CausedBy)
            })
            .iter()
            .filter_map(|&nx| match &self.chronicle.graph[nx] {
                Entity::Event(e) => Some(e),
                _ => None,
            })
            .collect()
    }

    /// State changes produced by this event.
    pub fn state_changes(&self) -> &[EventStateChange] {
        &self.data().state_changes
    }
}

// ── PlaceQuery ─────────────────────────────────────────────

/// Query handle for a [`Place`] node in the chronicle graph.
///
/// Provides methods to inspect events at this location, actors present
/// at a point in time, and computed status.
pub struct PlaceQuery<'a> {
    chronicle: &'a Chronicle,
    nx: NodeIndex,
}

impl<'a> PlaceQuery<'a> {
    /// Returns a reference to the underlying [`Place`] data.
    pub fn data(&self) -> &'a Place {
        match &self.chronicle.graph[self.nx] {
            Entity::Place(p) => p,
            _ => unreachable!(),
        }
    }

    /// All events at this place.
    pub fn events(&self) -> Vec<&'a Event> {
        self.chronicle
            .neighbors_by_edge(self.nx, Direction::Incoming, |r| {
                matches!(r, Relationship::OccurredAt)
            })
            .iter()
            .filter_map(|&nx| match &self.chronicle.graph[nx] {
                Entity::Event(e) => Some(e),
                _ => None,
            })
            .collect()
    }

    /// Events at this place filtered by time range.
    pub fn events_during(&self, range: RangeInclusive<i32>) -> Vec<&'a Event> {
        self.events()
            .into_iter()
            .filter(|e| e.time_span.start <= *range.end() && e.time_span.end >= *range.start())
            .collect()
    }

    /// All actors who participated in events at this place during a given year.
    pub fn actors_present_at(&self, year: i32) -> Vec<&'a Actor> {
        let mut actors = Vec::new();
        for event in self.events() {
            if event.time_span.start <= year && event.time_span.end >= year {
                for p in &event.participants {
                    if let Some(q) = self.chronicle.actor(&p.actor)
                        && !actors.iter().any(|a: &&Actor| a.id == q.data().id)
                    {
                        actors.push(q.data());
                    }
                }
            }
        }
        actors
    }

    /// Status at a given point in time.
    pub fn status_at(&self, year: i32) -> Status {
        status_at_impl(self.chronicle, &self.data().id, year)
    }
}

// ── ConceptQuery ───────────────────────────────────────────

/// Query handle for a [`Concept`] node in the chronicle graph.
///
/// Provides methods to inspect the concept's data and its origin event.
pub struct ConceptQuery<'a> {
    chronicle: &'a Chronicle,
    nx: NodeIndex,
}

impl<'a> ConceptQuery<'a> {
    /// Returns a reference to the underlying [`Concept`] data.
    pub fn data(&self) -> &'a Concept {
        match &self.chronicle.graph[self.nx] {
            Entity::Concept(c) => c,
            _ => unreachable!(),
        }
    }

    /// The event that originated this concept, if any.
    pub fn origin_event(&self) -> Option<&'a Event> {
        let origin_id = self.data().origin_event.as_ref()?;
        let &nx = self.chronicle.index.get(origin_id.as_str())?;
        match &self.chronicle.graph[nx] {
            Entity::Event(e) => Some(e),
            _ => None,
        }
    }
}

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

/// Compute status at a point in time by scanning state changes.
/// Starts from Active and applies state changes up to the queried year in chronological order.
fn status_at_impl(chronicle: &Chronicle, entity_id: &str, year: i32) -> Status {
    let mut changes: Vec<(i32, &Status)> = Vec::new();

    for nx in chronicle.graph.node_indices() {
        if let Entity::Event(event) = &chronicle.graph[nx]
            && event.time_span.end <= year
        {
            for sc in &event.state_changes {
                if sc.entity == entity_id
                    && let StateChange::StatusChange(s) = &sc.change
                {
                    changes.push((event.time_span.end, s));
                }
            }
        }
    }

    changes.sort_by_key(|(time, _)| *time);
    changes
        .last()
        .map(|(_, s)| (*s).clone())
        .unwrap_or(Status::Active)
}