Skip to main content

kernel/graph/
journal.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! The edit spine: mere's captured-delta stream over the substrate log.
8//!
9//! The graph's durable mutations already exist as a stream of [`CapturedDelta`]s
10//! (stable-id, serializable), emitted through the capture hook as each live
11//! [`GraphDelta`](super::apply::GraphDelta) applies (see `capture.rs`). This module
12//! gives that stream its principled home: a [`muniment::Journal`] of captured
13//! deltas, the append-only log primitive shared across the Merely apps. The
14//! materialized graph is the *replay* of the journal, and because live editing and
15//! replay both funnel through `apply_graph_delta`, the two cannot diverge. What an
16//! edit reads from the clock or mints (a new node's visit stamp, a statement id)
17//! is journaled beside it, so replay reproduces those too.
18//!
19//! This is the edit spine over the substrate. mere keeps its own rich edit
20//! vocabulary — `CapturedDelta` carries content edits (title, tags, body,
21//! navigation) that chartulary's topology-only `GraphEdit` deliberately cannot
22//! express, and muniment supplies the ordered, forkable, persistable log beneath
23//! it. Checkpointing reuses mere's existing `GraphSnapshot`: load a snapshot, then
24//! [`replay_from`](GraphJournal::replay_from) the journal tail past its sequence,
25//! mirroring `chartulary::GraphLog::load_checkpointed`.
26//!
27//! WASM-clean: muniment is the substrate's portable persistence primitive (the
28//! same ones the browser persists through), so this module compiles to
29//! `wasm32-unknown-unknown` like the rest of `graph/`.
30
31use std::sync::{Arc, Mutex};
32
33use muniment::{Backend, Codec, SlotStore, StoreError};
34use muniment::{Journal, LogId, Provenance, Seq};
35
36use rkyv::{Archive, Deserialize, Serialize};
37
38use super::Graph;
39use super::capture::{
40    CapturedDelta, DeltaRecorder, OnRefusal, ReplayAttribution, ReplayRefused,
41    replay_attributed_deltas_onto, replay_outcomes_onto,
42};
43use super::source_time::{SourceExtent, SourceTime};
44
45/// The id the trusted UI's person records under when the host has no persona
46/// to name: see [`Author::user`].
47pub const USER_AUTHOR: &str = "user";
48
49/// What kind of author made a change: a person, or a rule, script or engine
50/// acting at some version (the ambiance design's moves between keeping levels
51/// record the same four).
52#[derive(
53    Debug,
54    Clone,
55    Copy,
56    PartialEq,
57    Eq,
58    Hash,
59    Archive,
60    Serialize,
61    Deserialize,
62    serde::Serialize,
63    serde::Deserialize,
64)]
65#[serde(rename_all = "snake_case")]
66pub enum AuthorKind {
67    Person,
68    Rule,
69    Script,
70    Engine,
71}
72
73/// Who or what made a journal entry, and through which application.
74///
75/// Every field is always written, since a positional codec cannot read back a
76/// field written conditionally.
77#[derive(
78    Debug,
79    Clone,
80    PartialEq,
81    Eq,
82    Hash,
83    Archive,
84    Serialize,
85    Deserialize,
86    serde::Serialize,
87    serde::Deserialize,
88)]
89pub struct Author {
90    pub kind: AuthorKind,
91    /// A persona or subject id for a person; the rule's, script's or engine's
92    /// name otherwise.
93    pub id: String,
94    /// The rule's, script's or engine's version. A person has none.
95    pub version: Option<String>,
96    /// The application the change came through. A resident fills this in
97    /// from the admitted route rather than taking the client's word for it.
98    pub via: Option<String>,
99}
100
101impl Author {
102    /// Stable assertion attribution; version and recording application stay metadata.
103    pub fn asserter_iri(&self) -> String {
104        if self.kind == AuthorKind::Person
105            && !self.id.chars().any(|c| c.is_whitespace() || c.is_control())
106            && url::Url::parse(&self.id).is_ok()
107        {
108            return self.id.clone();
109        }
110        let kind = match self.kind {
111            AuthorKind::Person => "person",
112            AuthorKind::Rule => "rule",
113            AuthorKind::Script => "script",
114            AuthorKind::Engine => "engine",
115        };
116        let encoded: String = url::form_urlencoded::byte_serialize(self.id.as_bytes()).collect();
117        format!("https://mere.computer/ns/agent#{kind}/{encoded}")
118    }
119
120    /// A person, by persona or subject id.
121    pub fn person(id: impl Into<String>) -> Self {
122        Self::new(AuthorKind::Person, id, None)
123    }
124
125    /// The person at the trusted UI, when the host has no persona to name.
126    pub fn user() -> Self {
127        Self::person(USER_AUTHOR)
128    }
129
130    /// A rule at a version.
131    pub fn rule(id: impl Into<String>, version: impl Into<String>) -> Self {
132        Self::new(AuthorKind::Rule, id, Some(version.into()))
133    }
134
135    /// A script at a version.
136    pub fn script(id: impl Into<String>, version: impl Into<String>) -> Self {
137        Self::new(AuthorKind::Script, id, Some(version.into()))
138    }
139
140    /// An engine at a version.
141    pub fn engine(id: impl Into<String>, version: impl Into<String>) -> Self {
142        Self::new(AuthorKind::Engine, id, Some(version.into()))
143    }
144
145    fn new(kind: AuthorKind, id: impl Into<String>, version: Option<String>) -> Self {
146        Self {
147            kind,
148            id: id.into(),
149            version,
150            via: None,
151        }
152    }
153
154    /// The same author, arriving through `application`.
155    pub fn via(mut self, application: impl Into<String>) -> Self {
156        self.via = Some(application.into());
157        self
158    }
159}
160
161impl std::fmt::Display for Author {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        let kind = match self.kind {
164            AuthorKind::Person => "person",
165            AuthorKind::Rule => "rule",
166            AuthorKind::Script => "script",
167            AuthorKind::Engine => "engine",
168        };
169        write!(f, "{kind} {}", self.id)?;
170        if let Some(version) = &self.version {
171            write!(f, " {version}")?;
172        }
173        if let Some(via) = &self.via {
174            write!(f, " via {via}")?;
175        }
176        Ok(())
177    }
178}
179
180/// One journal entry: a captured delta in the attribution envelope — the
181/// participant-gate plan's B1 adoption of chartulary's `Batch { author, edits }`
182/// shape over mere's edit spine. WHO made a change rides the journal, so a
183/// participant's edits read back attributed and compensable.
184#[derive(
185    Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
186)]
187pub struct AttributedDelta {
188    pub author: Author,
189    pub delta: CapturedDelta,
190}
191
192/// An append-only journal of a graph's captured edits: the persisted edit
193/// spine. The materialized [`Graph`] is the replay of this log; forking it forks
194/// the graph's whole history with provenance, and it persists whole through one
195/// muniment slot.
196#[derive(Clone, Debug)]
197pub struct GraphJournal {
198    log: Journal<AttributedDelta>,
199    /// The author the next [`record`](Self::record) attributes: [`Author::user`]
200    /// by default; a host scopes a participant run with
201    /// [`set_author`](Self::set_author) and restores afterwards.
202    author: Author,
203}
204
205impl Default for GraphJournal {
206    fn default() -> Self {
207        Self {
208            log: Journal::default(),
209            author: Author::user(),
210        }
211    }
212}
213
214impl GraphJournal {
215    /// A fresh, empty journal, recording as [`Author::user`].
216    pub fn new() -> Self {
217        Self::default()
218    }
219
220    /// A journal with a stable identity, so it can later be forked with
221    /// provenance pointing back at it.
222    pub fn with_id(id: LogId) -> Self {
223        Self {
224            log: Journal::with_id(id),
225            author: Author::user(),
226        }
227    }
228
229    /// An empty journal that starts where `provenance` says another left off,
230    /// without copying its entries: the keeper holds the graph they built as a
231    /// snapshot. A session forked at a cursor starts this way.
232    pub fn starting_from(id: LogId, provenance: Provenance) -> Self {
233        Self::from_log(Journal::starting_from(id, provenance))
234    }
235
236    /// Adopt an existing journal of attributed deltas (e.g. one just loaded
237    /// from a store or received from a peer).
238    pub fn from_log(log: Journal<AttributedDelta>) -> Self {
239        Self {
240            log,
241            author: Author::user(),
242        }
243    }
244
245    /// The author subsequent [`record`](Self::record)s attribute.
246    pub fn author(&self) -> &Author {
247        &self.author
248    }
249
250    /// Scope the recording author (a participant run); the host restores the
251    /// previous one when the run ends.
252    pub fn set_author(&mut self, author: Author) {
253        self.author = author;
254    }
255
256    /// Append one captured edit under the current author, returning the [`Seq`]
257    /// it was stamped with. This is the write path: a live mutation's capture
258    /// lands here (usually via [`journal_capture_hook`]).
259    pub fn record(&mut self, delta: CapturedDelta) -> Seq {
260        let author = self.author.clone();
261        self.record_as(author, delta)
262    }
263
264    /// Append one captured edit under an explicit author (the gate path).
265    pub fn record_as(&mut self, author: Author, delta: CapturedDelta) -> Seq {
266        self.log.append(AttributedDelta { author, delta })
267    }
268
269    /// The underlying journal, for cursors, replication, and persistence.
270    pub fn log(&self) -> &Journal<AttributedDelta> {
271        &self.log
272    }
273
274    /// Every attributed edit, oldest first.
275    pub fn entries(&self) -> &[AttributedDelta] {
276        self.log.entries()
277    }
278
279    /// The number of edits recorded.
280    pub fn len(&self) -> usize {
281        self.log.len()
282    }
283
284    /// Whether the journal holds no edits.
285    pub fn is_empty(&self) -> bool {
286        self.log.is_empty()
287    }
288
289    /// The [`Seq`] the next recorded edit will receive — a durable cursor a
290    /// checkpoint can store to resume replay from.
291    pub fn next_seq(&self) -> Seq {
292        self.log.next_seq()
293    }
294
295    /// The earliest source-time cursor: the empty graph before the first
296    /// captured delta. Journal source time is a **prefix cursor**, so this is
297    /// intentionally `Seq(0)` even though no entry is addressed there yet.
298    pub const fn earliest_cursor(&self) -> Seq {
299        Seq(0)
300    }
301
302    /// The current live source-time cursor: the prefix immediately after the
303    /// newest captured delta. Appending later deltas never changes the graph a
304    /// previously returned cursor replays to.
305    pub fn live_cursor(&self) -> Seq {
306        self.next_seq()
307    }
308
309    /// Materialize graph truth at a journal prefix cursor without changing the
310    /// journal or its current live graph. `Seq(n)` replays exactly the first
311    /// `n` entries; `Seq(0)` is empty and [`live_cursor`](Self::live_cursor)
312    /// replays every current entry. A cursor beyond the known prefix is stale
313    /// and is refused rather than silently clamped to live.
314    pub fn snapshot_at(&self, cursor: Seq) -> Result<Option<Graph>, ReplayRefused> {
315        self.snapshot_at_from(&Graph::new(), cursor)
316    }
317
318    /// Replay a prefix over its retained baseline, preserving baseline attribution.
319    pub fn snapshot_at_from(
320        &self,
321        baseline: &Graph,
322        cursor: Seq,
323    ) -> Result<Option<Graph>, ReplayRefused> {
324        let end = cursor.index();
325        if end > self.log.len() {
326            return Ok(None);
327        }
328        let mut graph = baseline.clone();
329        replay_entries_onto(&mut graph, &self.log.entries()[..end], OnRefusal::Stop)?;
330        Ok(Some(graph))
331    }
332
333    /// Migration of a caller-qualified legacy baseline and prefix.
334    /// Ordinary replay does not infer a legacy profile from absent resource columns.
335    pub fn migrated_prefix_at_from(
336        &self,
337        baseline: &Graph,
338        cursor: Seq,
339    ) -> Result<
340        Option<super::legacy_resource_migration::MigratedReplay>,
341        super::legacy_resource_migration::LegacyMigrationError,
342    > {
343        let end = cursor.index();
344        if end > self.log.len() {
345            return Ok(None);
346        }
347        super::legacy_resource_migration::migrate_legacy_prefix(
348            baseline,
349            &self.log.entries()[..end],
350        )
351        .map(Some)
352    }
353
354    /// Validate choices against this complete qualified legacy journal, then read a prefix.
355    /// Future carried-handle choices do not change or invalidate earlier prefixes.
356    /// A host with a modern suffix must supply only its qualified legacy prefix to the adapter.
357    pub fn migrated_prefix_at_from_with_resolutions(
358        &self,
359        baseline: &Graph,
360        cursor: Seq,
361        resolutions: &[super::legacy_resource_migration::LegacyResourceOriginResolution],
362    ) -> Result<
363        Option<super::legacy_resource_migration::MigratedReplay>,
364        super::legacy_resource_migration::LegacyMigrationError,
365    > {
366        use super::legacy_resource_migration::{
367            migrate_legacy_prefix_with_resolutions, probe_legacy_mint_links,
368            validate_legacy_origin_resolutions,
369        };
370        let end = cursor.index();
371        if end > self.log.len() {
372            return Ok(None);
373        }
374        validate_legacy_origin_resolutions(baseline, self.log.entries(), resolutions)?;
375        let prefix = &self.log.entries()[..end];
376        let ids: std::collections::BTreeSet<_> = probe_legacy_mint_links(baseline, prefix)?
377            .into_iter()
378            .map(|diagnostic| diagnostic.statement_id)
379            .collect();
380        let relevant: Vec<_> = resolutions
381            .iter()
382            .filter(|choice| ids.contains(&choice.statement_id))
383            .cloned()
384            .collect();
385        migrate_legacy_prefix_with_resolutions(baseline, prefix, &relevant).map(Some)
386    }
387
388    pub fn migrated_snapshot_at_from_with_resolutions(
389        &self,
390        baseline: &Graph,
391        cursor: Seq,
392        resolutions: &[super::legacy_resource_migration::LegacyResourceOriginResolution],
393    ) -> Result<Option<Graph>, super::legacy_resource_migration::LegacyMigrationError> {
394        self.migrated_prefix_at_from_with_resolutions(baseline, cursor, resolutions)
395            .map(|replay| replay.map(|replay| replay.graph))
396    }
397
398    /// The graph-only convenience form of [`migrated_prefix_at_from`](Self::migrated_prefix_at_from).
399    pub fn migrated_snapshot_at_from(
400        &self,
401        baseline: &Graph,
402        cursor: Seq,
403    ) -> Result<Option<Graph>, super::legacy_resource_migration::LegacyMigrationError> {
404        self.migrated_prefix_at_from(baseline, cursor)
405            .map(|replay| replay.map(|replay| replay.graph))
406    }
407
408    /// Reconstruct retained history before replacing a legacy checkpoint atomically.
409    /// The full prefix supplies historical URLs and withdrawn handles; `since` is
410    /// validated but cannot substitute the checkpoint's current URL for that evidence.
411    pub fn migrated_replay_from_with_baseline(
412        &self,
413        since: Seq,
414        graph: &mut Graph,
415        baseline: &Graph,
416    ) -> Result<(), super::legacy_resource_migration::LegacyMigrationError> {
417        self.migrated_replay_from_with_baseline_and_resolutions(since, graph, baseline, &[])
418    }
419
420    pub fn migrated_replay_from_with_baseline_and_resolutions(
421        &self,
422        since: Seq,
423        graph: &mut Graph,
424        baseline: &Graph,
425        resolutions: &[super::legacy_resource_migration::LegacyResourceOriginResolution],
426    ) -> Result<(), super::legacy_resource_migration::LegacyMigrationError> {
427        if since.index() > self.log.len() {
428            return Err(super::legacy_resource_migration::LegacyMigrationError(
429                "legacy checkpoint cursor is beyond retained history".into(),
430            ));
431        }
432        let mut replay = self
433            .migrated_prefix_at_from_with_resolutions(baseline, self.live_cursor(), resolutions)?
434            .expect("live cursor exists");
435        replay.graph.recorder.0 = graph.recorder.0.take();
436        replay.graph.write_author = graph.write_author.clone();
437        replay.graph.current_session = graph.current_session;
438        replay.graph.revision = replay.graph.revision.max(graph.revision).saturating_add(1);
439        replay.graph.url_grouping_revision = replay
440            .graph
441            .url_grouping_revision
442            .max(graph.url_grouping_revision)
443            .saturating_add(1);
444        *graph = replay.graph;
445        Ok(())
446    }
447
448    /// Stable, evenly distributed prefix cursors for a compact scrubber. This
449    /// uses sequence order alone: journal history has no required wall-clock
450    /// timestamp. `max_points == 1` yields only the current live cursor;
451    /// larger requests always include both earliest and live when distinct.
452    pub fn sequence_ticks(&self, max_points: usize) -> Vec<Seq> {
453        let live = self.live_cursor();
454        if max_points == 0 {
455            return Vec::new();
456        }
457        if max_points == 1 || live.0 == 0 {
458            return vec![live];
459        }
460        let points = max_points.min(live.0 as usize + 1);
461        let denominator = (points - 1) as u64;
462        (0..points)
463            .map(|index| Seq((index as u64 * live.0) / denominator))
464            .collect()
465    }
466
467    /// This journal's log identity, if any.
468    pub fn id(&self) -> Option<&LogId> {
469        self.log.id()
470    }
471
472    /// Where this journal forked from, if it is a fork.
473    pub fn provenance(&self) -> Option<&Provenance> {
474        self.log.provenance()
475    }
476
477    /// Rebuild the whole graph, using its author for legacy unattributed assertions.
478    pub fn replay(&self) -> Graph {
479        let mut graph = Graph::new();
480        // A whole-log rebuild drops a refused entry and keeps going; checked
481        // readers use `snapshot_at`.
482        let _ = replay_entries_onto(&mut graph, self.log.entries(), OnRefusal::Drop);
483        graph
484    }
485
486    /// Advance an already-materialized `graph` by the edits from `since` onward.
487    /// The checkpoint-plus-tail path: restore a `GraphSnapshot`, then apply only
488    /// the journal entries recorded after the snapshot's sequence. The incremental
489    /// twin of [`replay`](Self::replay).
490    /// Without a retained baseline, exact records missing attribution stay unknown.
491    /// Use [`replay_from_with_baseline`](Self::replay_from_with_baseline) to recover
492    /// the original minting author across earlier removal and later restoration.
493    pub fn replay_from(&self, since: Seq, graph: &mut Graph) -> Result<(), ReplayRefused> {
494        replay_outcomes_onto(
495            graph,
496            self.log
497                .from(since)
498                .iter()
499                .map(|entry| entry.delta.replay_as(&entry.author)),
500            OnRefusal::Stop,
501        )
502    }
503
504    /// Replay a checkpoint tail with the baseline and original minting entries.
505    /// `baseline` is the graph before entry zero, not the checkpoint at `since`.
506    pub fn replay_from_with_baseline(
507        &self,
508        since: Seq,
509        graph: &mut Graph,
510        baseline: &Graph,
511    ) -> Result<(), ReplayRefused> {
512        let mut attribution = ReplayAttribution::from_baseline(baseline);
513        // Reconstruct prefix evidence on one shadow graph. Pair/kind legacy
514        // attribution needs ordered membership transitions, while cloning the
515        // graph once per journal entry would make checkpoint replay quadratic.
516        let mut shadow = baseline.clone();
517        replay_attributed_deltas_onto(
518            &mut shadow,
519            &mut attribution,
520            self.log.entries().iter().take(since.index()),
521            OnRefusal::Stop,
522        )?;
523        attribution.repair_checkpoint(graph);
524        replay_attributed_deltas_onto(
525            graph,
526            &mut attribution,
527            self.log.from(since),
528            OnRefusal::Stop,
529        )
530    }
531
532    /// Fork this journal under a new identity: copies the whole edit history and
533    /// records where it branched from, then diverges independently. The log-level
534    /// mirror of a graph fork; the fork replays to an identical graph and then
535    /// edits without touching the source.
536    pub fn fork(&self, new_id: LogId) -> Self {
537        Self {
538            log: self.log.fork(new_id),
539            author: self.author.clone(),
540        }
541    }
542
543    /// Write the whole journal to the muniment slot at `key`.
544    pub async fn save<B: Backend, C: Codec>(
545        &self,
546        slots: &SlotStore<B, C>,
547        key: &str,
548    ) -> Result<(), StoreError> {
549        self.log.save(slots, key).await
550    }
551
552    /// Load a journal from the muniment slot at `key`, or an empty journal if the
553    /// slot is absent.
554    pub async fn load<B: Backend, C: Codec>(
555        slots: &SlotStore<B, C>,
556        key: &str,
557    ) -> Result<Self, StoreError> {
558        Ok(Self::from_log(Journal::load(slots, key).await?))
559    }
560}
561
562fn replay_entries_onto<'a, I>(
563    graph: &mut Graph,
564    entries: I,
565    on_refusal: OnRefusal,
566) -> Result<(), ReplayRefused>
567where
568    I: IntoIterator<Item = &'a AttributedDelta>,
569{
570    let mut attribution = ReplayAttribution::from_baseline(graph);
571    replay_attributed_deltas_onto(graph, &mut attribution, entries, on_refusal)
572}
573
574impl SourceTime for GraphJournal {
575    type Cursor = Seq;
576    type Snapshot = Graph;
577
578    fn source_extent(&self) -> SourceExtent<Self::Cursor> {
579        SourceExtent {
580            earliest: self.earliest_cursor(),
581            current: self.live_cursor(),
582        }
583    }
584
585    fn source_ticks(&self, max_points: usize) -> Vec<Self::Cursor> {
586        self.sequence_ticks(max_points)
587    }
588
589    fn source_snapshot(&self, cursor: &Self::Cursor) -> Option<Self::Snapshot> {
590        self.snapshot_at(*cursor).ok().flatten()
591    }
592}
593
594/// A shared journal plus a capture hook that records every emitted
595/// [`CapturedDelta`] into it. Install the hook with
596/// [`set_captured_delta_hook`](super::set_captured_delta_hook) and keep the handle
597/// to replay or persist the journal:
598///
599/// ```ignore
600/// let (journal, hook) = journal_capture_hook();
601/// kernel::graph::set_captured_delta_hook(Some(hook));
602/// // ... drive live mutations through apply_graph_delta ...
603/// let restored = journal.lock().unwrap().replay();
604/// ```
605///
606/// The capture hook is one per-thread slot, so this replaces any previously
607/// installed hook. It is offered as the host's journal-backed persistence path.
608pub fn journal_capture_hook() -> (Arc<Mutex<GraphJournal>>, DeltaRecorder) {
609    let journal = Arc::new(Mutex::new(GraphJournal::new()));
610    let sink = Arc::clone(&journal);
611    let hook: DeltaRecorder = Arc::new(move |delta| {
612        if let Ok(mut journal) = sink.lock() {
613            journal.record(delta.clone());
614        }
615    });
616    (journal, hook)
617}
618
619#[cfg(test)]
620mod tests {
621    use super::*;
622    use crate::graph::apply::{GraphDelta, GraphDeltaResult, apply_graph_delta};
623    use crate::graph::capture::{replay_captured_deltas, replay_captured_deltas_onto};
624    use crate::graph::set_captured_delta_hook;
625    use crate::graph::{EdgeAssertion, SemanticSubKind, SourceExtent, SourceTime};
626    use euclid::default::Point2D;
627    use uuid::Uuid;
628
629    #[test]
630    fn assertion_attribution_ignores_automated_versions_and_recording_application() {
631        for kind in [AuthorKind::Rule, AuthorKind::Script, AuthorKind::Engine] {
632            let v1 = Author::new(kind, "extractor", Some("1".into())).via("turnstone");
633            let v2 = Author::new(kind, "extractor", Some("2".into())).via("knot");
634            assert_ne!(v1, v2, "the journal keeps version and application metadata");
635            assert_eq!(v1.asserter_iri(), v2.asserter_iri());
636            assert_ne!(
637                v1.asserter_iri(),
638                Author::new(kind, "another-extractor", Some("1".into())).asserter_iri(),
639                "different names still identify different asserters"
640            );
641        }
642        let kinds = [
643            Author::person("extractor"),
644            Author::rule("extractor", "1"),
645            Author::script("extractor", "1"),
646            Author::engine("extractor", "1"),
647        ];
648        let identities: std::collections::BTreeSet<_> =
649            kinds.iter().map(Author::asserter_iri).collect();
650        assert_eq!(identities.len(), kinds.len());
651    }
652
653    #[test]
654    fn assertion_attribution_keeps_person_iris_and_encodes_opaque_ids() {
655        for iri in [
656            "https://people.test/alice",
657            "did:key:z6MkAlice",
658            "urn:uuid:058e1fe2-851b-4f1c-bbf0-0cbf74fe7727",
659        ] {
660            assert_eq!(Author::person(iri).asserter_iri(), iri);
661        }
662        let person = Author::person("alice /+?#%名字");
663        assert_eq!(
664            person.asserter_iri(),
665            "https://mere.computer/ns/agent#person/alice+%2F%2B%3F%23%25%E5%90%8D%E5%AD%97"
666        );
667        assert_eq!(
668            person.asserter_iri(),
669            person.clone().via("knot").asserter_iri()
670        );
671        assert!(url::Url::parse(&person.asserter_iri()).is_ok());
672        assert_ne!(
673            Author::person("alice /+?#%名字").asserter_iri(),
674            Author::person("alice +?#%名字").asserter_iri()
675        );
676        assert_ne!(
677            Author::person(".").asserter_iri(),
678            Author::person("..").asserter_iri(),
679            "opaque dot segments are preserved in the fragment"
680        );
681        assert_eq!(
682            Author::person(" https://people.test/alice ").asserter_iri(),
683            "https://mere.computer/ns/agent#person/+https%3A%2F%2Fpeople.test%2Falice+"
684        );
685    }
686
687    fn add(id: u128, url: &str) -> CapturedDelta {
688        CapturedDelta::ReplayAddNodeWithIdIfMissing {
689            id: Uuid::from_u128(id).to_string(),
690            url: url.to_string(),
691            position: [0.0, 0.0],
692        }
693    }
694
695    fn assert_live_add_captures(deltas: &[CapturedDelta], id: u128, url: &str) {
696        let resource = super::super::ResourceNode::new(url);
697        assert_eq!(deltas.len(), 4);
698        assert_eq!(deltas[0], add(id, url));
699        assert!(
700            matches!(&deltas[1], CapturedDelta::ReplayTouchNodeLastVisitedById {
701            node_id, ..
702        } if node_id == &Uuid::from_u128(id).to_string())
703        );
704        assert_eq!(
705            deltas[2],
706            CapturedDelta::ReplaySetResourceRecordById {
707                resource_id: resource.id().to_string(),
708                record: Some(crate::persistence::PersistedResourceRecord {
709                    canonical_iri: resource.canonical_iri().into(),
710                    facets: vec![],
711                }),
712            }
713        );
714        assert_eq!(
715            deltas[3],
716            CapturedDelta::ReplaySetShownResourceById {
717                surface_id: Uuid::from_u128(id).to_string(),
718                resource_id: Some(resource.id().to_string()),
719            }
720        );
721    }
722
723    #[test]
724    fn legacy_journal_assertions_use_each_entry_author_on_full_and_prefix_replay() {
725        let mut journal = GraphJournal::new();
726        journal.record(add(1, "https://a.test/"));
727        journal.record(add(2, "https://b.test/"));
728        let recognized = CapturedDelta::ReplayAssertRelationByIds {
729            from_id: Uuid::from_u128(1).to_string(),
730            to_id: Uuid::from_u128(2).to_string(),
731            assertion: EdgeAssertion::Semantic {
732                sub_kind: SemanticSubKind::Cites,
733                label: None,
734            },
735        };
736        let open = CapturedDelta::ReplayAssertSemanticPredicateByIds {
737            from_id: Uuid::from_u128(1).to_string(),
738            to_id: Uuid::from_u128(2).to_string(),
739            predicate: "https://vocab.test/mentions".into(),
740        };
741        let alice = Author::person("https://people.test/alice");
742        let bob = Author::person("https://people.test/bob");
743        for author in [&alice, &bob] {
744            journal.record_as(author.clone(), recognized.clone());
745            journal.record_as(author.clone(), open.clone());
746        }
747        let attributions = |graph: &Graph| {
748            let a = graph.get_node_key_by_id(Uuid::from_u128(1)).unwrap();
749            let b = graph.get_node_key_by_id(Uuid::from_u128(2)).unwrap();
750            let edge = graph.find_edge_key(a, b).unwrap();
751            let mut values: Vec<_> = graph
752                .get_edge(edge)
753                .unwrap()
754                .semantic_statements()
755                .iter()
756                .map(|statement| {
757                    (
758                        statement.predicate.clone(),
759                        statement.provenance_iri.clone().unwrap(),
760                    )
761                })
762                .collect();
763            values.sort();
764            values
765        };
766        let full = journal.replay();
767        let full_attributions = attributions(&full);
768        assert_eq!(full_attributions.len(), 4);
769        for author in [&alice, &bob] {
770            assert_eq!(
771                full_attributions
772                    .iter()
773                    .filter(|(_, iri)| iri == &author.asserter_iri())
774                    .count(),
775                2
776            );
777        }
778        let mut prefix = journal.snapshot_at(Seq(4)).unwrap().unwrap();
779        let prefix_attributions = attributions(&prefix);
780        assert_eq!(prefix_attributions.len(), 2);
781        assert!(
782            prefix_attributions
783                .iter()
784                .all(|(_, iri)| iri == &alice.asserter_iri())
785        );
786        journal.replay_from(Seq(4), &mut prefix).unwrap();
787        assert_eq!(attributions(&prefix), full_attributions);
788        let unattributed =
789            replay_captured_deltas(journal.entries().iter().map(|entry| entry.delta.clone()));
790        let legacy_attributions = attributions(&unattributed);
791        assert_eq!(
792            legacy_attributions.len(),
793            2,
794            "without envelopes attribution remains unknown"
795        );
796        assert!(
797            legacy_attributions
798                .iter()
799                .all(|(_, iri)| iri == crate::graph::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI)
800        );
801    }
802
803    #[test]
804    fn exact_statement_capture_preserves_source_over_journal_recorder() {
805        let mut source =
806            replay_captured_deltas([add(1, "https://a.test/"), add(2, "https://b.test/")]);
807        let a = source.get_node_key_by_id(Uuid::from_u128(1)).unwrap();
808        let b = source.get_node_key_by_id(Uuid::from_u128(2)).unwrap();
809        let source_iri = "https://source.test/page";
810        source
811            .assert_surface_semantic_statement(
812                a,
813                b,
814                super::super::SemanticStatementSpec {
815                    predicate: super::super::predicate_iri(SemanticSubKind::Cites).into(),
816                    recognized_sub_kind: Some(SemanticSubKind::Cites),
817                    provenance_iri: Some(source_iri.into()),
818                    asserted_at_ms: Some(100),
819                    ..Default::default()
820                },
821            )
822            .unwrap();
823        let expected = source.persisted_edges_between(a, b);
824        let exact = CapturedDelta::ReplaySetEdgesByIds {
825            from_id: Uuid::from_u128(1).to_string(),
826            to_id: Uuid::from_u128(2).to_string(),
827            edges: expected.clone(),
828        };
829        let recorder = Author::engine("extractor", "9");
830        assert_ne!(source_iri, recorder.asserter_iri());
831        let mut journal = GraphJournal::new();
832        journal.record(add(1, "https://a.test/"));
833        journal.record(add(2, "https://b.test/"));
834        journal.record_as(recorder.clone(), exact.clone());
835        let restored = journal.replay();
836        let restored_a = restored.get_node_key_by_id(Uuid::from_u128(1)).unwrap();
837        let restored_b = restored.get_node_key_by_id(Uuid::from_u128(2)).unwrap();
838        assert_eq!(
839            restored.persisted_edges_between(restored_a, restored_b),
840            expected
841        );
842        let mut direct = Graph::new();
843        crate::graph::capture::replay_captured_deltas_as_onto(
844            &mut direct,
845            &recorder,
846            [add(1, "https://a.test/"), add(2, "https://b.test/"), exact],
847        );
848        let direct_a = direct.get_node_key_by_id(Uuid::from_u128(1)).unwrap();
849        let direct_b = direct.get_node_key_by_id(Uuid::from_u128(2)).unwrap();
850        assert_eq!(direct.persisted_edges_between(direct_a, direct_b), expected);
851    }
852
853    #[test]
854    fn legacy_exact_capture_attribution_matches_checkpoint_replay() {
855        use crate::graph::SemanticStatementSpec;
856
857        let recorder = Author::engine("legacy-extractor", "1");
858        for source in [Some("https://source.test/page"), None] {
859            let mut template =
860                replay_captured_deltas([add(1, "https://a.test/"), add(2, "https://b.test/")]);
861            let from = template.get_node_key_by_id(Uuid::from_u128(1)).unwrap();
862            let to = template.get_node_key_by_id(Uuid::from_u128(2)).unwrap();
863            template
864                .assert_surface_semantic_statement(
865                    from,
866                    to,
867                    SemanticStatementSpec {
868                        predicate: super::super::predicate_iri(SemanticSubKind::Cites).into(),
869                        recognized_sub_kind: Some(SemanticSubKind::Cites),
870                        provenance_iri: Some("https://template.test/".into()),
871                        asserted_at_ms: Some(100),
872                        ..Default::default()
873                    },
874                )
875                .unwrap();
876            let mut old_edges = template.persisted_edges_between(from, to);
877            let old_statement = &mut old_edges[0].retained_assertions_mut()[0];
878            old_statement.statement_id = "legacy-exact-handle".into();
879            old_statement.provenance_iri = source.map(str::to_owned);
880            if source.is_none() {
881                let exact = CapturedDelta::ReplaySetEdgesByIds {
882                    from_id: Uuid::from_u128(1).to_string(),
883                    to_id: Uuid::from_u128(2).to_string(),
884                    edges: old_edges.clone(),
885                };
886                let mut baseline = template.clone();
887                super::super::capture::replay_captured_deltas_onto(&mut baseline, [exact.clone()]);
888                let mut baseline_journal = GraphJournal::new();
889                baseline_journal.record_as(recorder.clone(), exact);
890                baseline_journal.replay_from(Seq(0), &mut baseline).unwrap();
891                assert_eq!(
892                    baseline.persisted_edges_between(from, to)[0].retained_assertions()[0]
893                        .provenance_iri
894                        .as_deref(),
895                    Some(super::super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI),
896                    "an unattributed baseline handle stays unknown"
897                );
898            }
899            let mut journal = GraphJournal::new();
900            journal.record(add(1, "https://a.test/"));
901            journal.record(add(2, "https://b.test/"));
902            journal.record_as(
903                recorder.clone(),
904                CapturedDelta::ReplayAssertRelationByIds {
905                    from_id: Uuid::from_u128(1).to_string(),
906                    to_id: Uuid::from_u128(2).to_string(),
907                    assertion: EdgeAssertion::Semantic {
908                        sub_kind: SemanticSubKind::Cites,
909                        label: None,
910                    },
911                },
912            );
913            let prefix = journal.snapshot_at(Seq(3)).unwrap().unwrap();
914            let prefix_edges = prefix.persisted_edges_between(from, to);
915            assert_eq!(
916                prefix_edges[0].retained_assertions()[0].provenance_iri,
917                Some(recorder.asserter_iri()),
918                "the raw historical assertion first recovers its recorder"
919            );
920            journal.record_as(
921                recorder.clone(),
922                CapturedDelta::ReplaySetEdgesByIds {
923                    from_id: Uuid::from_u128(1).to_string(),
924                    to_id: Uuid::from_u128(2).to_string(),
925                    edges: old_edges,
926                },
927            );
928
929            let full = journal.replay();
930            let expected = full.persisted_edges_between(from, to);
931            let statements = &expected[0].retained_assertions();
932            assert_eq!(statements.len(), 1);
933            assert_eq!(statements[0].statement_id, "legacy-exact-handle");
934            assert_eq!(statements[0].asserted_at_ms, Some(100));
935            assert_eq!(
936                statements[0].provenance_iri.as_deref(),
937                Some(
938                    source
939                        .map(str::to_owned)
940                        .unwrap_or_else(|| recorder.asserter_iri())
941                        .as_str()
942                ),
943                "a minted handle recovers its Author; a known source remains unchanged"
944            );
945
946            let mut checkpoint = Graph::from_snapshot(&prefix.to_snapshot());
947            journal
948                .replay_from_with_baseline(Seq(3), &mut checkpoint, &Graph::new())
949                .unwrap();
950            assert_eq!(checkpoint.persisted_edges_between(from, to), expected);
951            let reopened = Graph::from_snapshot(&full.to_snapshot());
952            assert_eq!(reopened.persisted_edges_between(from, to), expected);
953        }
954    }
955
956    #[test]
957    fn legacy_checkpoint_empty_tail_recovers_proven_minting_attribution() {
958        use crate::graph::{SemanticStatementSpec, edge_data::UNKNOWN_LEGACY_ASSERTER_IRI};
959
960        let mut template =
961            replay_captured_deltas([add(1, "https://a.test/"), add(2, "https://b.test/")]);
962        let from = template.get_node_key_by_id(Uuid::from_u128(1)).unwrap();
963        let to = template.get_node_key_by_id(Uuid::from_u128(2)).unwrap();
964        template.assert_surface_semantic_statement(
965            from,
966            to,
967            SemanticStatementSpec {
968                predicate: super::super::predicate_iri(SemanticSubKind::Cites).into(),
969                recognized_sub_kind: Some(SemanticSubKind::Cites),
970                provenance_iri: Some("https://template.test/".into()),
971                asserted_at_ms: Some(100),
972                ..Default::default()
973            },
974        );
975        let mut edges = template.persisted_edges_between(from, to);
976        let mut unknown = edges[0].retained_assertions()[0].clone();
977        unknown.statement_id = "baseline-unknown".into();
978        unknown.provenance_iri = None;
979        let mut known = unknown.clone();
980        known.statement_id = "baseline-source".into();
981        known.provenance_iri = Some("https://source.test/page".into());
982        known.asserted_at_ms = Some(101);
983        *edges[0].assertions.as_mut().unwrap() = vec![unknown.clone(), known];
984        let capture = |edges| CapturedDelta::ReplaySetEdgesByIds {
985            from_id: Uuid::from_u128(1).to_string(),
986            to_id: Uuid::from_u128(2).to_string(),
987            edges,
988        };
989        let mut baseline = template;
990        super::super::capture::replay_captured_deltas_onto(&mut baseline, [capture(edges.clone())]);
991        let mut minted = unknown;
992        minted.statement_id = "minted-handle".into();
993        minted.asserted_at_ms = Some(200);
994        edges[0].assertions.as_mut().unwrap().push(minted);
995        let minter = Author::engine("first-extractor", "1");
996        let mut journal = GraphJournal::new();
997        journal.record_as(minter.clone(), capture(edges));
998        let mut checkpoint = baseline.clone();
999        super::super::capture::replay_captured_deltas_onto(
1000            &mut checkpoint,
1001            journal.entries().iter().map(|entry| entry.delta.clone()),
1002        );
1003        let old = checkpoint.persisted_edges_between(from, to);
1004        let old_statements = &old[0].retained_assertions();
1005        assert_eq!(old_statements.len(), 3);
1006        assert_eq!(
1007            old_statements[0].provenance_iri.as_deref(),
1008            Some(UNKNOWN_LEGACY_ASSERTER_IRI)
1009        );
1010        assert_eq!(
1011            old_statements[1].provenance_iri.as_deref(),
1012            Some("https://source.test/page")
1013        );
1014        assert_eq!(
1015            old_statements[2].provenance_iri.as_deref(),
1016            Some(UNKNOWN_LEGACY_ASSERTER_IRI)
1017        );
1018        checkpoint = Graph::from_snapshot(&checkpoint.to_snapshot());
1019        let before_revision = checkpoint.revision();
1020        let captured = Arc::new(Mutex::new(Vec::new()));
1021        let sink = captured.clone();
1022        checkpoint.set_recorder(Some(Arc::new(move |delta| {
1023            sink.lock().unwrap().push(delta.clone());
1024        })));
1025        journal
1026            .replay_from_with_baseline(Seq(1), &mut checkpoint, &baseline)
1027            .unwrap();
1028        let repaired = checkpoint.persisted_edges_between(from, to);
1029        let statements = &repaired[0].retained_assertions();
1030        assert_eq!(statements[2].provenance_iri, Some(minter.asserter_iri()));
1031        assert_eq!(statements[2].statement_id, "minted-handle");
1032        assert_eq!(statements[2].asserted_at_ms, Some(200));
1033        assert_eq!(statements[0], old_statements[0]);
1034        assert_eq!(statements[1], old_statements[1]);
1035        assert!(checkpoint.revision() > before_revision);
1036        assert!(captured.lock().unwrap().is_empty());
1037        let full = journal
1038            .snapshot_at_from(&baseline, Seq(1))
1039            .unwrap()
1040            .unwrap();
1041        assert_eq!(repaired, full.persisted_edges_between(from, to));
1042    }
1043
1044    #[test]
1045    fn exact_capture_attribution_survives_later_authors_and_absent_checkpoint_handles() {
1046        use crate::graph::{SemanticStatementSpec, edge_data::UNKNOWN_LEGACY_ASSERTER_IRI};
1047
1048        let mut template =
1049            replay_captured_deltas([add(1, "https://a.test/"), add(2, "https://b.test/")]);
1050        let from = template.get_node_key_by_id(Uuid::from_u128(1)).unwrap();
1051        let to = template.get_node_key_by_id(Uuid::from_u128(2)).unwrap();
1052        template.assert_surface_semantic_statement(
1053            from,
1054            to,
1055            SemanticStatementSpec {
1056                predicate: super::super::predicate_iri(SemanticSubKind::Cites).into(),
1057                recognized_sub_kind: Some(SemanticSubKind::Cites),
1058                provenance_iri: Some("https://template.test/".into()),
1059                asserted_at_ms: Some(100),
1060                ..Default::default()
1061            },
1062        );
1063        let mut edges = template.persisted_edges_between(from, to);
1064        let mut unknown = edges[0].retained_assertions()[0].clone();
1065        unknown.statement_id = "baseline-unknown".into();
1066        unknown.provenance_iri = None;
1067        let mut known = unknown.clone();
1068        known.statement_id = "baseline-source".into();
1069        known.provenance_iri = Some("https://source.test/page".into());
1070        *edges[0].assertions.as_mut().unwrap() = vec![unknown.clone(), known.clone()];
1071        let capture = |edges| CapturedDelta::ReplaySetEdgesByIds {
1072            from_id: Uuid::from_u128(1).to_string(),
1073            to_id: Uuid::from_u128(2).to_string(),
1074            edges,
1075        };
1076        let mut baseline = template;
1077        super::super::capture::replay_captured_deltas_onto(&mut baseline, [capture(edges.clone())]);
1078
1079        let minter = Author::engine("first-extractor", "1");
1080        let updater = Author::script("later-update", "1");
1081        let undoer = Author::rule("undo", "1");
1082        let mut minted = unknown.clone();
1083        minted.statement_id = "minted-handle".into();
1084        minted.asserted_at_ms = Some(200);
1085        edges[0].assertions.as_mut().unwrap().push(minted);
1086        let mut journal = GraphJournal::new();
1087        journal.record_as(minter.clone(), capture(edges.clone()));
1088        edges[0].retained_assertions_mut()[2].asserted_at_ms = Some(201);
1089        journal.record_as(updater.clone(), capture(edges.clone()));
1090        let mut withdrawn = edges.clone();
1091        *withdrawn[0].assertions.as_mut().unwrap() = vec![known];
1092        journal.record_as(updater, capture(withdrawn));
1093        edges[0].retained_assertions_mut()[2].asserted_at_ms = Some(202);
1094        edges[0].retained_assertions_mut()[1].provenance_iri = None;
1095        journal.record_as(undoer, capture(edges));
1096
1097        let full = journal
1098            .snapshot_at_from(&baseline, Seq(4))
1099            .unwrap()
1100            .unwrap();
1101        let expected = full.persisted_edges_between(from, to);
1102        let statements = &expected[0].retained_assertions();
1103        assert_eq!(statements.len(), 3);
1104        assert_eq!(statements[0].statement_id, "baseline-unknown");
1105        assert_eq!(statements[0].asserted_at_ms, Some(100));
1106        assert_eq!(
1107            statements[0].provenance_iri.as_deref(),
1108            Some(UNKNOWN_LEGACY_ASSERTER_IRI)
1109        );
1110        assert_eq!(statements[1].statement_id, "baseline-source");
1111        assert_eq!(
1112            statements[1].provenance_iri.as_deref(),
1113            Some("https://source.test/page")
1114        );
1115        assert_eq!(statements[2].statement_id, "minted-handle");
1116        assert_eq!(statements[2].asserted_at_ms, Some(202));
1117        assert_eq!(statements[2].provenance_iri, Some(minter.asserter_iri()));
1118        for cursor in 0..=4 {
1119            let prefix = journal
1120                .snapshot_at_from(&baseline, Seq(cursor))
1121                .unwrap()
1122                .unwrap();
1123            let mut checkpoint = Graph::from_snapshot(&prefix.to_snapshot());
1124            journal
1125                .replay_from_with_baseline(Seq(cursor), &mut checkpoint, &baseline)
1126                .unwrap();
1127            assert_eq!(checkpoint.persisted_edges_between(from, to), expected);
1128        }
1129
1130        let withdrawn = journal
1131            .snapshot_at_from(&baseline, Seq(3))
1132            .unwrap()
1133            .unwrap();
1134        assert_eq!(
1135            withdrawn.persisted_edges_between(from, to)[0]
1136                .retained_assertions()
1137                .len(),
1138            1
1139        );
1140        let mut without_baseline = Graph::from_snapshot(&withdrawn.to_snapshot());
1141        journal.replay_from(Seq(3), &mut without_baseline).unwrap();
1142        let conservative = without_baseline.persisted_edges_between(from, to);
1143        assert_eq!(
1144            conservative[0].retained_assertions()[2]
1145                .provenance_iri
1146                .as_deref(),
1147            Some(UNKNOWN_LEGACY_ASSERTER_IRI)
1148        );
1149    }
1150
1151    /// A key-independent view: sorted node ids and sorted (from, to, kind) triples.
1152    /// Two graphs are equal iff their fingerprints are, regardless of petgraph keys.
1153    fn fingerprint(graph: &Graph) -> (Vec<String>, Vec<(String, String, String)>) {
1154        let mut nodes: Vec<String> = graph.nodes().map(|(_, n)| n.id.to_string()).collect();
1155        nodes.sort();
1156        let mut edges: Vec<(String, String, String)> = graph
1157            .relations()
1158            .map(|rel| {
1159                let from = graph
1160                    .get_node(rel.from)
1161                    .map(|n| n.id.to_string())
1162                    .unwrap_or_default();
1163                let to = graph
1164                    .get_node(rel.to)
1165                    .map(|n| n.id.to_string())
1166                    .unwrap_or_default();
1167                (from, to, format!("{:?}", rel.kind))
1168            })
1169            .collect();
1170        edges.sort();
1171        (nodes, edges)
1172    }
1173
1174    /// The envelope: entries carry their author; the default is the trusted
1175    /// UI's person, a scoped author attributes a participant run, and replay
1176    /// strips the envelope.
1177    #[test]
1178    fn entries_are_attributed_and_author_scoping_works() {
1179        let mut journal = GraphJournal::new();
1180        journal.record(add(1, "https://a.test/"));
1181        journal.set_author(Author::person("aa11"));
1182        journal.record(add(2, "https://b.test/"));
1183        journal.set_author(Author::user());
1184        journal.record_as(
1185            Author::engine("tarot-shuffle", "1.2").via("cleromancy"),
1186            add(3, "https://c.test/"),
1187        );
1188
1189        let authors: Vec<String> = journal
1190            .entries()
1191            .iter()
1192            .map(|e| e.author.to_string())
1193            .collect();
1194        assert_eq!(
1195            authors,
1196            [
1197                "person user",
1198                "person aa11",
1199                "engine tarot-shuffle 1.2 via cleromancy"
1200            ]
1201        );
1202        assert_eq!(journal.author(), &Author::user(), "scoping restored");
1203        assert_eq!(
1204            journal.replay().node_count(),
1205            3,
1206            "replay strips the envelope"
1207        );
1208    }
1209
1210    #[test]
1211    fn source_time_contract_selects_immutable_journal_prefixes() {
1212        let mut journal = GraphJournal::new();
1213        journal.record(add(1, "https://one.test/"));
1214        journal.record(add(2, "https://two.test/"));
1215
1216        assert_eq!(
1217            journal.source_extent(),
1218            SourceExtent {
1219                earliest: Seq(0),
1220                current: Seq(2),
1221            }
1222        );
1223        assert_eq!(journal.source_ticks(3), [Seq(0), Seq(1), Seq(2)]);
1224        assert_eq!(
1225            journal
1226                .source_snapshot(&Seq(1))
1227                .expect("known source cursor")
1228                .node_count(),
1229            1
1230        );
1231        assert!(journal.source_snapshot(&Seq(3)).is_none());
1232        assert_eq!(
1233            journal.replay().node_count(),
1234            2,
1235            "scrubbing leaves live truth intact"
1236        );
1237    }
1238
1239    /// Every author field is written, so the record reads back through any
1240    /// codec, positional ones included.
1241    #[test]
1242    fn an_author_writes_every_field() {
1243        let author = Author::rule("promote-on-tag", "3").via("turnstone");
1244        let json = serde_json::to_string(&author).unwrap();
1245        assert_eq!(
1246            json,
1247            r#"{"kind":"rule","id":"promote-on-tag","version":"3","via":"turnstone"}"#
1248        );
1249        assert_eq!(serde_json::from_str::<Author>(&json).unwrap(), author);
1250        let person = serde_json::to_string(&Author::user()).unwrap();
1251        assert_eq!(
1252            person,
1253            r#"{"kind":"person","id":"user","version":null,"via":null}"#
1254        );
1255    }
1256
1257    /// A graph that opted in records its own deltas; a clone of it records
1258    /// nothing, and neither does a graph that never opted in.
1259    #[test]
1260    fn a_graph_records_its_own_deltas_and_a_clone_does_not() {
1261        let seen = Arc::new(Mutex::new(Vec::new()));
1262        let sink = Arc::clone(&seen);
1263        let mut session = Graph::new();
1264        session.set_recorder(Some(Arc::new(move |delta: &CapturedDelta| {
1265            sink.lock().unwrap().push(delta.clone());
1266        })));
1267        assert!(session.is_recording());
1268        let add_node = |graph: &mut Graph, id: u128| {
1269            apply_graph_delta(
1270                graph,
1271                GraphDelta::AddNode {
1272                    id: Some(Uuid::from_u128(id)),
1273                    url: format!("https://{id}.test/"),
1274                    position: Point2D::new(0.0, 0.0),
1275                },
1276            )
1277        };
1278        add_node(&mut session, 1);
1279        let mut copy = session.clone();
1280        assert!(!copy.is_recording());
1281        add_node(&mut copy, 2);
1282        add_node(&mut Graph::new(), 3);
1283        let seen = seen.lock().unwrap();
1284        assert_live_add_captures(&seen, 1, "https://1.test/");
1285    }
1286
1287    /// Replay reproduces the live graph exactly, clock-read visit stamps and
1288    /// minted statement ids included: the journal keeps what was read or
1289    /// minted (reservoir plan V2).
1290    #[test]
1291    fn replay_reproduces_visit_stamps_and_statement_ids() {
1292        let (journal, hook) = journal_capture_hook();
1293        set_captured_delta_hook(Some(hook));
1294        let mut live = Graph::new();
1295        let key = |graph: &mut Graph, id: u128| match apply_graph_delta(
1296            graph,
1297            GraphDelta::AddNode {
1298                id: Some(Uuid::from_u128(id)),
1299                url: format!("https://{id}.test/"),
1300                position: Point2D::new(0.0, 0.0),
1301            },
1302        ) {
1303            GraphDeltaResult::NodeAdded(key) => key,
1304            other => panic!("expected NodeAdded, got {other:?}"),
1305        };
1306        let a = key(&mut live, 1);
1307        // Let the clock move, so a replay's own stamp would differ.
1308        std::thread::sleep(std::time::Duration::from_millis(2));
1309        let b = key(&mut live, 2);
1310        apply_graph_delta(
1311            &mut live,
1312            GraphDelta::AssertRelation {
1313                asserter_iri: crate::graph::journal::Author::user().asserter_iri(),
1314                from: a,
1315                to: b,
1316                assertion: EdgeAssertion::Semantic {
1317                    sub_kind: SemanticSubKind::Cites,
1318                    label: None,
1319                },
1320            },
1321        );
1322        apply_graph_delta(
1323            &mut live,
1324            GraphDelta::AssertSemanticPredicate {
1325                asserter_iri: crate::graph::journal::Author::user().asserter_iri(),
1326                from: b,
1327                to: a,
1328                predicate: "https://schema.org/about".into(),
1329            },
1330        );
1331        set_captured_delta_hook(None);
1332
1333        std::thread::sleep(std::time::Duration::from_millis(2));
1334        let replayed = journal.lock().unwrap().replay();
1335        for id in [1u128, 2] {
1336            let visited = |graph: &Graph| {
1337                let (key, _) = graph.get_node_by_id(Uuid::from_u128(id)).unwrap();
1338                graph.node_last_visited(key)
1339            };
1340            assert!(
1341                visited(&live).is_some(),
1342                "creating node {id} stamped a visit"
1343            );
1344            assert_eq!(
1345                visited(&replayed),
1346                visited(&live),
1347                "node {id}'s visit stamp"
1348            );
1349        }
1350        let key_of = |graph: &Graph, key| {
1351            let id = live.get_node(key).unwrap().id;
1352            graph.get_node_key_by_id(id).unwrap()
1353        };
1354        for (from, to) in [(a, b), (b, a)] {
1355            let resource_pair = (
1356                live.shown_resource_id(from).unwrap(),
1357                live.shown_resource_id(to).unwrap(),
1358            );
1359            assert!(live.persisted_edges_between(from, to).is_empty());
1360            assert!(
1361                !live
1362                    .persisted_resource_edges_between(resource_pair.0, resource_pair.1)
1363                    .is_empty(),
1364                "the live Resource graph holds a minted statement there"
1365            );
1366            assert_eq!(
1367                replayed.shown_resource_id(key_of(&replayed, from)),
1368                Some(resource_pair.0)
1369            );
1370            assert_eq!(
1371                replayed.shown_resource_id(key_of(&replayed, to)),
1372                Some(resource_pair.1)
1373            );
1374            assert_eq!(
1375                replayed.persisted_resource_edges_between(resource_pair.0, resource_pair.1),
1376                live.persisted_resource_edges_between(resource_pair.0, resource_pair.1),
1377                "statement ids survive replay"
1378            );
1379        }
1380    }
1381
1382    /// Replay records nothing: a scrub or a catch-up re-applies history, it
1383    /// does not make new history. The same run first proves both instruments
1384    /// see a live edit, so the silence after is the replay's.
1385    #[test]
1386    fn replay_records_nothing() {
1387        let (hooked, hook) = journal_capture_hook();
1388        set_captured_delta_hook(Some(hook));
1389        let seen = Arc::new(Mutex::new(0usize));
1390        let sink = Arc::clone(&seen);
1391        let mut session = Graph::new();
1392        session.set_recorder(Some(Arc::new(move |_: &CapturedDelta| {
1393            *sink.lock().unwrap() += 1;
1394        })));
1395        apply_graph_delta(
1396            &mut session,
1397            GraphDelta::AddNode {
1398                id: Some(Uuid::from_u128(1)),
1399                url: "https://a.test/".to_string(),
1400                position: Point2D::new(0.0, 0.0),
1401            },
1402        );
1403        // A live add records the surface, visit, resource and shown binding.
1404        assert_live_add_captures(
1405            &hooked
1406                .lock()
1407                .unwrap()
1408                .entries()
1409                .iter()
1410                .map(|entry| entry.delta.clone())
1411                .collect::<Vec<_>>(),
1412            1,
1413            "https://a.test/",
1414        );
1415        assert_eq!(
1416            hooked.lock().unwrap().len(),
1417            4,
1418            "the thread hook sees live edits"
1419        );
1420        assert_eq!(
1421            *seen.lock().unwrap(),
1422            4,
1423            "the graph's recorder sees live edits"
1424        );
1425
1426        let history = hooked.lock().unwrap().clone();
1427        let scrubbed = history.snapshot_at(history.live_cursor()).unwrap().unwrap();
1428        replay_captured_deltas_onto(&mut session, [add(2, "https://b.test/")]);
1429        assert_eq!(scrubbed.node_count(), 1);
1430        assert_eq!(session.node_count(), 2);
1431        assert_eq!(
1432            hooked.lock().unwrap().len(),
1433            4,
1434            "replay reached the thread hook"
1435        );
1436        assert_eq!(
1437            *seen.lock().unwrap(),
1438            4,
1439            "replay reached the graph's recorder"
1440        );
1441
1442        // Both instruments are back once the replay ends.
1443        assert!(session.is_recording());
1444        apply_graph_delta(
1445            &mut session,
1446            GraphDelta::AddNode {
1447                id: Some(Uuid::from_u128(3)),
1448                url: "https://c.test/".to_string(),
1449                position: Point2D::new(0.0, 0.0),
1450            },
1451        );
1452        let captures = hooked
1453            .lock()
1454            .unwrap()
1455            .entries()
1456            .iter()
1457            .map(|entry| entry.delta.clone())
1458            .collect::<Vec<_>>();
1459        assert_eq!(captures.len(), 8);
1460        assert_live_add_captures(&captures[4..], 3, "https://c.test/");
1461        assert_eq!(*seen.lock().unwrap(), 8);
1462        set_captured_delta_hook(None);
1463    }
1464
1465    #[test]
1466    fn records_and_replays_reconstruct_the_graph() {
1467        let mut journal = GraphJournal::new();
1468        journal.record(add(1, "https://a.test/"));
1469        journal.record(add(2, "https://b.test/"));
1470        journal.record(CapturedDelta::ReplayAssertRelationByIds {
1471            from_id: Uuid::from_u128(1).to_string(),
1472            to_id: Uuid::from_u128(2).to_string(),
1473            assertion: EdgeAssertion::Semantic {
1474                sub_kind: SemanticSubKind::Cites,
1475                label: None,
1476            },
1477        });
1478        journal.record(CapturedDelta::ReplaySetNodeTitleById {
1479            node_id: Uuid::from_u128(1).to_string(),
1480            title: "Paper A".to_string(),
1481        });
1482
1483        let graph = journal.replay();
1484        assert_eq!(graph.node_count(), 2);
1485        assert_eq!(graph.relations().count(), 1, "the cites relation replayed");
1486        let (_, node) = graph
1487            .get_node_by_id(Uuid::from_u128(1))
1488            .expect("node a present");
1489        assert_eq!(node.title, "Paper A", "the content edit replayed too");
1490    }
1491
1492    #[test]
1493    fn prefix_cursors_replay_historical_graphs_without_touching_live_history() {
1494        let mut journal = GraphJournal::new();
1495        journal.record(add(1, "https://a.test/"));
1496        journal.record(add(2, "https://b.test/"));
1497        journal.record(CapturedDelta::ReplayAssertRelationByIds {
1498            from_id: Uuid::from_u128(1).to_string(),
1499            to_id: Uuid::from_u128(2).to_string(),
1500            assertion: EdgeAssertion::Semantic {
1501                sub_kind: SemanticSubKind::Cites,
1502                label: None,
1503            },
1504        });
1505
1506        assert_eq!(journal.earliest_cursor(), Seq(0));
1507        assert_eq!(journal.live_cursor(), Seq(3));
1508        assert_eq!(
1509            journal.snapshot_at(Seq(0)).unwrap().unwrap().node_count(),
1510            0
1511        );
1512        assert_eq!(
1513            journal.snapshot_at(Seq(1)).unwrap().unwrap().node_count(),
1514            1
1515        );
1516        let historical = journal.snapshot_at(Seq(2)).unwrap().expect("known prefix");
1517        assert_eq!(historical.node_count(), 2);
1518        assert_eq!(historical.relations().count(), 0);
1519        assert_eq!(
1520            journal
1521                .snapshot_at(Seq(3))
1522                .unwrap()
1523                .unwrap()
1524                .relations()
1525                .count(),
1526            1
1527        );
1528        assert!(
1529            journal.snapshot_at(Seq(4)).unwrap().is_none(),
1530            "stale cursors refuse"
1531        );
1532        assert_eq!(
1533            journal.replay().relations().count(),
1534            1,
1535            "live history remains live"
1536        );
1537        assert_eq!(journal.sequence_ticks(3), vec![Seq(0), Seq(1), Seq(3)]);
1538    }
1539
1540    #[test]
1541    fn fork_carries_history_then_diverges() {
1542        let mut source = GraphJournal::with_id(LogId::new("source"));
1543        source.record(add(1, "https://a.test/"));
1544        source.record(add(2, "https://b.test/"));
1545
1546        let mut fork = source.fork(LogId::new("fork"));
1547        assert_eq!(
1548            fork.entries(),
1549            source.entries(),
1550            "the fork copies the history"
1551        );
1552        let provenance = fork.provenance().expect("a fork has provenance");
1553        assert_eq!(provenance.source, Some(LogId::new("source")));
1554        assert_eq!(provenance.at, Seq(source.len() as u64));
1555
1556        // Diverging the fork leaves the source untouched.
1557        fork.record(add(3, "https://c.test/"));
1558        assert_eq!(source.replay().node_count(), 2, "source unchanged");
1559        assert_eq!(fork.replay().node_count(), 3);
1560    }
1561
1562    #[test]
1563    fn journal_round_trips_through_a_muniment_slot() {
1564        use muniment::{JsonSlots, MemoryBackend};
1565        pollster::block_on(async {
1566            let slots = JsonSlots::new(MemoryBackend::new());
1567
1568            let mut journal = GraphJournal::new();
1569            journal.record(add(1, "https://a.test/"));
1570            journal.record(add(2, "https://b.test/"));
1571            journal.save(&slots, "journal").await.unwrap();
1572
1573            let reloaded = GraphJournal::load(&slots, "journal").await.unwrap();
1574            assert_eq!(reloaded.len(), 2, "the log survived the round trip");
1575            assert_eq!(
1576                fingerprint(&reloaded.replay()),
1577                fingerprint(&journal.replay()),
1578                "the reloaded journal replays to the same graph"
1579            );
1580        });
1581    }
1582
1583    #[test]
1584    fn the_capture_hook_feeds_the_journal_and_replay_matches_live() {
1585        // The edit-spine invariant: a graph built by live mutation and one rebuilt
1586        // by replaying the journal those mutations produced are identical.
1587        let (journal, hook) = journal_capture_hook();
1588        set_captured_delta_hook(Some(hook));
1589
1590        let mut live = Graph::new();
1591        let a = match apply_graph_delta(
1592            &mut live,
1593            GraphDelta::AddNode {
1594                id: Some(Uuid::from_u128(1)),
1595                url: "https://a.test/".to_string(),
1596                position: Point2D::new(0.0, 0.0),
1597            },
1598        ) {
1599            GraphDeltaResult::NodeAdded(key) => key,
1600            other => panic!("expected NodeAdded, got {other:?}"),
1601        };
1602        let b = match apply_graph_delta(
1603            &mut live,
1604            GraphDelta::AddNode {
1605                id: Some(Uuid::from_u128(2)),
1606                url: "https://b.test/".to_string(),
1607                position: Point2D::new(1.0, 0.0),
1608            },
1609        ) {
1610            GraphDeltaResult::NodeAdded(key) => key,
1611            other => panic!("expected NodeAdded, got {other:?}"),
1612        };
1613        apply_graph_delta(
1614            &mut live,
1615            GraphDelta::AssertRelation {
1616                asserter_iri: crate::graph::journal::Author::user().asserter_iri(),
1617                from: a,
1618                to: b,
1619                assertion: EdgeAssertion::Semantic {
1620                    sub_kind: SemanticSubKind::Cites,
1621                    label: None,
1622                },
1623            },
1624        );
1625        apply_graph_delta(
1626            &mut live,
1627            GraphDelta::SetNodeTitle {
1628                key: a,
1629                title: "Paper A".to_string(),
1630            },
1631        );
1632
1633        set_captured_delta_hook(None);
1634
1635        let replayed = journal.lock().unwrap().replay();
1636        assert_eq!(
1637            fingerprint(&replayed),
1638            fingerprint(&live),
1639            "replay of the captured journal reconstructs the live graph"
1640        );
1641        let (_, node) = replayed.get_node_by_id(Uuid::from_u128(1)).expect("node a");
1642        assert_eq!(node.title, "Paper A");
1643    }
1644}