Skip to main content

tilo_resource/
history.rs

1//! Version history of any resource, derived from its document's change graph:
2//! who changed it, when, through which action — and what it looked like then.
3//!
4//! Nothing here is specific to a resource type. The attribution comes from
5//! the executor (the change's actor is the author, its message carries the
6//! action's [`ActionContext`]); materialising a past version is
7//! [`Resource::read`] on the document forked at that version's heads.
8//!
9//! Versions are addressed two ways: by heads (a set of change hashes, what a
10//! member can name) and by position in [`versions`]' causal order (what
11//! a scrubber counts). [`prefix_heads`] turns a position into heads, which
12//! the document is read at.
13
14use std::collections::{BinaryHeap, HashMap};
15use tilo_sort::CompactSort as _;
16
17use automerge::ChangeHash;
18use automerge::transaction::{CommitOptions, Transactable};
19use tilo_actions::ActionContext;
20
21use crate::model::{Doc, ModelError};
22use crate::resource::Resource;
23
24/// One change on a resource's timeline.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct Version {
27    pub hash: ChangeHash,
28    /// Hex of the authoring actor.
29    pub actor: String,
30    /// Milliseconds since the Unix epoch, or 0 when the change carries no time.
31    pub time_ms: i64,
32    /// What the change did, when it was made through an action.
33    pub context: Option<ActionContext>,
34    /// The raw change message.
35    pub message: Option<String>,
36}
37
38/// The actor every document schema's genesis change is written under. Nobody
39/// edits as this actor; it exists so that the operations creating the schema's
40/// containers are the same operations, under the same actor and counters, on
41/// every replica, leaving one change hash instead of competing roots. The bytes
42/// are pinned: changing them changes the genesis hash of every document.
43pub const SCHEMA_GENESIS_ACTOR: &[u8] = b"qdoc.schema.genesis.v1";
44
45/// Whether `actor` wrote the schema rather than the document's content: a
46/// change it authored is not a revision, and history must not attribute one to
47/// a person.
48pub fn is_schema_genesis_actor(actor: &automerge::ActorId) -> bool {
49    actor.to_bytes() == SCHEMA_GENESIS_ACTOR
50}
51
52/// Whether `version` is the schema genesis rather than something a person wrote
53/// (see [`is_schema_genesis_actor`]).
54pub fn is_schema_genesis(version: &Version) -> bool {
55    version.actor == schema_genesis_actor_hex()
56}
57
58/// The schema genesis actor as hex, for comparing against a recorded actor. See
59/// [`is_schema_genesis_actor`].
60pub fn schema_genesis_actor_hex() -> String {
61    automerge::ActorId::from(SCHEMA_GENESIS_ACTOR).to_hex_string()
62}
63
64/// One change of `doc` as a version on the timeline; a continuation of a
65/// gesture reads as its gesture's entry ([`tilo_actions::entry_of`]).
66pub fn version_of(doc: &automerge::Automerge, meta: &automerge::ChangeMetadata<'_>) -> Version {
67    let message = meta.message.as_deref().map(str::to_owned);
68    let context = context_of(doc, meta.hash, message.as_deref());
69    Version {
70        hash: meta.hash,
71        actor: meta.actor.to_hex_string(),
72        time_ms: meta.timestamp.saturating_mul(1000),
73        context,
74        message,
75    }
76}
77
78/// What the change `hash` of `doc`, written with `message`, did: the action
79/// its message records, or, for a continuation of a gesture, the gesture's
80/// entry ([`tilo_actions::entry_of`]).
81pub fn context_of(
82    doc: &automerge::Automerge,
83    hash: ChangeHash,
84    message: Option<&str>,
85) -> Option<ActionContext> {
86    match message {
87        Some(text)
88            if tilo_actions::stamp::Label::of(text)
89                == Some(tilo_actions::stamp::Label::Continuation) =>
90        {
91            tilo_actions::entry_of(doc, hash)
92        }
93        text => text.and_then(ActionContext::from_change_message),
94    }
95}
96
97/// Every change in causal order, oldest first. A change's position in this
98/// list is the address [`prefix_heads`] takes.
99///
100/// Reads every change's metadata (never its operations). For a long history
101/// shown a screen at a time, [`page`] reads only the page.
102pub fn versions(doc: &mut Doc) -> Vec<Version> {
103    // Closes the open transaction, so its change is listed too.
104    doc.get_heads();
105    committed_versions(doc)
106}
107
108/// [`versions`] of the committed document, read through a shared
109/// reference: a transaction still open is not listed.
110pub fn committed_versions(doc: &Doc) -> Vec<Version> {
111    let mut entries = tilo_actions::EntryReader::default();
112    doc.committed_document()
113        .get_changes_meta(&[])
114        .iter()
115        .map(|meta| {
116            let message = meta.message.as_deref().map(str::to_owned);
117            Version {
118                hash: meta.hash,
119                actor: meta.actor.to_hex_string(),
120                time_ms: meta.timestamp.saturating_mul(1000),
121                context: entries.read(&meta.actor, message.as_deref()),
122                message,
123            }
124        })
125        .collect()
126}
127
128/// What a change records of the act it is one change of: who made it and the
129/// work that act is named by. A record's changes name the gesture of the burst
130/// of typing they were part of and the invocation of the action that made
131/// them; a store an app keeps for itself names the run it was made in, or
132/// nothing but the person who made it ([`same_step`]).
133#[derive(Clone, Debug, Default, PartialEq, Eq)]
134pub struct StepFacts<'a> {
135    /// Who made the change; `None` for a change that names nobody.
136    pub who: Option<&'a str>,
137    /// The run it was made in: an agent's connection, a task's run.
138    pub run: Option<&'a str>,
139    /// The gesture it is one change of: the keystrokes of one burst of typing.
140    pub gesture: Option<&'a tilo_actions::ActionId>,
141    /// The invocation it is one change of: one action and the actions it called.
142    pub invocation: Option<&'a tilo_actions::InvocationId>,
143}
144
145/// Whether `next`, the change after `last`, is a change of the same step of
146/// history: both name one act — one run, one gesture, one invocation — or,
147/// naming no act of their own, one person made both.
148#[must_use]
149pub fn same_step(last: &StepFacts<'_>, next: &StepFacts<'_>) -> bool {
150    fn one_act<T: PartialEq + ?Sized>(last: Option<&T>, next: Option<&T>) -> bool {
151        last.is_some() && last == next
152    }
153    if one_act(last.run, next.run)
154        || one_act(last.gesture, next.gesture)
155        || one_act(last.invocation, next.invocation)
156    {
157        return true;
158    }
159    let names_no_act = |facts: &StepFacts<'_>| {
160        facts.run.is_none() && facts.gesture.is_none() && facts.invocation.is_none()
161    };
162    names_no_act(last) && names_no_act(next) && last.who.is_some() && last.who == next.who
163}
164
165/// Commit the open transaction with a wall-clock timestamp attached.
166/// `AutoCommit::commit()` leaves the change's advisory time at `0`, which is
167/// why routing commits through here is what makes [`Version::time_ms`] — and
168/// any date-range filter over the history — mean something. Returns `None`
169/// when there was nothing to commit, exactly like `AutoCommit::commit`.
170///
171/// An empty commit abandons the empty transaction and records nothing.
172pub fn commit_stamped(doc: &mut Doc) -> Option<ChangeHash> {
173    commit_stamped_at_with_message(doc, tilo_clock::unix_now_i64(), None)
174}
175
176/// As [`commit_stamped`], with a caller-supplied Unix time in **seconds**
177/// (Automerge's own unit), for hosts that own a clock: a store replaying a
178/// durable change chain, a test spreading versions across a day.
179pub fn commit_stamped_at(doc: &mut Doc, unix_secs: i64) -> Option<ChangeHash> {
180    commit_stamped_at_with_message(doc, unix_secs, None)
181}
182
183/// Commit a native document edit with a timestamp and an optional semantic
184/// message: the commit-boundary counterpart to action dispatch, so history
185/// learns which app and resource an edit belongs to.
186pub fn commit_stamped_with_message(doc: &mut Doc, message: Option<String>) -> Option<ChangeHash> {
187    commit_stamped_at_with_message(doc, tilo_clock::unix_now_i64(), message)
188}
189
190/// [`commit_stamped_with_message`] at a caller-supplied Unix time in seconds.
191pub fn commit_stamped_at_with_message(
192    doc: &mut Doc,
193    unix_secs: i64,
194    message: Option<String>,
195) -> Option<ChangeHash> {
196    // commit_with opens a transaction even when there are no edits, which
197    // can add then prune a fresh actor, poisoning the next differently
198    // authored transaction. Rolling the empty transaction back discards it
199    // with its own patch log branch, so the document's diff cursor — and a
200    // `Tracker` following it — stays valid.
201    if doc.pending_ops() == 0 {
202        doc.rollback();
203        return None;
204    }
205    let mut options = CommitOptions::default().with_time(unix_secs);
206    if let Some(message) = message {
207        options = options.with_message(message);
208    }
209    doc.commit_with(options)
210}
211
212/// Heads of the document as of the first `upto + 1` changes of [`versions`].
213/// Any prefix of that causal order is a valid document state, but with
214/// several members it can have several concurrent frontiers, so "the
215/// heads" is a set: a change is a head of the prefix when no other change in
216/// the prefix depends on it.
217pub fn prefix_heads(doc: &mut Doc, upto: usize) -> Vec<ChangeHash> {
218    let metas = doc.get_changes_meta(&[]);
219    let take = upto.saturating_add(1).min(metas.len());
220    let prefix = metas.get(..take).unwrap_or(&[]);
221    let depended_on: std::collections::HashSet<ChangeHash> = prefix
222        .iter()
223        .flat_map(|meta| meta.deps.iter().copied())
224        .collect();
225    prefix
226        .iter()
227        .map(|meta| meta.hash)
228        .filter(|hash| !depended_on.contains(hash))
229        .collect()
230}
231
232/// Where a newest-first walk of the history stopped: hand it back to [`page`]
233/// for the next older page.
234#[derive(Clone, Debug, PartialEq, Eq)]
235pub struct Cursor {
236    /// The newest changes not listed yet, by operation counter: every change
237    /// they depend on is older than all of them.
238    frontier: Vec<(Rank, ChangeHash)>,
239}
240
241/// One page of history, newest first.
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct Page {
244    pub versions: Vec<Version>,
245    /// The rest of the history, or `None` when this page reached the start.
246    pub older: Option<Cursor>,
247}
248
249/// Up to `limit` versions, newest first, starting at the document's heads
250/// or where `from` stopped.
251///
252/// A page reads only the changes it lists and their direct dependencies, so
253/// a member who joins a document with years of history sees its latest
254/// changes at once, and older ones load as they scroll back. Every change is
255/// listed once, after every change that depends on it: a change's operation
256/// counters are greater than those of anything it depends on, so taking the
257/// frontier's greatest counter first is a reverse causal order.
258pub fn page(doc: &mut Doc, from: Option<&Cursor>, limit: usize) -> Page {
259    let mut walk = Walk::default();
260    let mut queue: BinaryHeap<(Rank, ChangeHash)> = if let Some(cursor) = from {
261        cursor.frontier.iter().copied().collect()
262    } else {
263        let heads = doc.get_heads();
264        heads
265            .into_iter()
266            .filter_map(|hash| walk.rank(doc, hash).map(|rank| (rank, hash)))
267            .collect()
268    };
269    let mut versions = Vec::new();
270    let mut listed = std::collections::HashSet::new();
271    while versions.len() < limit {
272        let Some((_, hash)) = queue.pop() else { break };
273        // A change reached along two paths is queued once per path.
274        if !listed.insert(hash) || walk.rank(doc, hash).is_none() {
275            continue;
276        }
277        let Some((_, deps, version)) = walk.metas.get(&hash).cloned() else {
278            continue;
279        };
280        for dep in deps {
281            if let Some(rank) = walk.rank(doc, dep) {
282                queue.push((rank, dep));
283            }
284        }
285        versions.push(version);
286    }
287    let mut frontier: Vec<(Rank, ChangeHash)> = queue.into_vec();
288    frontier.compact_sort();
289    frontier.dedup();
290    frontier.retain(|(_, hash)| !listed.contains(hash));
291    Page {
292        versions,
293        older: (!frontier.is_empty()).then_some(Cursor { frontier }),
294    }
295}
296
297/// A change's place in the newest-first walk: its last operation counter,
298/// then its first. An empty change ends at its dependency's last counter but
299/// starts after it, so the start breaks that tie.
300type Rank = (u64, u64);
301
302#[cfg(test)]
303thread_local! {
304    /// Change metadata [`Walk`] has read from the document on this thread.
305    static META_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
306}
307
308/// The change metadata one [`page`] call has read.
309#[derive(Default)]
310struct Walk {
311    metas: HashMap<ChangeHash, (Rank, Vec<ChangeHash>, Version)>,
312}
313
314impl Walk {
315    fn rank(&mut self, doc: &Doc, hash: ChangeHash) -> Option<Rank> {
316        if let Some((rank, _, _)) = self.metas.get(&hash) {
317            return Some(*rank);
318        }
319        let document = doc.committed_document();
320        let meta = document.get_change_meta_by_hash(&hash)?;
321        #[cfg(test)]
322        META_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
323        let rank = (meta.max_op, meta.start_op);
324        let entry = (rank, meta.deps.clone(), version_of(document, &meta));
325        self.metas.insert(hash, entry);
326        Some(rank)
327    }
328}
329
330/// What one change wrote to one property of an object: the value the
331/// property held before the change (at the change's dependencies) and after
332/// it (at the change itself), each as JSON, `null` where it held nothing.
333#[derive(Clone, Debug, PartialEq)]
334pub struct Written {
335    /// The property of the object: a field's key.
336    pub prop: String,
337    pub before: serde_json::Value,
338    pub after: serde_json::Value,
339}
340
341/// The keys of the map `obj` the change `hash` of `doc` reached, in the
342/// order it first reached each: a key it set or removed, or one holding an
343/// object it changed inside (the text of a field typed into, a list or map
344/// of it), read from the change's own operations. Empty for a change `doc`
345/// does not hold. A reader that decodes the values itself reads each key at
346/// the change's dependencies and at the change ([`written`] reads them as
347/// JSON).
348pub fn wrote(
349    doc: &automerge::Automerge,
350    hash: &ChangeHash,
351    obj: &automerge::ObjId,
352) -> Result<Vec<String>, ModelError> {
353    use automerge::ReadDoc as _;
354    let Some(change) = doc.get_change_by_hash(hash) else {
355        return Ok(Vec::new());
356    };
357    let after_heads = [*hash];
358    let mut keys: Vec<String> = Vec::new();
359    // The keys the change's named objects sit under, each read once: a change of a long note
360    // names one object per character typed, and Automerge's way up from an object searches
361    // the document's every operation for that object's op, so per op it is the whole document.
362    let mut reached: Vec<(automerge::ObjId, Option<String>)> = Vec::new();
363    for op in change.decode().operations {
364        let target = op_obj(doc, &op.obj)?;
365        let key = if target == *obj {
366            match &op.key {
367                automerge::legacy::Key::Map(key) => Some(key.to_string()),
368                automerge::legacy::Key::Seq(_) => None,
369            }
370        } else if let Some((_, key)) = reached.iter().find(|(at, _)| *at == target) {
371            key.clone()
372        } else {
373            // An operation inside an object under `obj`: the key of `obj` on its way up.
374            let key = doc.parents_at(&target, &after_heads)?.find_map(|parent| {
375                match (parent.obj == *obj, parent.prop) {
376                    (true, automerge::Prop::Map(key)) => Some(key),
377                    _ => None,
378                }
379            });
380            reached.push((target.clone(), key.clone()));
381            key
382        };
383        if let Some(key) = key
384            && !keys.contains(&key)
385        {
386            keys.push(key);
387        }
388    }
389    Ok(keys)
390}
391
392/// What the change `hash` of `doc` wrote under the map `obj`, one entry per
393/// key of `obj` it reached ([`wrote`]), with the values before and after
394/// read as JSON from the document as of the change's dependencies and as of
395/// the change, in place. A key whose value reads the same on both sides (a
396/// write of what it held) is left out. Empty for a change `doc` does not
397/// hold.
398pub fn written(
399    doc: &automerge::Automerge,
400    hash: &ChangeHash,
401    obj: &automerge::ObjId,
402) -> Result<Vec<Written>, ModelError> {
403    use automerge::ReadDoc as _;
404    let Some(change) = doc.get_change_by_hash(hash) else {
405        return Ok(Vec::new());
406    };
407    let before_heads = change.deps().to_vec();
408    let after_heads = [*hash];
409    let keys = wrote(doc, hash, obj)?;
410    let mut out = Vec::with_capacity(keys.len());
411    for key in keys {
412        let before = held_at(doc, obj, &key, &before_heads)?;
413        let after = held_at(doc, obj, &key, &after_heads)?;
414        if before != after {
415            out.push(Written {
416                prop: key,
417                before,
418                after,
419            });
420        }
421    }
422    Ok(out)
423}
424
425/// What the key `key` of the map `obj` held as of `heads`, as JSON, `null`
426/// where it held nothing (or `obj` did not exist yet), read in place: the
427/// cost of the value, not of the document.
428pub fn held_at(
429    doc: &automerge::Automerge,
430    obj: &automerge::ObjId,
431    key: &str,
432    heads: &[ChangeHash],
433) -> Result<serde_json::Value, ModelError> {
434    use automerge::ReadDoc as _;
435    match doc.get_at(obj, key, heads)? {
436        Some((value, inner)) => crate::value::read_value_at(doc, &value, &inner, heads),
437        None => Ok(serde_json::Value::Null),
438    }
439}
440
441/// One text a change typed into: where it sits under the object asked about, and what
442/// the change did to it.
443#[derive(Clone, Debug, PartialEq, Eq)]
444pub struct TextEdit {
445    /// The map keys from the object [`spliced_texts`] was given down to this text, in
446    /// reading order: a rich text field's `blocks`, its paragraph's id, `text`.
447    pub path: Vec<String>,
448    /// What the text read before the change and what it reads after it, whole: a reader
449    /// that shows a few words around the change cuts them itself.
450    pub before: String,
451    pub after: String,
452    /// What the change inserted: the character range of `after` it wrote, and its text.
453    pub inserted: Vec<(usize, usize, String)>,
454    /// What the change took away: the character range of `before` it deleted, and its text.
455    pub deleted: Vec<(usize, usize, String)>,
456}
457
458impl TextEdit {
459    /// Whether the change left the text as it was: a mark, not a splice.
460    #[must_use]
461    pub fn is_empty(&self) -> bool {
462        self.inserted.is_empty() && self.deleted.is_empty()
463    }
464
465    /// The name of the paragraph this text is in, when the text sits under one by a map
466    /// key: for rich text, the id of the paragraph whose `text` this is.
467    #[must_use]
468    pub fn block(&self) -> &str {
469        self.path.iter().rev().nth(1).map_or("", String::as_str)
470    }
471}
472
473/// The texts the change `hash` of `doc` spliced into, below the object `root`, each with
474/// what the change inserted into it and what it took away.
475///
476/// Which texts, from the change's own operations: a text object an operation of the change
477/// names is one it spliced, and each is read in place, whole, at the two sides of the change
478/// ([`text_at`]), and the two read as what changed. What a change inserted and what it took
479/// away is what the person sees: a word replaced whole reads as that word, never as the
480/// letters it happens to share with the one it replaced.
481///
482/// The cost is the texts the change spliced: rich text keeps each paragraph in a text of
483/// its own, so a word typed into one paragraph of a long note reads that paragraph, twice,
484/// and nothing else, and neither the note's length nor the document's is read. (Reading a
485/// rich text whole at past heads, or finding a character's place in a text this way, costs
486/// the document's operations: measured, see the test below.)
487///
488/// A change that only marked a run reads as no splice ([`TextEdit::is_empty`]).
489pub fn spliced_texts(
490    doc: &automerge::Automerge,
491    hash: &ChangeHash,
492    root: &automerge::ObjId,
493) -> Result<Vec<TextEdit>, ModelError> {
494    use automerge::ReadDoc as _;
495    let Some(change) = doc.get_change_by_hash(hash) else {
496        return Ok(Vec::new());
497    };
498    let before_heads = change.deps().to_vec();
499    let after_heads = [*hash];
500    // Which objects the change spliced, from its own operations: each op names its object.
501    // No op is looked up in the document: that search is the document's operations, and a
502    // change of a long note has as many ops as it typed characters.
503    let mut spliced: Vec<automerge::ObjId> = Vec::new();
504    for op in &change.decode().operations {
505        // A mark names the text it covers too, but marks a run of it rather than splicing
506        // it; only a put or a delete changes what the text says.
507        if matches!(
508            op.action,
509            automerge::legacy::OpType::MarkBegin(_) | automerge::legacy::OpType::MarkEnd(_)
510        ) {
511            continue;
512        }
513        let target = op_obj(doc, &op.obj)?;
514        if !spliced.contains(&target) {
515            spliced.push(target);
516        }
517    }
518    // Where each of them sits under `root`, from one walk of the rich text as it reads now.
519    let paths = paths_of(doc, root);
520    let mut out: Vec<TextEdit> = Vec::with_capacity(spliced.len());
521    for target in spliced {
522        let Some((_, path)) = paths
523            .iter()
524            .find(|(at, path)| *at == target && !path.is_empty())
525        else {
526            continue;
527        };
528        let path = path.clone();
529        let before = text_at(doc, &target, &before_heads)?;
530        let after = text_at(doc, &target, &after_heads)?;
531        let (inserted, deleted) = spliced_runs(&before, &after);
532        out.push(TextEdit {
533            path,
534            before,
535            after,
536            inserted,
537            deleted,
538        });
539    }
540    Ok(out)
541}
542
543/// The region of a text a change rewrote, as `(start, end)`: what the two sides do not share
544/// at their start and their end.
545fn region(before: &str, after: &str) -> (usize, usize, usize) {
546    let kept_start = common_chars(before, after, true);
547    let kept_end = common_chars(before, after, false);
548    (
549        kept_start,
550        before.chars().count().saturating_sub(kept_end),
551        after.chars().count().saturating_sub(kept_end),
552    )
553}
554
555/// What `text` says, as a reader reads it: the words outside the block markers a rich text
556/// lays its structure out with (each block's kind and attributes between two markers), its
557/// placeholders dropped.
558fn said(text: &str) -> String {
559    let mut out = String::with_capacity(text.len());
560    let mut open = 0usize;
561    for ch in text.chars() {
562        match ch {
563            '\u{fffc}' => open ^= 1,
564            '\u{fffe}' | '\u{fffd}' => {}
565            other if open == 0 => out.push(other),
566            _ => {}
567        }
568    }
569    out
570}
571
572/// What one text the change read at both sides made of it: the ranges of `after` the change
573/// inserted and the ranges of `before` it removed, each with its text, in reading order.
574///
575/// The runs of one text a change inserted and the runs it removed: each `(start, end, text)`.
576type Spliced = (Vec<(usize, usize, String)>, Vec<(usize, usize, String)>);
577
578/// The two sides differ in one region: what both share at their start and at their end is
579/// what the change kept. A length of zero either way is a text the change made or emptied,
580/// and the whole of it is the change's.
581fn spliced_runs(before: &str, after: &str) -> Spliced {
582    let (kept_start, deleted_end, inserted_end) = region(before, after);
583    // A change to the text's structure alone (an empty paragraph made, a body written whole
584    // over an empty one) writes nothing a reader reads.
585    let speaks = said(before).trim() != said(after).trim();
586    let spoken = |text: &str, start: usize, end: usize| {
587        speaks && !chars_between(text, start, end).trim().is_empty()
588    };
589    let inserted =
590        (kept_start < inserted_end && spoken(after, kept_start, inserted_end)).then(|| {
591            (
592                kept_start,
593                inserted_end,
594                chars_between(after, kept_start, inserted_end),
595            )
596        });
597    let deleted =
598        (kept_start < deleted_end && spoken(before, kept_start, deleted_end)).then(|| {
599            (
600                kept_start,
601                deleted_end,
602                chars_between(before, kept_start, deleted_end),
603            )
604        });
605    (
606        inserted.into_iter().collect(),
607        deleted.into_iter().collect(),
608    )
609}
610
611/// How many characters `a` and `b` share at their start (`from_start`) or their end.
612fn common_chars(a: &str, b: &str, from_start: bool) -> usize {
613    let (a, b) = if from_start {
614        (a.chars().collect::<Vec<_>>(), b.chars().collect::<Vec<_>>())
615    } else {
616        (
617            a.chars().rev().collect::<Vec<_>>(),
618            b.chars().rev().collect::<Vec<_>>(),
619        )
620    };
621    a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count()
622}
623
624/// The characters of `text` in `[start, end)`.
625fn chars_between(text: &str, start: usize, end: usize) -> String {
626    text.chars()
627        .skip(start)
628        .take(end.saturating_sub(start))
629        .collect()
630}
631
632/// The object the key `key` of the map `obj` holds as of `heads`, or `None` where it
633/// holds none: one seek into the map, never a walk of it.
634pub fn object_at(
635    doc: &automerge::Automerge,
636    obj: &automerge::ObjId,
637    key: &str,
638    heads: &[ChangeHash],
639) -> Result<Option<automerge::ObjId>, ModelError> {
640    automerge::ReadDoc::get_at(doc, obj, key, heads)
641        .map(|held| match held {
642            Some((automerge::Value::Object(_), child)) => Some(child),
643            _ => None,
644        })
645        .map_err(ModelError::from)
646}
647
648/// The text the text object `obj` held as of `heads`, read in place: the cost of this
649/// text, never of the document.
650///
651/// # Errors
652/// `obj` is not a text object of the document.
653pub fn text_at(
654    doc: &automerge::Automerge,
655    obj: &automerge::ObjId,
656    heads: &[ChangeHash],
657) -> Result<String, ModelError> {
658    automerge::ReadDoc::text_at(doc, obj, heads).map_err(ModelError::from)
659}
660
661/// How deep the keys from a rich text's field down to a paragraph's text run at most: the
662/// text of a block of the body (`b1.text`), of a note, or of a comment.
663const DEEPEST_TEXT: usize = 3;
664
665/// The map keys from `root` down to the object `obj`, outermost first, or `None` when `obj`
666/// does not sit `DEEPEST_TEXT` keys below `root`.
667///
668/// Read from the top, once for the rich text as it reads now: each map's children are its
669/// own, so the walk costs the maps the text holds and nothing of the document. (Automerge's
670/// way up from an object searches the document's every operation for that object's op, and
671/// its way down at a past version seeks each key a whole document reads: either is the
672/// note's length, and a reader of one entry cannot pay that. Only the texts a change spliced
673/// are read at the past version, and only their own characters.)
674fn paths_of(
675    doc: &automerge::Automerge,
676    root: &automerge::ObjId,
677) -> Vec<(automerge::ObjId, Vec<String>)> {
678    let mut out = Vec::new();
679    walk(doc, root, &mut Vec::new(), DEEPEST_TEXT, &mut out);
680    out
681}
682
683fn walk(
684    doc: &automerge::Automerge,
685    at: &automerge::ObjId,
686    path: &mut Vec<String>,
687    depth: usize,
688    out: &mut Vec<(automerge::ObjId, Vec<String>)>,
689) {
690    use automerge::ReadDoc as _;
691    out.push((at.clone(), path.clone()));
692    if depth == 0 {
693        return;
694    }
695    for key in doc.keys(at) {
696        if let Ok(Some((automerge::Value::Object(_), child))) = doc.get(at, key.as_str()) {
697            path.push(key.clone());
698            walk(doc, &child, path, depth.saturating_sub(1), out);
699            path.pop();
700        }
701    }
702}
703
704/// The object a change's operation names, as the document addresses it.
705fn op_obj(
706    doc: &automerge::Automerge,
707    obj: &automerge::legacy::ObjectId,
708) -> Result<automerge::ObjId, ModelError> {
709    Ok(match obj {
710        automerge::legacy::ObjectId::Root => automerge::ROOT,
711        automerge::legacy::ObjectId::Id(id) => doc.import_obj(&id.to_string())?,
712    })
713}
714
715pub fn read_at<R: Resource>(doc: &mut Doc, heads: &[ChangeHash]) -> Result<R::State, ModelError> {
716    let past = doc.fork_at(heads)?;
717    R::read(&past)
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723    use automerge::{ActorId, ROOT, ReadDoc};
724    use tilo_automerge::ApplyIncoming as _;
725
726    tilo_test_env::scenario! {
727        fn a_history_is_read_in_steps_pages_and_positions;
728
729        phase one_act_is_one_step_and_a_person_alone_is_one_step_beside_their_changes;
730        {
731            use tilo_actions::{ActionId, InvocationId};
732            let (gesture, other) = (ActionId::new(), ActionId::new());
733            let (invocation, elsewhere) = (InvocationId::new(), InvocationId::new());
734            let unnamed = |who| StepFacts {
735                who: Some(who),
736                ..StepFacts::default()
737            };
738            let in_run = |run| StepFacts {
739                run: Some(run),
740                ..StepFacts::default()
741            };
742            let of_gesture = |gesture| StepFacts {
743                gesture: Some(gesture),
744                ..StepFacts::default()
745            };
746            let in_invocation = |invocation| StepFacts {
747                invocation: Some(invocation),
748                ..StepFacts::default()
749            };
750            // The changes of one act are one step, by whichever fact the store names it, and a
751            // person's changes that name none are one step beside each other.
752            assert!(same_step(&unnamed("ada"), &unnamed("ada")));
753            assert!(same_step(&in_run("task@7"), &in_run("task@7")));
754            assert!(same_step(&of_gesture(&gesture), &of_gesture(&gesture)));
755            assert!(same_step(
756                &in_invocation(&invocation),
757                &in_invocation(&invocation)
758            ));
759            // Another act, another hand, or an act beside a change that names none: another step.
760            assert!(!same_step(&unnamed("ada"), &unnamed("bo")));
761            assert!(!same_step(&in_run("task@7"), &in_run("task@8")));
762            assert!(!same_step(&of_gesture(&gesture), &of_gesture(&other)));
763            assert!(!same_step(
764                &in_invocation(&invocation),
765                &in_invocation(&elsewhere)
766            ));
767            assert!(!same_step(&in_run("task@7"), &unnamed("alex")));
768            assert!(!same_step(&in_invocation(&invocation), &unnamed("ada")));
769        }
770
771        phase the_first_page_of_a_long_history_reads_only_that_page;
772        {
773            let mut doc = Doc::new();
774            for n in 0..2_000_i64 {
775                doc.put(ROOT, "tag", format!("t{}", n % 7)).unwrap();
776                commit_stamped_at(&mut doc, n).unwrap();
777            }
778            META_READS.with(|reads| reads.set(0));
779            let page = page(&mut doc, None, 50);
780            let read = META_READS.with(std::cell::Cell::get);
781            assert_eq!(page.versions.len(), 50);
782            assert!(page.older.is_some());
783            // Each listed change and the dependency that queues after it.
784            assert!(read <= 51, "a page of 50 read {read} changes of 2,000");
785        }
786
787        phase positions_mean_the_same_to_every_addressing_function;
788        {
789            let mut doc = combined();
790            let listed: Vec<ChangeHash> = versions(&mut doc).iter().map(|v| v.hash).collect();
791            let replayed: Vec<ChangeHash> = doc
792                .get_changes(&[])
793                .iter()
794                .map(automerge::Change::hash)
795                .collect();
796            assert_eq!(listed, replayed, "metadata and changes list in one order");
797            let changes = doc.get_changes(&[]);
798            for position in 0..listed.len() {
799                let mut rebuilt = Doc::new();
800                rebuilt
801                    .apply_incoming(changes[..=position].to_vec())
802                    .unwrap();
803                let mut heads = rebuilt.get_heads();
804                heads.compact_sort();
805                let mut expected = prefix_heads(&mut doc, position);
806                expected.compact_sort();
807                assert_eq!(heads, expected, "position {position}");
808            }
809        }
810    }
811
812    tilo_test_env::scenario! {
813        fn a_change_says_what_it_wrote;
814
815        phase a_change_says_what_it_wrote_with_the_values_before_and_after;
816        {
817            use automerge::transaction::Transactable as _;
818            use automerge::{ObjType, ScalarValue};
819            let mut doc = Doc::new();
820            let note = doc.put_object(ROOT, "note", ObjType::Map).unwrap();
821            let title = doc.put_object(&note, "title", ObjType::Text).unwrap();
822            doc.splice_text(&title, 0, 0, "Groceries").unwrap();
823            doc.put(&note, "due", "2026-10-30").unwrap();
824            doc.put(&note, "pinned", false).unwrap();
825            let first = commit_stamped_at(&mut doc, 1).unwrap();
826            // One step: the title typed into, the due day moved, `pinned` written as it was.
827            doc.splice_text(&title, 0, 9, "Shopping").unwrap();
828            doc.put(&note, "due", "2026-11-02").unwrap();
829            doc.put(&note, "pinned", ScalarValue::Boolean(false))
830                .unwrap();
831            let step = commit_stamped_at(&mut doc, 2).unwrap();
832            // A later step the earlier one's values do not see.
833            doc.put(&note, "due", "2026-12-24").unwrap();
834            commit_stamped_at(&mut doc, 3).unwrap();
835            let wrote = written(doc.document(), &step, &note).unwrap();
836            assert_eq!(
837                wrote,
838                vec![
839                    Written {
840                        prop: "title".into(),
841                        before: "Groceries".into(),
842                        after: "Shopping".into(),
843                    },
844                    Written {
845                        prop: "due".into(),
846                        before: "2026-10-30".into(),
847                        after: "2026-11-02".into(),
848                    },
849                ]
850            );
851            // The first step made everything it wrote: nothing before.
852            let made = written(doc.document(), &first, &ROOT).unwrap();
853            assert_eq!(made.len(), 1);
854            assert_eq!(made[0].prop, "note");
855            assert!(made[0].before.is_null());
856            assert_eq!(made[0].after["title"], "Groceries");
857        }
858
859        phase a_typed_paragraph_says_which_keys_of_characters_it_typed_and_erased;
860        {
861            use automerge::transaction::Transactable as _;
862            use automerge::{ObjType, ScalarValue};
863            let mut doc = Doc::new();
864            let note = doc.put_object(ROOT, "note", ObjType::Map).unwrap();
865            let body = doc.put_object(&note, "body", ObjType::Map).unwrap();
866            let blocks = doc.put_object(&body, "blocks", ObjType::Map).unwrap();
867            let first = doc.put_object(&blocks, "b1", ObjType::Map).unwrap();
868            let text = doc.put_object(&first, "text", ObjType::Text).unwrap();
869            let other = doc.put_object(&blocks, "b2", ObjType::Map).unwrap();
870            let other_text = doc.put_object(&other, "text", ObjType::Text).unwrap();
871            doc.splice_text(&text, 0, 0, "Groceries and milk").unwrap();
872            doc.splice_text(&other_text, 0, 0, "Untouched").unwrap();
873            commit_stamped_at(&mut doc, 1).unwrap();
874            // One step: a word replaced in the first paragraph, a title written beside it.
875            doc.splice_text(&text, 14, 4, "bread").unwrap();
876            doc.put(&note, "title", ScalarValue::Str("Shopping".into()))
877                .unwrap();
878            let step = commit_stamped_at(&mut doc, 2).unwrap();
879            let edits = spliced_texts(doc.document(), &step, &body).unwrap();
880            assert_eq!(edits.len(), 1, "only the paragraph typed into: {edits:?}");
881            let edit = &edits[0];
882            assert_eq!(edit.path, ["blocks", "b1", "text"]);
883            let inserted: String = edit
884                .inserted
885                .iter()
886                .map(|(_, _, text)| text.as_str())
887                .collect();
888            let deleted: String = edit
889                .deleted
890                .iter()
891                .map(|(_, _, text)| text.as_str())
892                .collect();
893            assert_eq!(inserted, "bread");
894            assert_eq!(deleted, "milk");
895            assert_eq!(edit.before, "Groceries and milk");
896            assert_eq!(edit.after, "Groceries and bread");
897            assert!(!edit.is_empty());
898        }
899
900        phase a_body_retyped_whole_reads_as_what_was_there_and_what_was_written;
901        {
902            use automerge::ObjType;
903            use automerge::transaction::Transactable as _;
904            let mut doc = Doc::new();
905            let body = doc.put_object(ROOT, "body", ObjType::Map).unwrap();
906            let text = doc.put_object(&body, "text", ObjType::Text).unwrap();
907            doc.splice_text(&text, 0, 0, "Groceries and milk").unwrap();
908            commit_stamped_at(&mut doc, 1).unwrap();
909            // A control hands over its whole text: the whole of what was there goes, and what
910            // was typed in its place comes.
911            doc.splice_text(&text, 0, 15, "Oat milk and bread").unwrap();
912            let step = commit_stamped_at(&mut doc, 2).unwrap();
913            let edits = spliced_texts(doc.document(), &step, &body).unwrap();
914            let edit = &edits[0];
915            let inserted: String = edit
916                .inserted
917                .iter()
918                .map(|(_, _, text)| text.as_str())
919                .collect();
920            let deleted: String = edit
921                .deleted
922                .iter()
923                .map(|(_, _, text)| text.as_str())
924                .collect();
925            assert_eq!(inserted, "Oat milk and bread");
926            // "il" is shared by "milk" and "bread" at the end, so those two stand outside the
927            // region the change rewrote: the reader sees the part that differs, as anybody
928            // reading the two texts sees it.
929            assert_eq!(deleted, "Groceries and m");
930            assert_eq!(edit.before, "Groceries and milk");
931            // The trailing "il" the record kept is still there, after the typed text.
932            assert_eq!(edit.after, "Oat milk and breadilk");
933        }
934
935        phase a_paragraph_the_change_only_marked_reads_as_no_splice;
936        {
937            use automerge::ObjType;
938            use automerge::marks::Mark;
939            use automerge::transaction::Transactable as _;
940            let mut doc = Doc::new();
941            let body = doc.put_object(ROOT, "body", ObjType::Map).unwrap();
942            let text = doc.put_object(&body, "text", ObjType::Text).unwrap();
943            doc.splice_text(&text, 0, 0, "Groceries").unwrap();
944            commit_stamped_at(&mut doc, 1).unwrap();
945            doc.mark(
946                &text,
947                Mark::new("strong".to_owned(), true, 0, 9),
948                automerge::marks::ExpandMark::Both,
949            )
950            .unwrap();
951            let step = commit_stamped_at(&mut doc, 2).unwrap();
952            let edits = spliced_texts(doc.document(), &step, &body).unwrap();
953            assert!(edits.iter().all(TextEdit::is_empty), "{edits:?}");
954        }
955    }
956
957    fn check_empty_commit_actor_transition(open_empty: bool) {
958        let mut doc = Doc::new();
959        doc.set_actor(ActorId::from(vec![0x80]));
960        doc.put(ROOT, "body", "seed").unwrap();
961        commit_stamped_at(&mut doc, 1).unwrap();
962        let heads = doc.get_heads();
963        doc.set_actor(ActorId::from(vec![0x10]));
964        if open_empty {
965            doc.delete(ROOT, "absent").unwrap();
966            assert_eq!(doc.pending_ops(), 0);
967        }
968        assert_eq!(commit_stamped_at(&mut doc, 2), None);
969        assert_eq!(doc.get_heads(), heads);
970        doc.set_actor(ActorId::from(vec![0x20]));
971        doc.put(ROOT, "body", "edited").unwrap();
972        let change = commit_stamped_at(&mut doc, 3).unwrap();
973        assert_eq!(doc.get_change_by_hash(&change).unwrap().timestamp(), 3);
974        let after = doc.get_heads();
975        let patches = doc.diff(&heads, &after);
976        assert!(matches!(patches.as_slice(), [automerge::Patch {
977            action: automerge::PatchAction::PutMap { key, value, .. }, ..
978        }] if key == "body" && value.0.as_str() == Some("edited")));
979    }
980
981    tilo_test_env::scenario! {
982        fn an_empty_commit_poisons_no_actor_and_stays_tracked;
983
984        phase empty_stamped_commit_does_not_poison_next_actor;
985        {
986            check_empty_commit_actor_transition(false);
987        }
988
989        phase empty_open_transaction_does_not_poison_next_actor;
990        {
991            check_empty_commit_actor_transition(true);
992        }
993
994        phase an_empty_stamped_commit_keeps_changes_tracked_incrementally;
995        {
996            let mut doc = Doc::new();
997            doc.put(ROOT, "n", 0).unwrap();
998            commit_stamped_at(&mut doc, 1).unwrap();
999            let mut tracker = crate::Tracker::new();
1000            tracker.start(&mut doc);
1001            for (n, actor) in [(1_i64, 0x10_u8), (2, 0x20)] {
1002                doc.set_actor(ActorId::from(vec![actor]));
1003                assert_eq!(commit_stamped_at(&mut doc, 2), None);
1004                doc.put(ROOT, "n", n).unwrap();
1005                commit_stamped_at(&mut doc, 3).unwrap();
1006                let delta = tracker.delta(&mut doc);
1007                assert!(!delta.is_everything(), "round {n}");
1008                assert_eq!(delta.key(&ROOT, "n"), crate::Touch::Written);
1009            }
1010        }
1011    }
1012
1013    /// Two members' interleaved, combined edits.
1014    fn combined() -> Doc {
1015        let mut left = Doc::new();
1016        left.put(ROOT, "n", 0).unwrap();
1017        commit_stamped_at(&mut left, 1).unwrap();
1018        let mut right = left.fork();
1019        for round in 1..8_i64 {
1020            left.put(ROOT, "left", round).unwrap();
1021            commit_stamped_at(&mut left, round).unwrap();
1022            right.put(ROOT, "right", round).unwrap();
1023            commit_stamped_at(&mut right, round).unwrap();
1024            if round % 3 == 0 {
1025                left.merge_incoming(&mut right).unwrap();
1026                right.merge_incoming(&mut left).unwrap();
1027            }
1028        }
1029        left.merge_incoming(&mut right).unwrap();
1030        left
1031    }
1032}