Skip to main content

tilo_actions/
lib.rs

1//! # Tilo ACTION model
2//!
3//! The state layer behind Ctrl+K and cross-peer collaboration: a
4//! serializable, **replayable** unit of CRDT mutation.
5//!
6//! ## Play locally, replay anywhere
7//!
8//! An [`Action`] is a *value* that deterministically mutates a CRDT
9//! [`Doc`]. Applied to the local replica, its
10//! [`ActionEnvelope`] is replicated; a peer starting from the same state
11//! [`replay`]s it and lands on the **identical**
12//! document — the [executor] pins the Automerge actor id (from
13//! the action's [`ActionId`]) and commit timestamp on every apply, so
14//! the resulting change is content-addressed identical everywhere.
15//!
16//! Replayable [`Action`] values are strictly **not presentation** and mutate
17//! only shared CRDT state. The wider resource/action protocol also describes
18//! client-local [`OperationKind::View`] and external
19//! [`OperationKind::Effect`] operations. Those use the same typed descriptors,
20//! permission checks and invocation receipts, but are dispatched through the
21//! toolkit's operation handler instead of being replayed as document history.
22//!
23//! ## Resources
24//!
25//! An app publishes the tree of [`ResourceSpec`]s it currently has open (a
26//! video → its comments; a book → its annotations) through the toolkit's
27//! `PublishesResources`. Each resource exports [`ActionSpec`]s; the
28//! palette lists them, and choosing one
29//! [`dispatch`]es the underlying action.
30//!
31//! ## The action API
32//!
33//! A resource tree is only useful to the app that built it until someone
34//! else can reach it. [`api`] is that reach: [`api::survey`] turns a
35//! live tree into inert, stably-addressed descriptors, and
36//! [`api::invoke`] performs one attributed to the caller — so another
37//! session acts on an app without the app growing a remote-control
38//! surface of its own.
39//!
40//! ## Remote use
41//!
42//! [`remote`] carries the action API across machines: a versioned, transport-neutral
43//! vocabulary for listing, invoking, observing and cancelling another peer's
44//! actions, and the [`remote::ActionProvider`] trait a peer implements to answer
45//! it. The caller is always the actor the transport authenticated, and
46//! invocations are idempotent per [`InvocationId`].
47//!
48//! ## Execution locus
49//!
50//! Each action declares an [`ExecutionLocus`]: `ClientLocal` (this
51//! client applies + replicates; peers replay) or `ServerPreferred`
52//! (route to an authoritative host). [`dispatch`] honours
53//! it against an [`ActionTransport`] and refuses
54//! the operation when no host answers.
55//!
56//! ## Sharing this vocabulary with the compositor
57//!
58//! [`params`] is the *same* vocabulary the compositor's headless
59//! action API speaks — [`ParamType`], [`ActionParam`], [`ArgValue`], and the
60//! strict [`ActionArgs::bind`] — lifted into one definition rather than left to
61//! converge by accident. The wire spellings of `text` / `integer` / `boolean`
62//! and the bind semantics (unknown argument refused, first failure wins,
63//! nothing partial reaches an action) are unchanged from that surface, and the
64//! `const` constructors keep a `const PARAMS: &[ActionParam] = &[…]` compiling
65//! as written.
66//!
67//! Two additive extensions: [`ParamType::Number`], because the
68//! app-side arguments this replaces are overwhelmingly fractional and rounding
69//! them would discard the values they exist to carry; and
70//! [`ActionParam::choices`], which turns a prose list into something a caller
71//! can read and binding can enforce. The string fields are
72//! [`Cow<'static, str>`](std::borrow::Cow) rather than `&'static str` because an
73//! app builds its parameters per frame out of live document state — a `const`
74//! declaration is `Cow::Borrowed` and costs nothing.
75//!
76//! ## Plain vocabulary
77//!
78//! The parts of Tilo's resource vocabulary that need no store, document or
79//! CRDT live here too: the smallest splice between two texts ([`splice_between`]),
80//! the scope a search looks within ([`ScopeDecl`]), the kind an item's address
81//! names ([`item_kind`]), the name a workspace emoji is written by
82//! ([`custom_emoji_name`]), the catalogue key a kind is named under
83//! ([`message_key`]), the id of a history entry ([`HistoryEntryId`]), the named
84//! scopes the app framework is profiled by ([`profiling`]).
85//! `tilo-resource` publishes them where they have always been; the toolkit reads
86//! them here, with or without that model.
87
88#![cfg_attr(
89    test,
90    allow(
91        clippy::string_slice,
92        clippy::unreachable,
93        reason = "in a test these are the assertion, not a hazard"
94    )
95)]
96
97/// Serde for a JSON-only type whose reading goes through one
98/// `serde_json::Value`.
99///
100/// The type derives with `#[serde(remote = "Self")]`, which makes its
101/// derived code inherent functions. Writing runs them as derived. Reading
102/// runs them once, against a `Value`, in the crate that declares the type:
103/// every format and every crate that reads the type then shares that one
104/// copy instead of compiling the type's whole deserializer (and, for an
105/// internally tagged enum, its buffered copy) again for each deserializer it
106/// meets. Only for types every encoding of which is JSON: a `Value` needs a
107/// self-describing format. `custom` leaves `from_json_value` to the type.
108/// `write` also writes through one `Value`, built by a function compiled in
109/// the declaring crate, so a crate that writes the type compiles none of its
110/// serializer either; the JSON is the same.
111#[macro_export]
112macro_rules! read_through_json_value {
113    ($ty:ty) => {
114        $crate::read_through_json_value!($ty, custom);
115
116        impl $ty {
117            #[inline(never)]
118            fn from_json_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
119                Self::deserialize(value)
120            }
121        }
122    };
123    ($ty:ty, custom) => {
124        impl serde::Serialize for $ty {
125            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
126                Self::serialize(self, serializer)
127            }
128        }
129
130        $crate::read_through_json_value!($ty, read);
131    };
132    ($ty:ty, write) => {
133        impl serde::Serialize for $ty {
134            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
135                match self.to_json_value() {
136                    Ok(value) => serde::Serialize::serialize(&value, serializer),
137                    Err(error) => Err(serde::ser::Error::custom(error)),
138                }
139            }
140        }
141
142        $crate::read_through_json_value!($ty, read);
143
144        impl $ty {
145            #[inline(never)]
146            fn from_json_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
147                Self::deserialize(value)
148            }
149
150            #[inline(never)]
151            fn to_json_value(&self) -> Result<serde_json::Value, serde_json::Error> {
152                Self::serialize(self, serde_json::value::Serializer)
153            }
154        }
155    };
156    ($ty:ty, read) => {
157        impl<'de> serde::Deserialize<'de> for $ty {
158            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
159                let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
160                Self::from_json_value(value).map_err(serde::de::Error::custom)
161            }
162        }
163    };
164}
165
166/// Serde for a type kept as JSON and in a binary format: in a human-readable
167/// format (JSON, a `serde_json::Value`, serde's buffered content) it is read
168/// and written through one `Value`, by functions compiled once in the crate
169/// that declares it; in any other (postcard) by its derived code, unchanged.
170///
171/// The type derives with `#[serde(remote = "Self")]`, as for
172/// [`read_through_json_value!`]. A crate that reads or writes the type as JSON
173/// then compiles only the `Value` step, not the type's whole serializer and
174/// deserializer (and, for an internally tagged or flattened type, its buffered
175/// copy) once per format it meets. The JSON is the same: a `Value`'s map keeps
176/// the order its fields were written in. `read` routes only reading, for a
177/// type whose `Serialize` is its own.
178#[macro_export]
179macro_rules! readable_through_json_value {
180    ($ty:ty) => {
181        impl serde::Serialize for $ty {
182            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
183                if !serializer.is_human_readable() {
184                    return Self::serialize(self, serializer);
185                }
186                match self.to_readable_json() {
187                    Ok(value) => serde::Serialize::serialize(&value, serializer),
188                    Err(error) => Err(serde::ser::Error::custom(error)),
189                }
190            }
191        }
192
193        impl $ty {
194            #[inline(never)]
195            fn to_readable_json(&self) -> Result<serde_json::Value, serde_json::Error> {
196                Self::serialize(self, serde_json::value::Serializer)
197            }
198        }
199
200        $crate::readable_through_json_value!($ty, read);
201    };
202    ($ty:ty, read) => {
203        impl<'de> serde::Deserialize<'de> for $ty {
204            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
205                if !deserializer.is_human_readable() {
206                    return Self::deserialize(deserializer);
207                }
208                let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
209                Self::from_readable_json(value).map_err(serde::de::Error::custom)
210            }
211        }
212
213        impl $ty {
214            #[inline(never)]
215            fn from_readable_json(value: serde_json::Value) -> Result<Self, serde_json::Error> {
216                Self::deserialize(value)
217            }
218        }
219    };
220}
221
222/// Serde for an enum written as one object whose `$tag` field names the
223/// variant, beside the variant's own fields: the form of
224/// `#[serde(tag = "...")]`, the same JSON field for field and in order.
225///
226/// The enum derives with `#[serde(remote = "Self")]` in place of `tag`, so
227/// the derive writes a variant as an object's only key, and this moves the
228/// name between the two places through one `serde_json::Value`, by code
229/// compiled once here. serde reads a `tag` enum by buffering the object in
230/// its private `Content` form and gives every struct inside two more readers
231/// for that, in every crate that reads the enum; read through a `Value`, each
232/// struct keeps the one reader a `Value` has. A unit variant reads from its
233/// name alone, any other fields beside it ignored, as with `tag`. `read`
234/// routes only reading, for an enum that derives only `Deserialize`.
235#[macro_export]
236macro_rules! tagged_through_json_value {
237    ($ty:ty, $tag:literal) => {
238        $crate::tagged_through_json_value!($ty, $tag, read);
239
240        impl serde::Serialize for $ty {
241            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
242                let named = Self::serialize(self, serde_json::value::Serializer)
243                    .map_err(serde::ser::Error::custom)?;
244                let tagged = $crate::tagged_json::tag_inside(named, $tag)
245                    .map_err(serde::ser::Error::custom)?;
246                serde::Serialize::serialize(&tagged, serializer)
247            }
248        }
249    };
250    ($ty:ty, $tag:literal, read) => {
251        impl<'de> serde::Deserialize<'de> for $ty {
252            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
253                let object = <serde_json::Map<String, serde_json::Value> as serde::Deserialize>::deserialize(
254                    deserializer,
255                )?;
256                let (named, unit) = $crate::tagged_json::tag_outside(object, $tag)
257                    .map_err(serde::de::Error::custom)?;
258                Self::deserialize(named)
259                    .or_else(|error| Self::deserialize(unit).map_err(|_| error))
260                    .map_err(serde::de::Error::custom)
261            }
262        }
263    };
264}
265
266/// The two halves of [`tagged_through_json_value!`], compiled once.
267#[doc(hidden)]
268pub mod tagged_json {
269    use serde_json::{Map, Value};
270
271    /// `{"variant": {fields}}`, or a unit variant's `"variant"`, as
272    /// `{"<tag>": "variant", fields}`.
273    #[inline(never)]
274    pub fn tag_inside(named: Value, tag: &str) -> Result<Value, String> {
275        let (variant, fields) = match named {
276            Value::String(variant) => (variant, Map::new()),
277            Value::Object(named) if named.len() == 1 => match named.into_iter().next() {
278                Some((variant, Value::Object(fields))) => (variant, fields),
279                Some((variant, _)) => {
280                    return Err(format!(
281                        "the variant `{variant}` holds no fields, so it has no place for `{tag}`"
282                    ));
283                }
284                None => return Err("an empty object is not a variant".to_owned()),
285            },
286            other => return Err(format!("{other} is not a variant")),
287        };
288        let mut object = Map::with_capacity(fields.len().saturating_add(1));
289        object.insert(tag.to_owned(), Value::String(variant));
290        object.extend(fields);
291        Ok(Value::Object(object))
292    }
293
294    /// `{"<tag>": "variant", fields}` as `{"variant": {fields}}`, and as the
295    /// unit variant `"variant"` to read when that is what it names.
296    #[inline(never)]
297    pub fn tag_outside(
298        mut object: Map<String, Value>,
299        tag: &str,
300    ) -> Result<(Value, Value), String> {
301        let variant = match object.remove(tag) {
302            Some(Value::String(variant)) => variant,
303            Some(other) => return Err(format!("`{tag}` is {other}, not a variant name")),
304            None => return Err(format!("missing field `{tag}`")),
305        };
306        let unit = Value::String(variant.clone());
307        let mut named = Map::with_capacity(1);
308        named.insert(variant, Value::Object(object));
309        Ok((Value::Object(named), unit))
310    }
311}
312
313pub mod action;
314pub mod agent_disclosure;
315pub mod api;
316pub mod appearance;
317#[cfg(feature = "asks")]
318pub mod asks;
319pub mod compact;
320pub mod content;
321pub mod context;
322pub mod contract;
323pub mod document_sync;
324pub mod draft;
325mod emoji;
326pub mod entry;
327pub mod envelope;
328pub mod executor;
329pub mod field_type;
330pub mod framework;
331pub mod group_form;
332mod history;
333pub mod interaction;
334mod item;
335pub mod key;
336mod label;
337pub mod noun;
338pub mod offload;
339pub mod opened_by;
340pub mod outcome;
341pub mod outside_document;
342pub mod params;
343pub mod prefill;
344pub mod profiling;
345pub mod protocol;
346pub mod published;
347pub mod reaction;
348pub mod receipt;
349mod refusal;
350pub mod registry;
351pub mod remote;
352pub mod resource;
353pub mod row_status;
354pub mod run;
355pub mod schema;
356mod scope;
357pub mod selection;
358pub mod selectors;
359pub mod send_to;
360pub mod stamp;
361pub mod step;
362pub mod surface;
363pub mod task_step;
364pub mod terminal_text;
365mod text;
366pub mod tree;
367
368pub use action::{
369    Action, ActionError, ActionId, ActionStep, Declined, Doc, EncodedAction, ExecutionLocus,
370    MAX_TEXT_BYTES, OperationKind, RECALL_SUMMARY_BYTES, asks_first, codes, undo_takes_back,
371};
372pub use agent_disclosure::hidden_from_agents;
373pub use api::{
374    ActionAddress, ActionDescriptor, ActionEffect, ApiError, InputSpec, NOT_THE_ASKED_PERSON,
375    ResourceViewDescriptor,
376};
377pub use appearance::{Appearance, AppearanceError, Persona};
378pub use content::{
379    CONTENT_PART_THRESHOLD, CONTENT_REFERENCE_KEY, ContentParts, MissingContent, current, register,
380};
381pub use context::{
382    ActionApp, ActionContext, ActionFacet, ActionInvoker, ActionResource, CHANGE_MESSAGE_PREFIX,
383    CONTINUATION_PREFIX, Cause, ChangeKind, InvokerDevice, MAX_PRESENCE_ID_BYTES, PLACE_FACET,
384    PresenceId, RISK_FACET, WorkGroup,
385};
386pub use contract::{
387    AGENTS_AUDIENCE_TAG, ARGUMENT_RISK_TAG, ATTENDED_TAG, ActionContract, ActionKind, ActionNeed,
388    Audience, Availability, CARRIER_TAG, COMPENSATED_UNDO_TAG, ConfirmationPolicy,
389    DOCUMENT_READ_TAG, ExecutionMode, HOST_RENDER_TAG, HOST_UNSUPPORTED_CODE, HOUSEKEEPING_TAG,
390    INCOMING_MESSAGE_FACET, INCOMING_MESSAGE_TAG, IRREVERSIBLE_TAG, MAX_OFFLOAD_CPU_TIME_MS,
391    MAX_OFFLOAD_MEMORY_BYTES, MAX_OFFLOAD_OUTPUT_BYTES, MEMBER_OWN_TAG, MIN_OFFLOAD_MEMORY_BYTES,
392    OPENS_HIT_TAG, OPENS_PATH_EXTENSION_PREFIX, OPENS_PATH_TAG, ORIGIN_FACET,
393    OUTSIDE_CAPABILITY_PREFIX, OWN_DEVICE_SCOPE, Offload, PEOPLE_AUDIENCE_TAG, READERS_FACET,
394    REQUIRES_HOST_PREFIX, REQUIRES_NATIVE_PATHS_TAG, RESOURCE_READ_TAG, ROOT_ONLY_TAG,
395    ROUTED_CHANGE_TAG, ResultSpec, RetryPolicy, RiskLevel, SCREEN_PLACE_TAG, SCREEN_TAG,
396    SEARCH_KIND_PREFIX, SEARCH_TAG, SECRET_ANSWER_TAG, UNTRUSTED_CONTENT_TAG, action_node,
397    phrase_is_meaningful, resource_node,
398};
399pub use draft::{Draft, DraftEdit, DraftField, DraftLayout, DraftValue, MessageRole};
400pub use emoji::{MAX_CUSTOM_NAME, custom_emoji_name, valid_custom_emoji_name};
401pub use entry::{
402    ActionItem, Described, Did, EditOp, FieldEdit, GroupOf, HistoryOp, HistoryStep, PathStep,
403    Scalar, VerbCall,
404};
405pub use envelope::ActionEnvelope;
406pub use executor::{
407    ActionTransport, CompensatingScope, Dispatched, EntryReader, HostDecision, LocalTransport,
408    UNDONE_KEY, Verified, apply_local, apply_local_by, apply_local_with_context,
409    await_compensation, await_settlement, commit_written, current_step, dispatch, dispatch_by,
410    dispatch_by_with_context, dispatch_with_context, entry_message, entry_of, envelope_at,
411    invoking_context, open_step, reading_invoking_context, replay, replay_decoded, replaying_as,
412    settle_compensation, verify_change, with_invoking_context,
413};
414pub use framework::FrameworkChange;
415pub use history::{HistoryEntryId, change_hex, entry_hex, entry_id};
416pub use interaction::{
417    INTERACTION_VERSION, InteractionAction, InteractionAnchor, InteractionGridRange,
418    InteractionPhase, InteractionTextRange, InteractionUpdate, InteractionViolation,
419    MAX_ANCHOR_ITEMS, MAX_DETAIL_BYTES, MAX_ID_BYTES, MAX_INTERACTION_BYTES, MAX_LABEL_BYTES,
420    SemanticInteraction,
421};
422pub use item::item_kind;
423pub use key::{ActionKey, CREATE_ACTION};
424pub use label::{message_key, noun_key};
425pub use outcome::{
426    ActionFailure, ActionOutput, CONTENT_RESOURCE_KIND, EffectReceiptStatus, InvocationId,
427    InvocationUpdate, content_hash, content_resource, named_reference,
428};
429pub use params::{
430    ARGUMENTS_JSON_PREFIX, ActionArgs, ActionParam, ArgError, ArgValue, ArgViolation,
431    CHOICE_LABELS_ANNOTATION, CONTENT_ANNOTATION, PEOPLE_ANNOTATION, PICK_ANNOTATION,
432    PLACE_ANNOTATION, ParamType, Pick, RESOURCE_KINDS_ANNOTATION, SHAPED_BY_ANNOTATION,
433    picked_address_schema, picked_resource_schema, place_schema, resource_reference_schema,
434    shaped_by_schema, validate_json_schema,
435};
436pub use protocol::{ContractViolation, validate_surface, validate_surface_contracts};
437pub use refusal::Refusal;
438pub use registry::{ActionRegistry, DecodePayload, decode_json, decode_payload};
439pub use resource::{
440    ActionBinding, ActionBindingError, ActionInput, ActionSpec, ActionState, ActionType,
441    ArgsBuilder, Collects, ContinuationArguments, ContinuationEvidence, ContinuationKey,
442    ContinuationQuery, ControlInvocation, Exports, FlatAction, KEY_SEP, ListedRow,
443    NESTED_RESOURCE_FACET, Noun, PROMPTED_PARAM, ReadingRow, ResourceId, ResourcePresentation,
444    ResourceSemanticIdentity, ResourceSpec, ResourceType, ResourceViewMountSpec,
445    ResourceViewRangeSpec, ResourceViewSpec, RunBy, SEMANTIC_OPERATION_TYPE, Target, action_label,
446    app_label, flatten, in_words, kind_is_a_drawn_control, kind_mirrors_a_control,
447    listed_for_people, listed_row, listed_row_problems, plural, singular, sole_text_argument,
448};
449pub use row_status::{RowStatus, apply_row_statuses};
450pub use schema::{
451    CatalogueSchemaEntry, ContextRequirement, PRESENCE_VIEW_TAG, REQUIRES_TAG_PREFIX,
452    catalogue_schema, catalogue_schema_bytes,
453};
454pub use scope::{ScopeDecl, scope_contains};
455pub use selection::{
456    BOUND_RESOURCE_PREFIX, MAX_EXCERPT_BYTES, MAX_EXCERPT_CHARS, MAX_SELECTED_ITEMS,
457    SelectionAnchor, SelectionPlace, SelectionSubject, excerpt_of, logical_resource_id,
458};
459pub use send_to::{Recipient, RecipientKind, recipients_matching};
460pub use step::{Step, StepKind};
461pub use text::{Splice, common_ends, common_text_ends, splice_between};
462/// Grants and the decisions over them, as apps read and show them.
463pub use tilo_action_policy as policy;
464/// The field a resource's comments live in: an action that only comments
465/// is placed below it ([`ActionContract::field`]), where someone who may only
466/// comment is granted changes.
467pub use tilo_action_policy::roles::{COMMENTS_FIELD, MODERATION_FIELD};
468pub use tilo_action_policy::{Acting, Actor, MemberId, PersonId};
469
470/// The stable address (`kind:id`) of the item an item resource id names: `<kind>.<field>:<item>`
471/// for `<kind>/<field>/<item>` — the address an action's resource parameter takes. An app that
472/// publishes an item under its stable address resolves a link written in the older item form
473/// through this; `None` for an id naming no item of a top-level collection.
474#[must_use]
475pub fn stable_item_address(resource_id: &str) -> Option<String> {
476    let (collection, item) = resource_id.rsplit_once('/')?;
477    let (kind, field) = collection.split_once('/')?;
478    (!kind.is_empty()
479        && !field.is_empty()
480        && !field.contains('/')
481        && !item.is_empty()
482        && !resource_id.contains(':'))
483    .then(|| format!("{kind}.{field}:{item}"))
484}
485
486/// The item form (`<kind>/<field>/<item>`) of an item's stable address (`<kind>.<field>:<item>`):
487/// what an app that publishes its items in the item form publishes the item a stable link names
488/// under. `None` for an address that names no item of a collection (`tl:app:root-x`).
489#[must_use]
490pub fn item_form_of(address: &str) -> Option<String> {
491    let (kind_field, item) = address.split_once(':')?;
492    let (kind, field) = kind_field.rsplit_once('.')?;
493    (!kind.is_empty()
494        && !field.is_empty()
495        && !item.is_empty()
496        && !item.contains(':')
497        && !address.contains('/'))
498    .then(|| format!("{kind}/{field}/{item}"))
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504    use automerge::transaction::Transactable;
505
506    /// An item's older form names the same item at its stable address; anything else names none.
507    #[test]
508    fn an_items_older_form_names_its_stable_address() {
509        assert_eq!(
510            stable_item_address("chat.workspace/channels/c1").as_deref(),
511            Some("chat.workspace.channels:c1")
512        );
513        assert_eq!(stable_item_address("chat.workspace.channels:c1"), None);
514        assert_eq!(stable_item_address("tl:so.tilo.notes:root-x"), None);
515        assert_eq!(stable_item_address("notes/pages/p1/blocks/b2"), None);
516        assert_eq!(
517            item_form_of("chat.workspace.messages:m1").as_deref(),
518            Some("chat.workspace/messages/m1"),
519            "a stable address names the item an app publishes in the item form"
520        );
521        assert_eq!(item_form_of("tl:so.tilo.notes:root-x"), None);
522    }
523    use automerge::{AutoCommit, ROOT, ReadDoc, ScalarValue};
524    use serde::{Deserialize, Serialize};
525    use tilo_automerge::ApplyIncoming;
526
527    /// A real action: set a scalar under a key, and (for lists) append.
528    /// Mutates only via the passed doc, no wall-clock/RNG — the determinism contract.
529    #[derive(Debug, Clone, Serialize, Deserialize)]
530    enum Counter {
531        Put { key: String, value: i64 },
532        Append { key: String, value: String },
533    }
534
535    const COUNTER_TYPE: &str = "test.counter";
536
537    impl Action for Counter {
538        fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
539            match self {
540                Counter::Put { key, value } => {
541                    doc.put(&ROOT, key, ScalarValue::Int(*value))?;
542                }
543                Counter::Append { key, value } => {
544                    let list = match doc.get(&ROOT, key)? {
545                        Some((automerge::Value::Object(automerge::ObjType::List), id)) => id,
546                        _ => doc.put_object(&ROOT, key, automerge::ObjType::List)?,
547                    };
548                    let len = doc.length(&list);
549                    doc.insert(&list, len, ScalarValue::Str(value.as_str().into()))?;
550                }
551            }
552            Ok(())
553        }
554
555        fn locus(&self) -> ExecutionLocus {
556            match self {
557                // Appends prefer a host so a shared list is serialized.
558                Counter::Append { .. } => ExecutionLocus::ServerPreferred,
559                Counter::Put { .. } => ExecutionLocus::ClientLocal,
560            }
561        }
562    }
563
564    /// A read marker: shared state about the document, not its content.
565    #[derive(Debug, Clone, Serialize, Deserialize)]
566    struct Seen(i64);
567
568    const SEEN_TYPE: &str = "test.seen";
569
570    impl Action for Seen {
571        fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
572            doc.put(&ROOT, "seen", ScalarValue::Int(self.0))?;
573            Ok(())
574        }
575
576        fn change_kind(&self) -> ChangeKind {
577            ChangeKind::Housekeeping
578        }
579    }
580
581    fn registry() -> ActionRegistry {
582        let mut r = ActionRegistry::new();
583        r.register::<Counter>(COUNTER_TYPE);
584        r.register::<Seen>(SEEN_TYPE);
585        r
586    }
587
588    fn decode_seen(payload: &[u8]) -> Result<Box<dyn Action>, serde_json::Error> {
589        serde_json::from_slice::<Seen>(payload).map(|seen| Box::new(seen) as Box<dyn Action>)
590    }
591
592    fn last_message(doc: &mut AutoCommit) -> Option<String> {
593        let heads = doc.get_heads();
594        doc.get_change_by_hash(heads.first()?)?
595            .message()
596            .map(ToString::to_string)
597    }
598
599    fn last_context(doc: &mut AutoCommit) -> Option<ActionContext> {
600        ActionContext::from_change_message(&last_message(doc)?)
601    }
602
603    /// Seed two independent replicas that share history (so a replayed
604    /// change has identical deps), each with its OWN actor for normal edits.
605    fn two_replicas() -> (AutoCommit, AutoCommit) {
606        let mut a = AutoCommit::new();
607        a.put(&ROOT, "seed", ScalarValue::Str("s".into())).unwrap();
608        a.commit();
609        let bytes = a.save();
610        let b = AutoCommit::load(&bytes).unwrap();
611        (a, b)
612    }
613
614    /// THE HEADLINE TEST. An action applied on replica A, replicated, and
615    /// replayed on replica B (from the same state) yields the **identical**
616    /// document — same head hashes, not merely the same values.
617    fn action_replays_to_identical_doc_on_peer() {
618        let (mut a, mut b) = two_replicas();
619        assert_eq!(
620            a.get_heads(),
621            b.get_heads(),
622            "precondition: same base state"
623        );
624
625        let action = Counter::Put {
626            key: "score".into(),
627            value: 42,
628        };
629        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
630
631        let env = apply_local(&mut a, &action, encoded).unwrap();
632
633        replay(&mut b, &env, &registry()).unwrap();
634
635        // Identical *history*, not just identical materialized values.
636        assert_eq!(
637            a.get_heads(),
638            b.get_heads(),
639            "replay reproduces the identical change on the peer"
640        );
641        let av = a.get(&ROOT, "score").unwrap().unwrap().0;
642        let bv = b.get(&ROOT, "score").unwrap().unwrap().0;
643        assert_eq!(av.as_i64(), Some(42));
644        assert_eq!(bv.as_i64(), av.as_i64());
645    }
646
647    /// Two peers can author from the same base and receive each other's
648    /// envelopes after their own action has already advanced the live doc.
649    /// Replay must still reproduce each action at its recorded base and merge
650    /// the resulting CRDT change; applying either payload directly to the
651    /// newer live state would make document-reading actions order-dependent.
652    fn concurrent_envelopes_replay_from_their_recorded_base() {
653        let (mut a, mut b) = two_replicas();
654        let left = Counter::Put {
655            key: "left".into(),
656            value: 1,
657        };
658        let right = Counter::Put {
659            key: "right".into(),
660            value: 2,
661        };
662
663        let left_env = apply_local(
664            &mut a,
665            &left,
666            EncodedAction::encode(COUNTER_TYPE, &left).unwrap(),
667        )
668        .unwrap();
669        let right_env = apply_local(
670            &mut b,
671            &right,
672            EncodedAction::encode(COUNTER_TYPE, &right).unwrap(),
673        )
674        .unwrap();
675
676        replay(&mut a, &right_env, &registry()).unwrap();
677        replay(&mut b, &left_env, &registry()).unwrap();
678
679        assert_eq!(a.get_heads(), b.get_heads());
680        for doc in [&a, &b] {
681            assert_eq!(doc.get(&ROOT, "left").unwrap().unwrap().0.as_i64(), Some(1));
682            assert_eq!(
683                doc.get(&ROOT, "right").unwrap().unwrap().0.as_i64(),
684                Some(2)
685            );
686        }
687    }
688
689    /// The replayed change is content-addressed *identical* to the origin's,
690    /// so if the replicas later exchange native Automerge changes (ordinary
691    /// CRDT sync) the duplicate dedupes instead of double-applying — why
692    /// pinning actor + time on every apply matters.
693    fn replayed_change_dedupes_against_native_automerge_merge() {
694        let (mut a, mut b) = two_replicas();
695        let action = Counter::Append {
696            key: "queue".into(),
697            value: "vid1".into(),
698        };
699        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
700        // This test is about deterministic replay, not locus routing; apply it
701        // explicitly at the origin and retain the resulting envelope.
702        let env = apply_local(&mut a, &action, encoded).unwrap();
703
704        // B replays the envelope -> reproduces the identical change.
705        replay(&mut b, &env, &registry()).unwrap();
706        assert_eq!(a.get_heads(), b.get_heads(), "replay == origin change");
707        let heads_after_replay = b.get_heads();
708
709        // Now B *also* receives A's native Automerge change via ordinary CRDT
710        // sync. Since it's the same content-addressed change B already
711        // replayed, the merge is a no-op: no second append.
712        let a_bytes = a.save();
713        let mut a_native = AutoCommit::load(&a_bytes).unwrap();
714        b.merge_incoming(&mut a_native).unwrap();
715        assert_eq!(
716            b.get_heads(),
717            heads_after_replay,
718            "native merge of the identical change dedupes"
719        );
720        let (_, list) = b.get(&ROOT, "queue").unwrap().unwrap();
721        assert_eq!(b.length(&list), 1, "no double-apply");
722    }
723
724    tilo_test_env::scenario! {
725        fn dispatch_records_and_replay_reproduces_a_change;
726
727        phase a_registered_decoder_decodes_its_type_and_names_it_when_it_cannot;
728        // A type registered with a decoder of its own decodes, and applies, as
729        // one registered by type; a payload it cannot decode is a decode error
730        // naming the type.
731        {
732            let mut registry = ActionRegistry::new();
733            registry.register_decoder(SEEN_TYPE, decode_seen);
734            let action = registry
735                .decode(&EncodedAction::encode(SEEN_TYPE, &Seen(7)).unwrap())
736                .unwrap();
737            let mut doc = AutoCommit::new();
738            action.apply(&mut doc).unwrap();
739            assert_eq!(
740                doc.get(&ROOT, "seen")
741                    .unwrap()
742                    .map(|(value, _)| value.as_i64()),
743                Some(Some(7))
744            );
745            let refused = registry.decode(&EncodedAction {
746                type_id: SEEN_TYPE.to_owned(),
747                payload: b"not a number".to_vec(),
748            });
749            assert!(
750                matches!(&refused, Err(ActionError::Decode { type_id, .. }) if type_id == SEEN_TYPE),
751                "{refused:?}"
752            );
753        }
754
755        phase declared_kinds_travel_in_the_change_and_every_change_names_what_it_did;
756        // The executor writes an action's declared kind into its change, with or
757        // without a caller's context, and replay reproduces the same change.
758        {
759            let (mut a, mut b) = two_replicas();
760            let env = apply_local(
761                &mut a,
762                &Seen(3),
763                EncodedAction::encode(SEEN_TYPE, &Seen(3)).unwrap(),
764            )
765            .unwrap();
766            assert!(
767                env.context
768                    .as_ref()
769                    .is_some_and(ActionContext::is_housekeeping)
770            );
771            assert!(last_context(&mut a).is_some_and(|context| context.is_housekeeping()));
772            replay(&mut b, &env, &registry()).unwrap();
773            assert_eq!(a.get_heads(), b.get_heads(), "replay makes the same change");
774
775            let labelled = ActionContext::for_resource("c:1", "chat.channel", "general");
776            apply_local_with_context(
777                &mut a,
778                &Seen(4),
779                EncodedAction::encode(SEEN_TYPE, &Seen(4)).unwrap(),
780                None,
781                labelled,
782            )
783            .unwrap();
784            let context = last_context(&mut a).unwrap();
785            assert!(context.is_housekeeping());
786            assert_eq!(
787                context.resource.as_ref().map(|r| r.label.as_str()),
788                Some("general"),
789                "the caller's context is kept"
790            );
791
792            let put = Counter::Put {
793                key: "score".into(),
794                value: 1,
795            };
796            let env = apply_local(
797                &mut a,
798                &put,
799                EncodedAction::encode(COUNTER_TYPE, &put).unwrap(),
800            )
801            .unwrap();
802            let entry = env
803                .context
804                .expect("every committed action records an entry");
805            assert!(entry.change.is_step());
806            assert_eq!(
807                entry.what,
808                Some(Did::verb(
809                    ActionKey::new("test", COUNTER_TYPE, "put"),
810                    [
811                        ("key".to_string(), Scalar::from("score")),
812                        ("value".to_string(), Scalar::from(1)),
813                    ],
814                )),
815                "an action that describes nothing is named by its encoded verb"
816            );
817            assert_eq!(last_context(&mut a), Some(entry));
818
819            // A context may say a content action is nobody's step this time; an
820            // action's own declaration is never overridden by a context.
821            let seeded = Counter::Put {
822                key: "score".into(),
823                value: 2,
824            };
825            let env = apply_local_with_context(
826                &mut a,
827                &seeded,
828                EncodedAction::encode(COUNTER_TYPE, &seeded).unwrap(),
829                None,
830                ActionContext::default().with_change(ChangeKind::External),
831            )
832            .unwrap();
833            assert_eq!(last_context(&mut a).unwrap().change, ChangeKind::External);
834            assert!(!env.context.unwrap().change.is_step());
835            apply_local_with_context(
836                &mut a,
837                &Seen(5),
838                EncodedAction::encode(SEEN_TYPE, &Seen(5)).unwrap(),
839                None,
840                ActionContext::default().with_change(ChangeKind::External),
841            )
842            .unwrap();
843            assert!(last_context(&mut a).unwrap().is_housekeeping());
844        }
845
846        phase the_executor_keeps_the_admitted_invocation_and_replays_the_identical_change;
847        {
848            let (mut origin, mut peer) = two_replicas();
849            let action = Counter::Put {
850                key: "score".into(),
851                value: 42,
852            };
853            let invocation = InvocationId::new();
854            let context = ActionContext {
855                source_invocation: Some(invocation),
856                ..Default::default()
857            };
858            let envelope = apply_local_with_context(
859                &mut origin,
860                &action,
861                EncodedAction::encode(COUNTER_TYPE, &action).unwrap(),
862                Some(b"actual-person-device-writer"),
863                context,
864            )
865            .unwrap();
866            let committed = last_context(&mut origin).unwrap();
867            assert_eq!(committed.source_invocation, Some(invocation));
868            assert_eq!(envelope.context, Some(committed));
869            replay(&mut peer, &envelope, &registry()).unwrap();
870            assert_eq!(origin.get_heads(), peer.get_heads());
871            assert_eq!(
872                origin.get_changes(&envelope.base_change_hashes())[0].raw_bytes(),
873                peer.get_changes(&envelope.base_change_hashes())[0].raw_bytes(),
874            );
875        }
876
877        phase a_callers_entry_replays_to_the_identical_change;
878        {
879            let (mut origin, mut peer) = two_replicas();
880            let action = Counter::Put {
881                key: "score".into(),
882                value: 42,
883            };
884            let context = ActionContext::for_resource("score", "counter", "Score");
885            let envelope = ActionEnvelope {
886                id: ActionId::new(),
887                action: EncodedAction::encode(COUNTER_TYPE, &action).unwrap(),
888                base_heads: origin.get_heads().iter().map(|hash| hash.0).collect(),
889                timestamp: 17,
890                locus: ExecutionLocus::ClientLocal,
891                actor: Some(b"legacy-person-device-writer".to_vec()),
892                context: Some(context.clone()),
893            };
894            let old_message = context.change_message().unwrap();
895            let wire = serde_json::to_vec(&envelope).unwrap();
896            let decoded: ActionEnvelope = serde_json::from_slice(&wire).unwrap();
897            assert_eq!(serde_json::to_vec(&decoded).unwrap(), wire);
898            origin.set_actor(envelope.actor());
899            action.apply(&mut origin).unwrap();
900            origin.commit_with(
901                automerge::transaction::CommitOptions::default()
902                    .with_time(envelope.timestamp)
903                    .with_message(old_message.clone()),
904            );
905            replay(&mut peer, &decoded, &registry()).unwrap();
906            assert_eq!(last_message(&mut peer), Some(old_message));
907            assert_eq!(origin.get_heads(), peer.get_heads());
908            assert_eq!(
909                origin.get_changes(&envelope.base_change_hashes())[0].raw_bytes(),
910                peer.get_changes(&envelope.base_change_hashes())[0].raw_bytes(),
911            );
912        }
913
914        phase envelopes_replay_deterministically_on_peers;
915        // An action replays to an identical doc on a peer, concurrent envelopes replay from their
916        // recorded base, and a replayed change dedupes against a native Automerge merge.
917        // Invocations each phase below in order; every phase builds its own fixture.
918        {
919            action_replays_to_identical_doc_on_peer();
920            concurrent_envelopes_replay_from_their_recorded_base();
921            replayed_change_dedupes_against_native_automerge_merge();
922        }
923
924        phase dispatch_routes_by_placement_and_the_registry_knows_its_types;
925        // Client-local dispatch applies and replicates; server-preferred routes to the host without a
926        // local apply and refuses without a host; the registry rejects unknown types and flattens nested
927        // resources.
928        // Invocations each phase below in order; every phase builds its own fixture.
929        {
930            client_local_dispatch_applies_and_replicates();
931            server_preferred_routes_to_host_without_local_apply();
932            server_preferred_refuses_without_host();
933            registry_rejects_unknown_type();
934            flatten_walks_nested_resources();
935        }
936    }
937
938    /// `ClientLocal` dispatch applies locally and replicates exactly one
939    /// envelope through the transport.
940    fn client_local_dispatch_applies_and_replicates() {
941        let (mut a, _) = two_replicas();
942        let action = Counter::Put {
943            key: "likes".into(),
944            value: 1,
945        };
946        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
947        let mut tx = LocalTransport::new();
948        let d = dispatch(&mut a, &action, encoded, &mut tx).unwrap();
949        assert!(matches!(d, Dispatched::AppliedLocal(_)));
950        assert!(d.mutated_local());
951        assert_eq!(tx.replicated.len(), 1, "replicated exactly once");
952        assert_eq!(a.get(&ROOT, "likes").unwrap().unwrap().0.as_i64(), Some(1));
953    }
954
955    /// A transport that speaks for a reachable host, proving the
956    /// `ServerPreferred` plumbing is real: when a host accepts, the action is
957    /// NOT applied to the local doc (the host will execute + broadcast).
958    struct HostTransport {
959        submitted: Vec<ActionEnvelope>,
960    }
961    impl ActionTransport for HostTransport {
962        fn replicate(&mut self, _env: &ActionEnvelope) {}
963        fn submit_to_host(&mut self, env: &ActionEnvelope) -> HostDecision {
964            self.submitted.push(env.clone());
965            HostDecision::AcceptedByHost
966        }
967    }
968
969    fn server_preferred_routes_to_host_without_local_apply() {
970        let (mut a, _) = two_replicas();
971        let before = a.get_heads();
972        let action = Counter::Append {
973            key: "queue".into(),
974            value: "vidX".into(),
975        };
976        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
977        let mut tx = HostTransport { submitted: vec![] };
978        let d = dispatch(&mut a, &action, encoded, &mut tx).unwrap();
979        assert!(matches!(d, Dispatched::SubmittedToHost(_)));
980        assert!(
981            !d.mutated_local(),
982            "host-accepted action is not applied locally"
983        );
984        assert_eq!(tx.submitted.len(), 1, "submitted to the host once");
985        assert_eq!(a.get_heads(), before, "local doc untouched");
986        assert_eq!(d.envelope().locus, ExecutionLocus::ServerPreferred);
987    }
988
989    fn server_preferred_refuses_without_host() {
990        let (mut a, _) = two_replicas();
991        let before = a.get_heads();
992        let action = Counter::Append {
993            key: "queue".into(),
994            value: "vidY".into(),
995        };
996        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
997        let mut tx = LocalTransport::new();
998        let error = dispatch(&mut a, &action, encoded, &mut tx).unwrap_err();
999        assert!(matches!(error, ActionError::Refused(_)));
1000        assert_eq!(
1001            a.get_heads(),
1002            before,
1003            "an unavailable host grants no authority"
1004        );
1005        assert!(tx.replicated.is_empty());
1006        assert!(a.get(&ROOT, "queue").unwrap().is_none());
1007    }
1008
1009    fn registry_rejects_unknown_type() {
1010        let reg = registry();
1011        let bogus = EncodedAction {
1012            type_id: "nope".into(),
1013            payload: b"{}".to_vec(),
1014        };
1015        let mut doc = AutoCommit::new();
1016        let env = ActionEnvelope {
1017            id: ActionId::new(),
1018            action: bogus,
1019            base_heads: vec![],
1020            timestamp: 0,
1021            locus: ExecutionLocus::ClientLocal,
1022            actor: None,
1023            context: None,
1024        };
1025        assert!(matches!(
1026            replay(&mut doc, &env, &reg),
1027            Err(ActionError::UnknownType(_))
1028        ));
1029    }
1030
1031    /// Resource forests flatten depth-first, parents before children, with
1032    /// composite keys.
1033    fn flatten_walks_nested_resources() {
1034        let put = Counter::Put {
1035            key: "k".into(),
1036            value: 1,
1037        };
1038        let video = ResourceSpec::new("tube.video:v1", "tube.video", "A Video")
1039            .with_action(ActionSpec::immediate("like", "Like", COUNTER_TYPE, &put).unwrap())
1040            .with_child(
1041                ResourceSpec::new("tube.comment:v1:0", "tube.comment", "nice!").with_action(
1042                    ActionSpec::immediate("like", "Like comment", COUNTER_TYPE, &put).unwrap(),
1043                ),
1044            );
1045        let flat = flatten(std::slice::from_ref(&video));
1046        assert_eq!(flat.len(), 2);
1047        assert_eq!(flat[0].key, format!("tube.video:v1{KEY_SEP}like"));
1048        assert_eq!(flat[0].resource_kind, "tube.video");
1049        assert_eq!(flat[1].key, format!("tube.comment:v1:0{KEY_SEP}like"));
1050        assert_eq!(flat[1].resource_kind, "tube.comment");
1051    }
1052}