Skip to main content

tilo_actions/
context.rs

1//! The history entry an action carries into its committed change.
2//!
3//! The action payload says how to reproduce a mutation. [`ActionContext`]
4//! is the entry history keeps of it: who acted and for whom, in which task or
5//! run, on which resource and item (with the item's label at the time), what
6//! was done ([`Did`]), and what kind of change it was. It contains no
7//! sentence: readers render one in their own language, and agents, scripts
8//! and logs read the data. The caller supplies who and why (invoker,
9//! purpose, group); the executor fills in what, from the action itself.
10
11use serde::{Deserialize, Serialize};
12
13use crate::InvocationId;
14use crate::entry::{ActionItem, Described, Did, PathStep};
15use crate::key::ActionKind;
16use tilo_action_policy::{Acting, Actor};
17
18/// Prefix used when an entry is embedded in an Automerge change message,
19/// followed by the entry in its compact form ([`crate::compact`]).
20/// Ordinary application-authored commit messages remain untouched.
21pub const CHANGE_MESSAGE_PREFIX: &str = "tilo.entry/3 ";
22
23/// Prefix of a change message that continues its writer's last whole entry
24/// (the next keystroke of a word, or the first of the next word):
25/// `tilo.cont/3 <gesture> <claim> <kept> <tail> <middle>`. It is that entry
26/// again but for its gesture and the action's payload, so it carries only
27/// the gesture (its [`crate::compact`] form), what the change claims to be
28/// ([`ContinuedAction`]) and how its payload differs from that entry's: that
29/// payload's first `kept` and last `tail` bytes around `middle`. Readers
30/// fold it into that entry ([`ActionContext::continued`]).
31pub const CONTINUATION_PREFIX: &str = "tilo.cont/3 ";
32
33#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(remote = "Self", default)]
35pub struct ActionContext {
36    /// Publishing app, when the host knows it.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub app: Option<ActionApp>,
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub resource: Option<ActionResource>,
41    /// The item inside the resource the action addressed, with its label at
42    /// the time.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub item: Option<ActionItem>,
45    /// What the action did, described by the action before it applied.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub what: Option<Did>,
48    /// What the action is able to do (read, change the document, reach
49    /// outside it). Written by the executor from the action.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub kind: Option<ActionKind>,
52    /// What the actor says they are trying to accomplish. Never inferred.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub purpose: Option<String>,
55    /// Stable cross-action work unit: issue, agent run, task, or session.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub group: Option<WorkGroup>,
58    /// Browseable dimensions that do not fit the resource hierarchy.
59    #[serde(skip_serializing_if = "Vec::is_empty")]
60    pub facets: Vec<ActionFacet>,
61    /// Who invoked the action, for whom, and whose view it resolves
62    /// against. `None` is the local person acting in this window.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub invoker: Option<ActionInvoker>,
65    /// The invocation admitted by the action API, when this change came
66    /// through one. This is correlation, not authority: executors replace
67    /// this field from their retained admission before applying an action.
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub source_invocation: Option<InvocationId>,
70    /// The invocation as its caller signed it, when a host ran the action for
71    /// someone who asked it under their own key: the host signs the change as
72    /// the one who ran it, and this says who asked, for what, with what
73    /// arguments. A peer reading the change checks it against the person's
74    /// root ([`crate::remote::SignedCall`]); the host never makes one up.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub signed: Option<Box<crate::remote::SignedCall>>,
77    /// The bot run that made this change, when one did.
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub caused_by: Option<Cause>,
80    /// The action this change ran, encoded as the executor dispatched it:
81    /// what a device that receives the change replays to verify it, and
82    /// what redo runs again. The executor records it on every change it
83    /// commits whose action the change documents whole
84    /// ([`WHOLE_ACTION_BUDGET`]); a larger one records its large parts as
85    /// content ([`crate::content`]) and names them, and one too large even
86    /// then ([`HISTORY_BUDGET`]) is refused. It describes the change; it
87    /// carries no caller authority.
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub action: Option<crate::EncodedAction>,
90    /// The inverse of [`action`](Self::action) at its before state, as the
91    /// canonical executor computed it, for an action whose undo is an action
92    /// (it queued an outside consequence). Absent for one undone by
93    /// reverting the change. Carries no caller authority.
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub compensation: Option<crate::EncodedAction>,
96    /// The gesture this change belongs to: an id every change of one
97    /// actor's gesture shares (the keystrokes of a word, the values one drag
98    /// of a slider passes through), which undo takes back as one step.
99    /// Absent for a change that is a step of its own.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub gesture: Option<crate::ActionId>,
102    /// What the change is to the people sharing the document, declared by
103    /// the action ([`crate::Action::change_kind`]) or, for a change that is
104    /// nobody's step whatever it does (what a brand-new record starts with),
105    /// by the context it is applied with.
106    #[serde(skip_serializing_if = "ChangeKind::is_content")]
107    pub change: ChangeKind,
108    /// The facts an ask shows, as the calling runtime evaluated them, when
109    /// caller and callee are one app: values only that app can read (a
110    /// draft's subject). Taken only from that app's own call; any other
111    /// caller's are ignored and admission reads them from the arguments.
112    #[serde(default, skip_serializing_if = "Vec::is_empty")]
113    pub shows: Vec<crate::remote::asked::Fact>,
114    /// The person's approve of the asked record this invocation waited in, when it is that
115    /// call sent again ([`crate::remote::InvokeRequest::approval`]): what an app's handler
116    /// reads to run what it refused for want of their yes. Set only by the host that
117    /// admitted the invocation, from the call itself, never from a caller's context.
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub approval: Option<crate::remote::asked::Approval>,
120    /// The person made this invocation themselves, with a press the compositor attested to the
121    /// system's own surfaces (a palette's row, a menu's item, a shortcut's key): what an app's
122    /// handler runs as their own act, so what its code calls of its own does not ask them again.
123    /// Set only by the host that admitted the invocation, from the attestation it holds, never
124    /// from a caller's context.
125    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
126    pub pressed: bool,
127}
128
129read_through_json_value!(ActionContext);
130
131/// The gesture a change records for the undo step `gesture` its caller
132/// named, under the caller's `group`: one id for every change of that step,
133/// and never one the caller chose.
134fn ambient_gesture(gesture: crate::ActionId, group: Option<&WorkGroup>) -> crate::ActionId {
135    recorded_gesture(
136        gesture,
137        group.map(|group| (group.kind.as_str(), group.id.as_str())),
138    )
139}
140
141/// The gesture history records for the undo step `gesture` a caller named,
142/// under the run (its kind and id, as history lists them) the change was
143/// stamped with: how the caller finds its own step's changes in a record's
144/// history, without it ever naming a gesture someone else's change records.
145#[must_use]
146pub fn recorded_gesture(gesture: crate::ActionId, run: Option<(&str, &str)>) -> crate::ActionId {
147    let mut hasher = blake3::Hasher::new_derive_key("tilo ambient gesture v1");
148    hasher.update(gesture.0.as_bytes());
149    if let Some((kind, id)) = run {
150        for part in [kind, id] {
151            hasher.update(&u64::try_from(part.len()).unwrap_or(u64::MAX).to_le_bytes());
152            hasher.update(part.as_bytes());
153        }
154    }
155    let id = *hasher
156        .finalize()
157        .as_bytes()
158        .first_chunk::<16>()
159        .unwrap_or(&[0; 16]);
160    crate::ActionId(uuid::Builder::from_custom_bytes(id).into_uuid())
161}
162
163// Written out rather than derived: a derived clone is inlined into every
164// crate that clones a context.
165impl Clone for ActionContext {
166    fn clone(&self) -> Self {
167        Self {
168            app: self.app.clone(),
169            resource: self.resource.clone(),
170            item: self.item.clone(),
171            what: self.what.clone(),
172            kind: self.kind,
173            purpose: self.purpose.clone(),
174            group: self.group.clone(),
175            facets: self.facets.clone(),
176            invoker: self.invoker.clone(),
177            source_invocation: self.source_invocation,
178            signed: self.signed.clone(),
179            caused_by: self.caused_by.clone(),
180            action: self.action.clone(),
181            compensation: self.compensation.clone(),
182            gesture: self.gesture,
183            change: self.change,
184            shows: self.shows.clone(),
185            approval: self.approval.clone(),
186            pressed: self.pressed,
187        }
188    }
189}
190
191/// The most an entry's [`compensation`](ActionContext::compensation) may
192/// take, encoded: an action whose inverse is larger is refused.
193pub const COMPENSATION_BUDGET: usize = 128 * 1024;
194
195/// The most a change documents whole of the action it records, its payload inline: a larger
196/// action keeps its long parts as content ([`crate::content`]) and names them instead. Every
197/// device a change reaches reads that entry to verify the change, so what one change carries
198/// of an action stays small: 256 KiB of payload is a few hundred items of an import, or a long
199/// note's body.
200pub const WHOLE_ACTION_BUDGET: usize = 256 * 1024;
201
202/// The most an entry's [`action`](ActionContext::action) may take, its large parts kept as
203/// content included: a larger action is refused.
204pub const HISTORY_BUDGET: usize = 1024 * 1024;
205
206/// What a change is to the people sharing a document. Every kind is durable,
207/// shared and kept in the document's own history; they differ in whether a
208/// person takes the change back and whether a feed of what people did to the
209/// workspace shows it.
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
211pub enum ChangeKind {
212    /// Something a person did to the content: an undo step of its author's,
213    /// shown in workspace activity.
214    #[default]
215    Content,
216    /// Housekeeping about the content (a read marker, a reading position):
217    /// no undo step, and workspace activity leaves it out.
218    Housekeeping,
219    /// Content that came from outside rather than from anyone's edit:
220    /// articles a refresh fetched, a process's output, what a brand-new
221    /// record starts with from state that already existed. Members
222    /// see it like any content, but it is nobody's undo step, and workspace
223    /// activity leaves it out.
224    External,
225}
226
227impl ChangeKind {
228    pub const fn is_content(&self) -> bool {
229        matches!(self, Self::Content)
230    }
231
232    /// Whether a change of this kind is an undo step of its author's. Only
233    /// a person's own edits of the content are.
234    pub const fn is_step(&self) -> bool {
235        self.is_content()
236    }
237}
238
239impl ActionContext {
240    /// Fill missing provenance from a task/session context while preserving
241    /// every value supplied by the concrete action/resource.
242    #[must_use]
243    pub fn enriched_by(mut self, ambient: &Self) -> Self {
244        if self.app.is_none() {
245            self.app.clone_from(&ambient.app);
246        }
247        if self.resource.is_none() {
248            self.resource.clone_from(&ambient.resource);
249        }
250        if self.item.is_none() {
251            self.item.clone_from(&ambient.item);
252        }
253        if self.purpose.is_none() {
254            self.purpose.clone_from(&ambient.purpose);
255        }
256        if self.group.is_none() {
257            self.group.clone_from(&ambient.group);
258        }
259        if self.invoker.is_none() {
260            self.invoker.clone_from(&ambient.invoker);
261        }
262        if self.source_invocation.is_none() {
263            self.source_invocation = ambient.source_invocation;
264        }
265        if self.signed.is_none() {
266            self.signed.clone_from(&ambient.signed);
267        }
268        if self.caused_by.is_none() {
269            self.caused_by.clone_from(&ambient.caused_by);
270        }
271        // The caller's undo step: what an API joins its calls under (one
272        // task step), so they are taken back as one. Rebound under the
273        // caller's group, never recorded as the caller wrote it: a caller
274        // cannot name a gesture of someone else's and have its change
275        // continue theirs.
276        if self.gesture.is_none() {
277            self.gesture = ambient
278                .gesture
279                .map(|gesture| ambient_gesture(gesture, ambient.group.as_ref()));
280        }
281        for facet in &ambient.facets {
282            if !self.facets.contains(facet) {
283                self.facets.push(facet.clone());
284            }
285        }
286        self
287    }
288
289    /// Pin the invocation retained by the admitted dispatch boundary.
290    ///
291    /// This replaces rather than fills an ambient value. Only the executor
292    /// that owns admission should call it.
293    #[must_use]
294    pub fn with_source_invocation(mut self, invocation: Option<InvocationId>) -> Self {
295        self.source_invocation = invocation;
296        self
297    }
298
299    /// Record the bot run this change continues.
300    #[must_use]
301    pub fn with_caused_by(mut self, cause: Option<Cause>) -> Self {
302        self.caused_by = cause;
303        self
304    }
305
306    pub fn for_resource(
307        id: impl Into<String>,
308        kind: impl Into<String>,
309        label: impl Into<String>,
310    ) -> Self {
311        Self::of_resource(ActionResource {
312            id: id.into(),
313            kind: kind.into(),
314            label: label.into(),
315        })
316    }
317
318    /// [`Self::for_resource`] once its strings are made: not generic, so the
319    /// rest of the context is built by code compiled once rather than in
320    /// every crate that names a resource with `&str`s.
321    #[inline(never)]
322    fn of_resource(resource: ActionResource) -> Self {
323        Self {
324            resource: Some(resource),
325            ..Self::default()
326        }
327    }
328
329    /// The entry of an action published by one app.
330    pub fn for_app(id: impl Into<String>, label: impl Into<String>) -> Self {
331        Self::default().with_app(id, label)
332    }
333
334    #[must_use]
335    pub fn with_app(mut self, id: impl Into<String>, label: impl Into<String>) -> Self {
336        self.app = Some(ActionApp {
337            id: id.into(),
338            label: label.into(),
339        });
340        self
341    }
342
343    #[must_use]
344    pub fn with_purpose(mut self, purpose: impl Into<String>) -> Self {
345        let purpose = purpose.into();
346        self.purpose = nonempty(&purpose);
347        self
348    }
349
350    #[must_use]
351    pub fn with_group(
352        mut self,
353        id: impl Into<String>,
354        label: impl Into<String>,
355        kind: impl Into<String>,
356    ) -> Self {
357        self.group = Some(WorkGroup {
358            id: id.into(),
359            label: Some(label.into()),
360            kind: kind.into(),
361            declared_id: None,
362            session: None,
363        });
364        self
365    }
366
367    #[must_use]
368    pub fn with_invoker(mut self, invoker: ActionInvoker) -> Self {
369        self.invoker = Some(invoker);
370        self
371    }
372
373    /// Host-side rewrite of a caller-supplied context: the invoker becomes
374    /// exactly the authenticated `actor` and the host-derived `presence`,
375    /// discarding whatever invoker the caller put in the envelope.
376    #[must_use]
377    pub fn with_host_actor(mut self, actor: &Acting, presence: Option<PresenceId>) -> Self {
378        let mut invoker = ActionInvoker::admitted(actor);
379        invoker.presence = presence;
380        self.invoker = Some(invoker);
381        self
382    }
383
384    #[must_use]
385    pub fn with_facet(mut self, facet: ActionFacet) -> Self {
386        self.facets.push(facet);
387        self
388    }
389
390    /// Join the undo step open on this thread
391    /// ([`crate::executor::open_step`]) unless the entry names one.
392    #[must_use]
393    pub fn in_step(mut self) -> Self {
394        if self.gesture.is_none() {
395            self.gesture = crate::executor::current_step();
396        }
397        self
398    }
399
400    /// Continue the gesture `gesture` (see [`Self::gesture`]).
401    #[must_use]
402    pub fn in_gesture(mut self, gesture: Option<crate::ActionId>) -> Self {
403        self.gesture = gesture;
404        self
405    }
406
407    #[must_use]
408    pub fn with_change(mut self, change: ChangeKind) -> Self {
409        self.change = change;
410        self
411    }
412
413    /// Record what the action did and the item it addressed.
414    #[must_use]
415    pub fn with_described(mut self, described: Described) -> Self {
416        self.what = Some(described.what);
417        if described.item.is_some() {
418            self.item = described.item;
419        }
420        self
421    }
422
423    /// What the action did and to which item, as one value.
424    pub fn described(&self) -> Option<Described> {
425        Some(Described {
426            what: self.what.clone()?,
427            item: self.item.clone(),
428        })
429    }
430
431    /// Whether the change this context describes is housekeeping, not content.
432    pub fn is_housekeeping(&self) -> bool {
433        self.change == ChangeKind::Housekeeping
434    }
435
436    /// Whether workspace activity shows this change: content, not
437    /// housekeeping and not what came from outside.
438    pub fn is_activity(&self) -> bool {
439        self.change.is_content()
440    }
441
442    /// Who invoked the action, when the context names anyone.
443    pub fn acting(&self) -> Option<&Acting> {
444        self.invoker.as_ref().map(|invoker| &invoker.acting)
445    }
446
447    /// The message of a change `acting` made to a record directly, naming no finer action than
448    /// an edit of the whole record: what a device commits of its own edit, naming who made it as
449    /// every change a device signs must. Every receiver decides it as `acting`'s, never as its
450    /// signer's alone.
451    #[must_use]
452    pub fn whole_edit_by(acting: &Acting) -> String {
453        Self::default()
454            .with_invoker(ActionInvoker::admitted(acting))
455            .change_message()
456            .unwrap_or_default()
457    }
458
459    /// Encode into the Automerge change message. Returning `None` keeps an
460    /// empty/default context from displacing an app's ordinary history path.
461    pub fn change_message(&self) -> Option<String> {
462        if self == &Self::default() {
463            return None;
464        }
465        serde_json::to_value(wire::Entry::of(self))
466            .ok()
467            .map(|entry| format!("{CHANGE_MESSAGE_PREFIX}{}", crate::compact::encode(&entry)))
468    }
469
470    /// Read an entry from a change message, through the one reader of change labels
471    /// ([`Stamp::read`](crate::stamp::Stamp::read)). Unknown and malformed messages are ordinary
472    /// app commits, never an error that hides their history. A continuation is no entry on its
473    /// own: read it with [`continued`](Self::continued) from its writer's last whole entry. A
474    /// store's change names its action in a stamp: its context, and what the stamp itself says
475    /// of who invoked it and for which step.
476    pub fn from_change_message(message: &str) -> Option<Self> {
477        Self::of_label(crate::stamp::Stamp::read(message)?)
478    }
479
480    /// Read only what an entry says about who made its change, in which run
481    /// and step, and what kind of change it is (its group, invoker, invocation,
482    /// gesture, kind and change kind; everything else left default): what an index
483    /// over a long history keeps of every change, read without decoding
484    /// what the change did. `None` where [`from_change_message`](Self::from_change_message)
485    /// reads no entry.
486    pub fn head_of_change_message(message: &str) -> Option<Self> {
487        Self::of_label(crate::stamp::Stamp::read_head(message)?)
488    }
489
490    /// The context a label read as an entry or a stamp names; a continuation and a framework
491    /// change name none of their own.
492    fn of_label((label, stamp): (crate::stamp::Label, crate::stamp::Stamp)) -> Option<Self> {
493        matches!(
494            label,
495            crate::stamp::Label::Entry | crate::stamp::Label::Stamp
496        )
497        .then(|| stamp.action_context())
498    }
499
500    /// This entry, written as the continuation of `first` (its writer's
501    /// last whole entry): when it is in a gesture and differs from `first`
502    /// only in its gesture and its action's payload. `None` when it has to
503    /// be written whole.
504    #[must_use]
505    pub fn continuation_of(&self, first: &Self) -> Option<String> {
506        let gesture = self.gesture?;
507        let action = self.action.as_ref()?;
508        let earlier = first.action.as_ref()?;
509        let bare = |entry: &Self| Self {
510            action: None,
511            gesture: None,
512            ..entry.clone()
513        };
514        if self.compensation.is_some()
515            || first.compensation.is_some()
516            || action.type_id != earlier.type_id
517            || bare(self) != bare(first)
518        {
519            return None;
520        }
521        let claim = ContinuedAction::token(self)?;
522        let now = std::str::from_utf8(&action.payload).ok()?;
523        let then = std::str::from_utf8(&earlier.payload).ok()?;
524        let kept = now
525            .char_indices()
526            .zip(then.chars())
527            .find(|((_, now), then)| now != then)
528            .map_or_else(|| now.len().min(then.len()), |((at, _), _)| at);
529        let (now_rest, then_rest) = (now.get(kept..)?, then.get(kept..)?);
530        let tail: usize = now_rest
531            .chars()
532            .rev()
533            .zip(then_rest.chars().rev())
534            .take_while(|(now, then)| now == then)
535            .map(|(now, _)| now.len_utf8())
536            .sum();
537        let middle = now_rest.get(..now_rest.len().checked_sub(tail)?)?;
538        Some(format!(
539            "{CONTINUATION_PREFIX}{} {claim} {kept} {tail} {middle}",
540            gesture_token(gesture)
541        ))
542    }
543
544    /// The gesture a continuation `message` continues.
545    #[must_use]
546    pub fn continued_gesture(message: &str) -> Option<crate::ActionId> {
547        let rest = message.strip_prefix(CONTINUATION_PREFIX)?;
548        gesture_of(rest.split(' ').next()?)
549    }
550
551    /// The entry a continuation `message` stands for, from its writer's last
552    /// whole entry `first`.
553    #[must_use]
554    pub fn continued(message: &str, first: &Self) -> Option<Self> {
555        let rest = message.strip_prefix(CONTINUATION_PREFIX)?;
556        let mut parts = rest.splitn(3, ' ');
557        let gesture = gesture_of(parts.next()?)?;
558        let _claim = parts.next()?;
559        let mut diff = parts.next()?.splitn(3, ' ');
560        let kept = diff.next()?.parse::<usize>().ok()?;
561        let tail = diff.next()?.parse::<usize>().ok()?;
562        let earlier = first.action.as_ref()?;
563        let then = std::str::from_utf8(&earlier.payload).ok()?;
564        let payload = [
565            then.get(..kept)?,
566            diff.next()?,
567            then.get(then.len().checked_sub(tail)?..)?,
568        ]
569        .concat();
570        Some(Self {
571            action: Some(crate::EncodedAction {
572                type_id: earlier.type_id.clone(),
573                payload: payload.into_bytes(),
574            }),
575            gesture: Some(gesture),
576            ..first.clone()
577        })
578    }
579}
580
581/// What a continuation says its change is, in the terms a change's claim is
582/// written in, as the entry it continues says it: an edit of a resource kind
583/// at a path (the whole resource for an empty one), or one of its verbs on an
584/// item. A continuation writes it as one token: `e:<kind>:<step>/…` or
585/// `v:<app>/<kind>/<action>[:<item>]`, a step being `f<field>`, `i<id>`,
586/// `k<key>` or `c<row>:<column>`.
587#[derive(Clone, Debug, PartialEq, Eq)]
588pub enum ContinuedAction {
589    Edit {
590        kind: String,
591        path: Vec<PathStep>,
592    },
593    Verb {
594        action: crate::ActionKey,
595        item: Option<String>,
596    },
597}
598
599impl ContinuedAction {
600    /// The claim a continuation of `entry` writes; `None` for one whose names
601    /// hold a byte the token reserves, which writes the entry whole instead.
602    fn token(entry: &ActionContext) -> Option<String> {
603        let edit = |path: &[PathStep]| Self::Edit {
604            kind: entry
605                .resource
606                .as_ref()
607                .map_or_else(String::new, |resource| resource.kind.clone()),
608            path: path.to_vec(),
609        };
610        let action = match &entry.what {
611            Some(Did::Verb(verb)) => Self::Verb {
612                action: verb.action.clone(),
613                item: entry.item.as_ref().map(|item| item.id.clone()),
614            },
615            Some(Did::Edit(changed)) => edit(&changed.path),
616            None => edit(&[]),
617            Some(_) => return None,
618        };
619        let mut token = action.write()?;
620        // Who made the gesture, when not the signing person: what every
621        // receiver decides each of its changes as. A person's own keystrokes
622        // carry nothing more.
623        if let Some(invoker) = &entry.invoker {
624            let tree = serde_json::to_value(&invoker.acting).ok()?;
625            token.push(INVOKER_MARK);
626            token.push_str(&hex::encode(crate::compact::encode(&tree)));
627        }
628        Some(token)
629    }
630
631    /// Who made the gesture a continuation `message` continues, as its token
632    /// names them: `None` for a person's own keystrokes, or a token that does
633    /// not read.
634    #[must_use]
635    pub fn invoker_of_message(message: &str) -> Option<crate::Acting> {
636        let rest = message.strip_prefix(CONTINUATION_PREFIX)?;
637        let (_, invoker) = rest.split(' ').nth(1)?.split_once(INVOKER_MARK)?;
638        let text = crate::compact::decode(std::str::from_utf8(&hex::decode(invoker).ok()?).ok()?)?;
639        serde_json::from_str(&text).ok()
640    }
641
642    /// The claim a continuation `message` writes.
643    #[must_use]
644    pub fn of_message(message: &str) -> Option<Self> {
645        let rest = message.strip_prefix(CONTINUATION_PREFIX)?;
646        let token = rest.split(' ').nth(1)?;
647        Self::parse(
648            token
649                .split_once(INVOKER_MARK)
650                .map_or(token, |(claim, _)| claim),
651        )
652    }
653
654    /// The token this claim writes, read back by [`Self::parse`].
655    fn write(&self) -> Option<String> {
656        /// A name as the token carries it; the separators end it.
657        fn name(text: &str) -> Option<&str> {
658            (!text.contains([' ', ':', '/', INVOKER_MARK])).then_some(text)
659        }
660        fn write_step(token: &mut String, at: usize, step: &PathStep) -> Option<()> {
661            if at > 0 {
662                token.push('/');
663            }
664            let (tag, text) = match step {
665                PathStep::Field(field) => ('f', name(field)?),
666                PathStep::Item(id) => ('i', name(id)?),
667                PathStep::Key(key) => ('k', name(key)?),
668                PathStep::Cell(row, column) => {
669                    token.push('c');
670                    token.push_str(name(row)?);
671                    token.push(':');
672                    token.push_str(name(column)?);
673                    return Some(());
674                }
675            };
676            token.push(tag);
677            token.push_str(text);
678            Some(())
679        }
680        let mut token = String::new();
681        match self {
682            Self::Edit { kind, path } => {
683                token.push_str("e:");
684                token.push_str(name(kind)?);
685                token.push(':');
686                for (at, step) in path.iter().enumerate() {
687                    write_step(&mut token, at, step)?;
688                }
689            }
690            Self::Verb { action, item } => {
691                token.push_str("v:");
692                for part in [&action.app, &action.kind, &action.action] {
693                    token.push_str(name(part)?);
694                    token.push('/');
695                }
696                token.pop();
697                if let Some(item) = item {
698                    token.push(':');
699                    token.push_str(name(item)?);
700                }
701            }
702        }
703        Some(token)
704    }
705
706    /// The claim a continuation's token writes.
707    fn parse(token: &str) -> Option<Self> {
708        fn read_step(step: &str) -> Option<PathStep> {
709            let (tag, rest) = step.split_at_checked(1)?;
710            Some(match tag {
711                "f" => PathStep::Field(rest.to_owned()),
712                "i" => PathStep::Item(rest.to_owned()),
713                "k" => PathStep::Key(rest.to_owned()),
714                "c" => {
715                    let (row, column) = rest.split_once(':')?;
716                    PathStep::Cell(row.to_owned(), column.to_owned())
717                }
718                _ => return None,
719            })
720        }
721        let (tag, rest) = token.split_once(':')?;
722        Some(match tag {
723            "e" => {
724                let (kind, path) = rest.split_once(':')?;
725                let path = if path.is_empty() {
726                    Vec::new()
727                } else {
728                    path.split('/').map(read_step).collect::<Option<Vec<_>>>()?
729                };
730                Self::Edit {
731                    kind: kind.to_owned(),
732                    path,
733                }
734            }
735            "v" => {
736                let (app, rest) = rest.split_once('/')?;
737                let (kind, rest) = rest.split_once('/')?;
738                let (action, item) = match rest.split_once(':') {
739                    Some((action, item)) => (action, Some(item.to_owned())),
740                    None => (rest, None),
741                };
742                Self::Verb {
743                    action: crate::ActionKey::new(app, kind, action),
744                    item,
745                }
746            }
747            _ => return None,
748        })
749    }
750}
751
752/// What separates a continuation's claim from the invoker it names: the
753/// invoker's tree, in its [`crate::compact`] form, as hex.
754const INVOKER_MARK: char = '~';
755
756/// The gesture `gesture` as a continuation writes it: its [`crate::compact`]
757/// form.
758fn gesture_token(gesture: crate::ActionId) -> String {
759    crate::compact::encode(&serde_json::Value::String(
760        gesture.0.hyphenated().to_string(),
761    ))
762}
763
764/// The gesture a continuation's token writes.
765fn gesture_of(token: &str) -> Option<crate::ActionId> {
766    let text = crate::compact::decode(token)?;
767    let text = serde_json::from_str::<String>(&text).ok()?;
768    uuid::Uuid::try_parse(&text).ok().map(crate::ActionId)
769}
770
771/// The entry a change message carries whole; `None` for any other message. Entries are read
772/// through a value, not straight from their text, so every reader of entries shares one set of
773/// compiled field readers. Only [`crate::stamp::Stamp::read`] reads a message with it.
774pub(crate) fn entry_of_message(message: &str) -> Option<ActionContext> {
775    let entry = crate::compact::json_of(message.strip_prefix(CHANGE_MESSAGE_PREFIX)?)?;
776    let entry: serde_json::Value = serde_json::from_slice(&entry).ok()?;
777    serde_json::from_value::<wire::Entry>(entry)
778        .ok()
779        .map(wire::Entry::into_context)
780}
781
782/// What an entry a change message carries whole says of who made it and in which step
783/// ([`ActionContext::head_of_change_message`]); `None` for any other message.
784pub(crate) fn entry_head_of_message(message: &str) -> Option<ActionContext> {
785    let entry = crate::compact::json_of(message.strip_prefix(CHANGE_MESSAGE_PREFIX)?)?;
786    serde_json::from_slice::<wire::Head>(&entry)
787        .ok()
788        .map(wire::Head::into_context)
789}
790
791/// The entry as a change message carries it: every field of
792/// [`ActionContext`] under a short key, the resource and item as arrays, an
793/// action with its JSON payload inline, and what a reader derives again
794/// left out (the app the action's type names, an undoable kind, a field
795/// edit's path that is just its field). Reading it back and writing it again
796/// gives the same bytes, so a replaying device writes the same change.
797mod wire {
798    use serde::{Deserialize, Serialize};
799
800    use super::{
801        ActionApp, ActionContext, ActionFacet, ActionInvoker, ActionItem, ActionResource, Cause,
802        ChangeKind, WorkGroup,
803    };
804    use crate::entry::{Did, PathStep};
805    use crate::key::ActionKind;
806
807    #[derive(Default, Serialize, Deserialize)]
808    #[serde(default)]
809    pub(super) struct Entry {
810        #[serde(rename = "p", skip_serializing_if = "Option::is_none")]
811        app: Option<ActionApp>,
812        #[serde(rename = "r", skip_serializing_if = "Option::is_none")]
813        resource: Option<Resource>,
814        #[serde(rename = "i", skip_serializing_if = "Option::is_none")]
815        item: Option<Item>,
816        #[serde(rename = "w", skip_serializing_if = "Option::is_none")]
817        what: Option<Did>,
818        /// The path every field edit of a group shares, written once.
819        #[serde(rename = "wp", skip_serializing_if = "Option::is_none")]
820        shared_path: Option<Vec<PathStep>>,
821        #[serde(rename = "k", skip_serializing_if = "Option::is_none")]
822        kind: Option<ActionKind>,
823        #[serde(rename = "pu", skip_serializing_if = "Option::is_none")]
824        purpose: Option<String>,
825        #[serde(rename = "gr", skip_serializing_if = "Option::is_none")]
826        group: Option<WorkGroup>,
827        #[serde(rename = "f", skip_serializing_if = "Vec::is_empty")]
828        facets: Vec<ActionFacet>,
829        #[serde(
830            rename = "by",
831            skip_serializing_if = "Option::is_none",
832            deserialize_with = "readable"
833        )]
834        invoker: Option<ActionInvoker>,
835        #[serde(rename = "s", skip_serializing_if = "Option::is_none")]
836        source_invocation: Option<crate::InvocationId>,
837        #[serde(rename = "sc", skip_serializing_if = "Option::is_none")]
838        signed: Option<Box<crate::remote::SignedCall>>,
839        #[serde(rename = "cb", skip_serializing_if = "Option::is_none")]
840        caused_by: Option<Cause>,
841        #[serde(rename = "a", skip_serializing_if = "Option::is_none")]
842        action: Option<Action>,
843        #[serde(rename = "u", skip_serializing_if = "Option::is_none")]
844        compensation: Option<Action>,
845        #[serde(rename = "g", skip_serializing_if = "Option::is_none")]
846        gesture: Option<String>,
847        #[serde(rename = "c", skip_serializing_if = "ChangeKind::is_content")]
848        change: ChangeKind,
849        #[serde(rename = "sh", default, skip_serializing_if = "Vec::is_empty")]
850        shows: Vec<crate::remote::asked::Fact>,
851    }
852
853    /// The fields of an [`Entry`] an index keeps of every change, each left
854    /// as its text until read; the rest are skipped unread.
855    #[derive(Default, Deserialize)]
856    #[serde(default)]
857    pub(super) struct Head<'a> {
858        #[serde(rename = "k", borrow)]
859        kind: Option<&'a serde_json::value::RawValue>,
860        #[serde(rename = "gr", borrow)]
861        group: Option<&'a serde_json::value::RawValue>,
862        #[serde(rename = "by", borrow)]
863        invoker: Option<&'a serde_json::value::RawValue>,
864        #[serde(rename = "s", borrow)]
865        invocation: Option<&'a serde_json::value::RawValue>,
866        /// Only whether the entry carries an action: then it is undoable
867        /// unless it says otherwise.
868        #[serde(rename = "a", borrow)]
869        action: Option<&'a serde_json::value::RawValue>,
870        #[serde(rename = "g", borrow)]
871        gesture: Option<&'a serde_json::value::RawValue>,
872        #[serde(rename = "c", borrow)]
873        change: Option<&'a serde_json::value::RawValue>,
874    }
875
876    /// A field read through a JSON value, as whole entries are read, so the
877    /// field readers are compiled once.
878    fn field<T: serde::de::DeserializeOwned>(
879        raw: Option<&serde_json::value::RawValue>,
880    ) -> Option<T> {
881        let value = serde_json::from_slice::<serde_json::Value>(raw?.get().as_bytes()).ok()?;
882        serde_json::from_value(value).ok()
883    }
884
885    impl Head<'_> {
886        pub(super) fn into_context(self) -> ActionContext {
887            ActionContext {
888                kind: field(self.kind).or_else(|| self.action.map(|_| ActionKind::Undoable)),
889                group: field(self.group),
890                invoker: field(self.invoker),
891                source_invocation: field(self.invocation),
892                gesture: field::<String>(self.gesture)
893                    .and_then(|gesture| uuid::Uuid::try_parse(&gesture).ok())
894                    .map(crate::ActionId),
895                change: field(self.change).unwrap_or_default(),
896                ..ActionContext::default()
897            }
898        }
899    }
900
901    /// An encoded action: its type and its payload, inline as JSON when it
902    /// is canonical JSON, else as bytes.
903    #[derive(Serialize, Deserialize)]
904    #[serde(untagged)]
905    enum Action {
906        Json(String, serde_json::Value),
907        Bytes { t: String, b: Vec<u8> },
908    }
909
910    impl Action {
911        fn of(action: &crate::EncodedAction) -> Self {
912            serde_json::from_slice::<serde_json::Value>(&action.payload)
913                .ok()
914                .filter(|value| {
915                    serde_json::to_vec(value).is_ok_and(|bytes| bytes == action.payload)
916                })
917                .map_or_else(
918                    || Self::Bytes {
919                        t: action.type_id.clone(),
920                        b: action.payload.clone(),
921                    },
922                    |value| Self::Json(action.type_id.clone(), value),
923                )
924        }
925
926        fn into_encoded(self) -> Option<crate::EncodedAction> {
927            Some(match self {
928                Self::Json(type_id, value) => crate::EncodedAction {
929                    type_id,
930                    payload: serde_json::to_vec(&value).ok()?,
931                },
932                Self::Bytes { t, b } => crate::EncodedAction {
933                    type_id: t,
934                    payload: b,
935                },
936            })
937        }
938    }
939
940    /// The resource: id, kind and label, or kind and label for a resource
941    /// whose id is its kind (a record's own root).
942    #[derive(Serialize, Deserialize)]
943    #[serde(untagged)]
944    enum Resource {
945        Full(String, String, String),
946        Root(String, String),
947    }
948
949    impl Resource {
950        fn of(resource: &ActionResource) -> Self {
951            if resource.id == resource.kind {
952                Self::Root(resource.kind.clone(), resource.label.clone())
953            } else {
954                Self::Full(
955                    resource.id.clone(),
956                    resource.kind.clone(),
957                    resource.label.clone(),
958                )
959            }
960        }
961
962        fn into_resource(self) -> ActionResource {
963            match self {
964                Self::Full(id, kind, label) => ActionResource { id, kind, label },
965                Self::Root(kind, label) => ActionResource {
966                    id: kind.clone(),
967                    kind,
968                    label,
969                },
970            }
971        }
972    }
973
974    /// The item: its id and label, or its label alone when the resource's
975    /// id ends with the item's (`<kind>/<field>/<id>`).
976    #[derive(Serialize, Deserialize)]
977    #[serde(untagged)]
978    enum Item {
979        Full(String, String),
980        Named((String,)),
981    }
982
983    impl Item {
984        fn of(item: &ActionItem, resource: Option<&ActionResource>) -> Self {
985            let named = resource.is_some_and(|resource| {
986                !item.id.is_empty()
987                    && !item.id.contains('/')
988                    && resource
989                        .id
990                        .strip_suffix(item.id.as_str())
991                        .is_some_and(|rest| rest.ends_with('/'))
992            });
993            if named {
994                Self::Named((item.label.clone(),))
995            } else {
996                Self::Full(item.id.clone(), item.label.clone())
997            }
998        }
999
1000        fn into_item(self, resource: Option<&ActionResource>) -> ActionItem {
1001            match self {
1002                Self::Full(id, label) => ActionItem { id, label },
1003                Self::Named((label,)) => ActionItem {
1004                    id: resource
1005                        .and_then(|resource| resource.id.rsplit('/').next())
1006                        .unwrap_or_default()
1007                        .to_owned(),
1008                    label,
1009                },
1010            }
1011        }
1012    }
1013
1014    /// A field read as `None` when it does not parse, as [`Head`] reads it: an
1015    /// invoker written in an older form leaves the rest of its entry (the
1016    /// action, what it did and placed) readable.
1017    fn readable<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1018    where
1019        D: serde::Deserializer<'de>,
1020        T: serde::de::DeserializeOwned,
1021    {
1022        let value = serde_json::Value::deserialize(deserializer)?;
1023        Ok(serde_json::from_value(value).ok())
1024    }
1025
1026    /// What a reader derives again, left out: a field edit's path that is
1027    /// just its field, and a group's distinct actions when the group kept
1028    /// every member (they are its members without their values).
1029    fn trimmed(what: &Did) -> Did {
1030        let mut what = what.clone();
1031        trim(&mut what);
1032        what
1033    }
1034
1035    fn trim(what: &mut Did) {
1036        match what {
1037            Did::Edit(edit) if matches!(edit.path.as_slice(), [PathStep::Field(field)] if *field == edit.field) =>
1038            {
1039                edit.path.clear();
1040            }
1041            Did::Group(group) => {
1042                if group.count as usize == group.members.len()
1043                    && distinct_of(&group.members) == group.distinct
1044                {
1045                    group.distinct.clear();
1046                }
1047                group.members.iter_mut().for_each(trim);
1048            }
1049            _ => {}
1050        }
1051    }
1052
1053    fn filled(mut what: Did) -> Did {
1054        fill(&mut what);
1055        what
1056    }
1057
1058    fn fill(what: &mut Did) {
1059        match what {
1060            Did::Edit(edit) if edit.path.is_empty() => {
1061                edit.path.push(PathStep::Field(edit.field.clone()));
1062            }
1063            Did::Group(group) => {
1064                group.members.iter_mut().for_each(fill);
1065                if group.distinct.is_empty() && group.count as usize == group.members.len() {
1066                    group.distinct = distinct_of(&group.members);
1067                }
1068            }
1069            _ => {}
1070        }
1071    }
1072
1073    /// Where each field edit of `what` sits as the action the entry carries
1074    /// says it (a field edit's `path` argument; a group's members in order),
1075    /// when that action says it for every edit `what` describes.
1076    fn action_paths(
1077        action: Option<&crate::EncodedAction>,
1078        what: &Did,
1079    ) -> Option<Vec<Option<Vec<PathStep>>>> {
1080        fn path_of(stamped: &serde_json::Value) -> Option<Vec<PathStep>> {
1081            serde_json::from_value(stamped.get("op")?.get("args")?.get("path")?.clone()).ok()
1082        }
1083        let action = action?;
1084        let value: serde_json::Value = serde_json::from_slice(&action.payload).ok()?;
1085        let paths: Vec<Option<Vec<PathStep>>> = if crate::group_form::is_group(&action.type_id) {
1086            crate::group_form::members(value)?
1087                .iter()
1088                .map(path_of)
1089                .collect()
1090        } else {
1091            vec![path_of(&value)]
1092        };
1093        let fits = match what {
1094            Did::Edit(_) => paths.len() == 1,
1095            Did::Group(group) => paths.len() == group.members.len(),
1096            _ => false,
1097        };
1098        (fits && paths.iter().any(Option::is_some)).then_some(paths)
1099    }
1100
1101    /// `what` with every edit's path that the action says too left out (a
1102    /// group's distinct actions too, as [`trimmed`] leaves them); a path
1103    /// the action does not say stays written, even one that is just the
1104    /// field.
1105    fn paths_from_action(what: &Did, paths: &[Option<Vec<PathStep>>]) -> Did {
1106        let mut what = what.clone();
1107        let mut members: Vec<&mut Did> = match &mut what {
1108            Did::Group(group) => {
1109                if group.count as usize == group.members.len()
1110                    && distinct_of(&group.members) == group.distinct
1111                {
1112                    group.distinct.clear();
1113                }
1114                group.members.iter_mut().collect()
1115            }
1116            single => vec![single],
1117        };
1118        for (member, path) in members.iter_mut().zip(paths) {
1119            if let Did::Edit(edit) = member
1120                && path.as_ref() == Some(&edit.path)
1121            {
1122                edit.path.clear();
1123            }
1124        }
1125        what
1126    }
1127
1128    /// The paths [`paths_from_action`] left out, given back from the action.
1129    fn paths_given_back(mut what: Did, paths: &[Option<Vec<PathStep>>]) -> Did {
1130        let members: Vec<&mut Did> = match &mut what {
1131            Did::Group(group) => group.members.iter_mut().collect(),
1132            single => vec![single],
1133        };
1134        for (member, path) in members.into_iter().zip(paths) {
1135            if let (Did::Edit(edit), Some(path)) = (member, path)
1136                && edit.path.is_empty()
1137            {
1138                edit.path.clone_from(path);
1139            }
1140        }
1141        what
1142    }
1143
1144    /// The path every field edit member of a group shares, when there are
1145    /// at least two and the path is more than the field itself.
1146    fn shared_path(what: &Did) -> Option<Vec<PathStep>> {
1147        let Did::Group(group) = what else {
1148            return None;
1149        };
1150        let mut edits = group.members.iter().filter_map(|member| match member {
1151            Did::Edit(edit) => Some(edit),
1152            _ => None,
1153        });
1154        let first = edits.next()?;
1155        let mut more = false;
1156        for edit in edits {
1157            if edit.path != first.path {
1158                return None;
1159            }
1160            more = true;
1161        }
1162        let trivial =
1163            matches!(first.path.as_slice(), [PathStep::Field(field)] if *field == first.field);
1164        (more && !first.path.is_empty() && !trivial).then(|| first.path.clone())
1165    }
1166
1167    /// `what` with its edit members' shared path left to [`shared_path`].
1168    fn without_shared_path(mut what: Did) -> Did {
1169        if shared_path(&what).is_some()
1170            && let Did::Group(group) = &mut what
1171        {
1172            for member in &mut group.members {
1173                if let Did::Edit(edit) = member {
1174                    edit.path.clear();
1175                }
1176            }
1177        }
1178        what
1179    }
1180
1181    /// `what` with the shared path given back to its edit members.
1182    fn with_shared_path(mut what: Did, shared: Option<&[PathStep]>) -> Did {
1183        if let (Some(shared), Did::Group(group)) = (shared, &mut what) {
1184            for member in &mut group.members {
1185                if let Did::Edit(edit) = member {
1186                    edit.path = shared.to_vec();
1187                }
1188            }
1189        }
1190        what
1191    }
1192
1193    /// A group's distinct actions, as [`Did::group`] keeps them.
1194    fn distinct_of(members: &[Did]) -> Vec<Did> {
1195        match Did::group(members.iter().cloned()) {
1196            Did::Group(group) => group.distinct,
1197            _ => Vec::new(),
1198        }
1199    }
1200
1201    impl Entry {
1202        pub(super) fn of(context: &ActionContext) -> Self {
1203            let undoable = context.action.is_some() && context.kind == Some(ActionKind::Undoable);
1204            let paths = context
1205                .what
1206                .as_ref()
1207                .and_then(|what| action_paths(context.action.as_ref(), what));
1208            Self {
1209                app: context.app.clone(),
1210                resource: context.resource.as_ref().map(Resource::of),
1211                item: context
1212                    .item
1213                    .as_ref()
1214                    .map(|item| Item::of(item, context.resource.as_ref())),
1215                shared_path: context
1216                    .what
1217                    .as_ref()
1218                    .filter(|_| paths.is_none())
1219                    .and_then(shared_path),
1220                what: context.what.as_ref().map(|what| match &paths {
1221                    Some(paths) => paths_from_action(what, paths),
1222                    None => without_shared_path(trimmed(what)),
1223                }),
1224                kind: context.kind.filter(|_| !undoable),
1225                purpose: context.purpose.clone(),
1226                group: context.group.clone(),
1227                facets: context.facets.clone(),
1228                invoker: context.invoker.clone(),
1229                source_invocation: context.source_invocation,
1230                signed: context.signed.clone(),
1231                caused_by: context.caused_by.clone(),
1232                action: context.action.as_ref().map(Action::of),
1233                compensation: context.compensation.as_ref().map(Action::of),
1234                gesture: context
1235                    .gesture
1236                    .map(|gesture| gesture.0.simple().to_string()),
1237                change: context.change,
1238                shows: context.shows.clone(),
1239            }
1240        }
1241
1242        pub(super) fn into_context(self) -> ActionContext {
1243            let action = self.action.and_then(Action::into_encoded);
1244            let resource = self.resource.map(Resource::into_resource);
1245            ActionContext {
1246                app: self.app,
1247                resource: resource.clone(),
1248                item: self.item.map(|item| item.into_item(resource.as_ref())),
1249                what: self.what.map(|what| {
1250                    // A shared path is written only when the action does not say it.
1251                    let paths = self
1252                        .shared_path
1253                        .is_none()
1254                        .then(|| action_paths(action.as_ref(), &what))
1255                        .flatten();
1256                    match paths {
1257                        Some(paths) => filled(paths_given_back(what, &paths)),
1258                        None => filled(with_shared_path(what, self.shared_path.as_deref())),
1259                    }
1260                }),
1261                kind: self
1262                    .kind
1263                    .or_else(|| action.as_ref().map(|_| ActionKind::Undoable)),
1264                purpose: self.purpose,
1265                group: self.group,
1266                facets: self.facets,
1267                invoker: self.invoker,
1268                source_invocation: self.source_invocation,
1269                signed: self.signed,
1270                caused_by: self.caused_by,
1271                compensation: self.compensation.and_then(Action::into_encoded),
1272                gesture: self
1273                    .gesture
1274                    .and_then(|gesture| uuid::Uuid::try_parse(&gesture).ok())
1275                    .map(crate::ActionId),
1276                change: self.change,
1277                shows: self.shows,
1278                action,
1279                approval: None,
1280                pressed: false,
1281            }
1282        }
1283    }
1284}
1285
1286/// The longest label of a work group, in characters ([`one_line`]).
1287pub const MAX_LABEL_CHARS: usize = 96;
1288
1289/// `text` as one line people read: its first line with words on it, without
1290/// control characters, at most `max` characters, trimmed. `None` when it holds
1291/// no words.
1292#[must_use]
1293pub fn one_line(text: &str, max: usize) -> Option<String> {
1294    let line: String = text
1295        .lines()
1296        .map(str::trim)
1297        .find(|line| !line.is_empty())?
1298        .chars()
1299        .filter(|character| !character.is_control())
1300        .take(max)
1301        .collect();
1302    nonempty(&line)
1303}
1304
1305fn nonempty(value: &str) -> Option<String> {
1306    let trimmed = value.trim();
1307    (!trimmed.is_empty()).then(|| trimmed.to_string())
1308}
1309
1310pub use tilo_action_types::{MAX_PRESENCE_ID_BYTES, PresenceId};
1311
1312/// The longest name of a device kept with an invoker, in characters.
1313const MAX_DEVICE_NAME_CHARS: usize = 64;
1314
1315/// Another of its person's devices that an agent works from: the device the
1316/// MCP server that admitted the agent's connection verified it came from, by
1317/// the certificate the person's root signed for it.
1318///
1319/// It says where the agent runs, and grants nothing: who the agent is and
1320/// what it may do is [`ActionInvoker::acting`] and the admission behind it.
1321#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1322pub struct InvokerDevice {
1323    /// The device's public key, in lowercase hex.
1324    pub id: String,
1325    /// What the device's certificate calls it ("Studio laptop"); empty when
1326    /// it gives the device no name.
1327    #[serde(default, skip_serializing_if = "String::is_empty")]
1328    pub name: String,
1329}
1330
1331impl InvokerDevice {
1332    /// The device of the key `key`, called `label` by the certificate an API
1333    /// verified for it.
1334    #[must_use]
1335    pub fn certified(key: [u8; 32], label: &str) -> Self {
1336        Self {
1337            id: hex::encode(key),
1338            name: label
1339                .trim()
1340                .chars()
1341                .filter(|character| !character.is_control())
1342                .take(MAX_DEVICE_NAME_CHARS)
1343                .collect(),
1344        }
1345    }
1346
1347    /// The start of the device's key: what tells two devices of one name
1348    /// apart, and what names a device whose certificate names none.
1349    #[must_use]
1350    pub fn short_id(&self) -> &str {
1351        self.id.get(..8).unwrap_or(&self.id)
1352    }
1353
1354    /// The device as a person reads it: its name, or the start of its key
1355    /// when it has none.
1356    #[must_use]
1357    pub fn label(&self) -> &str {
1358        if self.name.is_empty() {
1359            self.short_id()
1360        } else {
1361            &self.name
1362        }
1363    }
1364}
1365
1366/// The invoker of one action: the authenticated acting tree, and optionally
1367/// the presence whose view the invocation resolves against.
1368///
1369/// `presence: None` means the actor's single/default view (the local
1370/// window for a person; the only view of a single-view app).
1371#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1372pub struct ActionInvoker {
1373    pub acting: Acting,
1374    #[serde(default, skip_serializing_if = "Option::is_none")]
1375    pub presence: Option<PresenceId>,
1376    /// The name and avatar a bot showed for this action. Set only by the
1377    /// API that admitted the invocation, and only for a bot allowed it.
1378    #[serde(default, skip_serializing_if = "Option::is_none")]
1379    pub appearance: Option<crate::Appearance>,
1380    /// The name an agent goes by: the name its harness gave the session it works
1381    /// in ("Release prep"), else the one the host that admitted it knows from the
1382    /// key its person certified for it ("Jane Doe's agent"). What History and a
1383    /// message's byline name it by; display only, never authority.
1384    #[serde(default, skip_serializing_if = "Option::is_none")]
1385    pub name: Option<String>,
1386    /// The other device of its person's an agent works from, when it came to
1387    /// this host through its MCP server. Set only by the host that admitted
1388    /// the connection, from the device certificate the API verified, and
1389    /// never taken from a request. `None` for an actor on the host's own
1390    /// device.
1391    #[serde(default, skip_serializing_if = "Option::is_none")]
1392    pub device: Option<InvokerDevice>,
1393}
1394
1395impl ActionInvoker {
1396    /// The actor the host admitted.
1397    #[must_use]
1398    pub fn admitted(acting: &Acting) -> Self {
1399        Self {
1400            acting: acting.clone(),
1401            presence: None,
1402            appearance: None,
1403            name: None,
1404            device: None,
1405        }
1406    }
1407
1408    /// A member acting for themselves.
1409    #[must_use]
1410    pub fn member(member: tilo_action_policy::MemberId) -> Self {
1411        Self::admitted(&Acting::member(member))
1412    }
1413
1414    /// A person the host authenticated, acting for themselves.
1415    #[track_caller]
1416    #[must_use]
1417    pub fn person(id: impl Into<tilo_action_policy::PersonId>) -> Self {
1418        Self::admitted(&Acting::person(id))
1419    }
1420
1421    /// The agent `id` of `person`, acting by itself.
1422    #[track_caller]
1423    #[must_use]
1424    pub fn agent(id: impl Into<String>, person: impl Into<tilo_action_policy::PersonId>) -> Self {
1425        Self::admitted(&Acting::agent(id, person))
1426    }
1427
1428    #[must_use]
1429    pub fn bot(id: impl Into<String>) -> Self {
1430        Self::admitted(&Acting::bot(id))
1431    }
1432
1433    #[must_use]
1434    pub fn automation(id: impl Into<String>) -> Self {
1435        Self::admitted(&Acting::automation(id))
1436    }
1437
1438    /// The view the invocation resolves against: its presence, else the member's default view.
1439    /// `None` for an automation, which has no view.
1440    #[must_use]
1441    pub fn view(&self) -> Option<PresenceId> {
1442        if let Some(presence) = &self.presence {
1443            return Some(presence.clone());
1444        }
1445        let member = self.acting.by.member_id()?.actor_bytes();
1446        PresenceId::new(String::from_utf8(member).ok()?).ok()
1447    }
1448
1449    #[must_use]
1450    pub fn with_presence(mut self, presence: PresenceId) -> Self {
1451        self.presence = Some(presence);
1452        self
1453    }
1454
1455    /// The name the admitting host knows this agent by ([`Self::name`]).
1456    #[must_use]
1457    pub fn named(mut self, name: Option<String>) -> Self {
1458        self.name = name;
1459        self
1460    }
1461
1462    /// The other device of its person's the agent works from
1463    /// ([`Self::device`]), as the API that admitted its connection verified
1464    /// it; `None` clears one, so an invoker copied from a caller's context
1465    /// never keeps a device no API checked.
1466    #[must_use]
1467    pub fn from_device(mut self, device: Option<InvokerDevice>) -> Self {
1468        self.device = device;
1469        self
1470    }
1471
1472    /// The same invoker, for `person`. A person acting for themselves
1473    /// records nobody.
1474    #[must_use]
1475    pub fn acting_for(mut self, person: impl Into<tilo_action_policy::PersonId>) -> Self {
1476        let person = person.into();
1477        if person.trim().is_empty() || self.acting.person_id() == Some(person.as_str()) {
1478            self.acting.acted_for.clear();
1479        } else {
1480            self.acting.acted_for = vec![Acting::person(person)];
1481        }
1482        self
1483    }
1484
1485    /// The appearance the API admitted for this one invocation; `None`
1486    /// clears one, so an invoker copied from a caller's context never keeps
1487    /// what no API checked.
1488    #[must_use]
1489    pub fn with_appearance(mut self, appearance: Option<crate::Appearance>) -> Self {
1490        self.appearance = appearance;
1491        self
1492    }
1493
1494    /// The invoker an application worker may act on for one delivered
1495    /// invocation. `actor` is the actor the host authenticated and put on
1496    /// the delivery; `context` is the host-built provenance of the same
1497    /// delivery. The presence, the person it acts for and the device it
1498    /// works from are kept only when the context names this exact actor, or an
1499    /// automation acting for exactly that actor. A context the host did not rewrite for this actor
1500    /// therefore never routes to anybody's view.
1501    pub fn delivered(actor: &Actor, context: Option<&ActionContext>) -> Self {
1502        let invoker = context.and_then(|context| context.invoker.as_ref());
1503        // An automation's step is delivered as the person it runs for; the
1504        // host names the automation acting for exactly that person.
1505        if let Some(automation) = invoker.filter(|invoker| {
1506            invoker.acting.is_automation()
1507                && invoker.acting.acted_for.first().map(|node| &node.by) == Some(actor)
1508        }) {
1509            return automation.clone();
1510        }
1511        match invoker.filter(|invoker| invoker.acting.by == *actor) {
1512            Some(named) => named.clone(),
1513            None => Self::admitted(&Acting::from(actor.clone())),
1514        }
1515    }
1516}
1517
1518#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1519pub struct ActionApp {
1520    /// Stable package/application id.
1521    pub id: String,
1522    pub label: String,
1523}
1524
1525#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1526pub struct ActionResource {
1527    pub id: String,
1528    pub kind: String,
1529    pub label: String,
1530}
1531
1532/// The run of a bot that made a change, and how deep in a chain of runs it
1533/// is: a run fired by a change that itself came from a run is one deeper.
1534/// Correlation only; it grants nothing. The dispatcher fires nothing past
1535/// a depth of four, so two bots answering each other stop.
1536#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1537pub struct Cause {
1538    pub installation: String,
1539    /// The firing change's hash (hex) or the connector event's id.
1540    pub event: String,
1541    pub depth: u8,
1542}
1543
1544/// The [`WorkGroup::kind`] of an agent session: every action one connection of
1545/// an agent (or a key it holds) takes, which history keeps, lists in Activity
1546/// and undoes whole.
1547pub const AGENT_SESSION_GROUP: &str = "agent-session";
1548
1549/// The group kind of one command line a shell ran: every file action it and
1550/// the commands it dispatched carried out, undone as one.
1551pub const COMMAND_GROUP: &str = "command";
1552
1553/// The group kind of the changes one move through history wrote, one for each step it moved
1554/// (an undo of three steps, a restore): History lists them as the one move a person made. The
1555/// kind names the move after a colon (`history:restore`), as [`history_group`] writes it.
1556pub const HISTORY_GROUP: &str = "history";
1557
1558/// The group kind of a move through history that was `op`.
1559#[must_use]
1560pub fn history_group(op: &crate::HistoryOp) -> String {
1561    let op = match op {
1562        crate::HistoryOp::Redo => "redo",
1563        crate::HistoryOp::Restore => "restore",
1564        crate::HistoryOp::Undo
1565        | crate::HistoryOp::Checkpoint { .. }
1566        | crate::HistoryOp::Migrate { .. } => "undo",
1567    };
1568    format!("{HISTORY_GROUP}:{op}")
1569}
1570
1571/// The move through history a group of `kind` was, when it is one.
1572#[must_use]
1573pub fn history_move(kind: &str) -> Option<crate::HistoryOp> {
1574    match kind.strip_prefix(HISTORY_GROUP)?.strip_prefix(':')? {
1575        "redo" => Some(crate::HistoryOp::Redo),
1576        "restore" => Some(crate::HistoryOp::Restore),
1577        "undo" => Some(crate::HistoryOp::Undo),
1578        _ => None,
1579    }
1580}
1581
1582/// Whether a group of this kind names a session that undo can name: an agent's
1583/// connection, or one command line of a shell.
1584#[must_use]
1585pub fn names_a_session(kind: &str) -> bool {
1586    kind == AGENT_SESSION_GROUP || kind == COMMAND_GROUP
1587}
1588
1589/// The unit of work an action belongs to: an issue, a task, an agent run.
1590/// Not a group of actions applied as one; that is `tilo_resource::ActionGroup`.
1591#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1592pub struct WorkGroup {
1593    /// Stable key shared by every action in the work unit.
1594    pub id: String,
1595    /// What the work is called, for people to read: an issue's title, what an
1596    /// agent session was asked to do, or the title the agent gave its work
1597    /// ("Fill Jane's application"). Never the group itself, which a host
1598    /// decides on its own. `None` when nothing says so.
1599    #[serde(default, skip_serializing_if = "Option::is_none")]
1600    pub label: Option<String>,
1601    /// Open vocabulary: `issue`, `task`, `agent-run`, `session`, …
1602    pub kind: String,
1603    /// The id the caller itself gave the work, when it named one: the run an
1604    /// agent says each of its calls is a step of. A host's own [`Self::id`]
1605    /// may span several of them (every call of one connection), so this is
1606    /// what tells the caller's runs apart in history; never the group itself.
1607    #[serde(default, skip_serializing_if = "Option::is_none")]
1608    pub declared_id: Option<String>,
1609    /// The session's own name, as the client's harness names it ("Office
1610    /// Hours"): what an agent that works through a connection of its own is
1611    /// shown by, where the session is what people see it as. Display only,
1612    /// like the label; `None` for work that names no session.
1613    #[serde(default, skip_serializing_if = "Option::is_none")]
1614    pub session: Option<String>,
1615}
1616
1617/// [`ActionFacet::key`] of the risk ([`crate::RiskLevel::name`]) of the
1618/// action a context describes, for a question about it put to a person.
1619pub const RISK_FACET: &str = "risk";
1620
1621/// [`ActionFacet::key`] of where in its app's record a step happened, as
1622/// everyone the record is shared with sees that place named: a chat post's
1623/// channel, `#general`. Only such a place is named; a direct conversation
1624/// never is.
1625pub const PLACE_FACET: &str = "place";
1626
1627/// A filterable activity dimension. Open key/value vocabulary lets future
1628/// apps add facets without changing the wire enum.
1629#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1630pub struct ActionFacet {
1631    /// e.g. `path`, `directory`, `file-type`, `mime`, `repository`.
1632    pub key: String,
1633    pub value: String,
1634}
1635
1636impl ActionFacet {
1637    pub fn new(key: impl Into<String>, value: impl Into<String>) -> Self {
1638        Self {
1639            key: key.into(),
1640            value: value.into(),
1641        }
1642    }
1643}
1644
1645#[cfg(test)]
1646mod tests {
1647    use super::*;
1648    use crate::entry::{EditOp, FieldEdit, PathStep, Scalar};
1649    use crate::key::ActionKey;
1650    use tilo_action_policy::MemberId;
1651
1652    fn laptop() -> InvokerDevice {
1653        InvokerDevice::certified([0x5c; 32], "  Studio\u{7} laptop ")
1654    }
1655
1656    fn starred() -> Described {
1657        Described::new(Did::Edit(FieldEdit {
1658            ty: "snippet".into(),
1659            field: "favorite".into(),
1660            path: vec![
1661                PathStep::Field("snippets".into()),
1662                PathStep::Item("s1".into()),
1663                PathStep::Field("favorite".into()),
1664            ],
1665            op: EditOp::Set,
1666            old: Some(false.into()),
1667            new: Some(true.into()),
1668            args: std::collections::BTreeMap::new(),
1669        }))
1670        .on("s1", "Deploy script")
1671    }
1672
1673    /// The entry `message` carries, as JSON text.
1674    fn written(message: &str) -> String {
1675        let entry = message.strip_prefix(CHANGE_MESSAGE_PREFIX).unwrap();
1676        crate::compact::decode(entry).unwrap()
1677    }
1678
1679    tilo_test_env::scenario! {
1680        fn the_host_states_the_invoker;
1681
1682        phase the_host_rewriting_the_invoker_drops_an_appearance_the_caller_put_there;
1683        {
1684            let smuggled = ActionContext::default().with_invoker(
1685                ActionInvoker::person("mallory")
1686                    .with_appearance(Some(crate::Appearance::new("Ada", None, None).unwrap())),
1687            );
1688            let hosted = smuggled.with_host_actor(&crate::Acting::person("mallory"), None);
1689            assert_eq!(hosted.invoker.unwrap().appearance, None);
1690        }
1691
1692        phase a_delivered_invoker_keeps_the_appearance_only_for_the_named_actor;
1693        {
1694            let appearance = crate::Appearance::new("alice", None, None).unwrap();
1695            let context = ActionContext::default().with_invoker(
1696                ActionInvoker::bot("7f1c").with_appearance(Some(appearance.clone())),
1697            );
1698            assert_eq!(
1699                ActionInvoker::delivered(&MemberId::bot("7f1c").into(), Some(&context)).appearance,
1700                Some(appearance)
1701            );
1702            assert_eq!(
1703                ActionInvoker::delivered(&MemberId::person("b").into(), Some(&context)).appearance,
1704                None
1705            );
1706        }
1707
1708        phase a_device_is_named_by_its_certificate_or_the_start_of_its_key;
1709        {
1710            let laptop = laptop();
1711            assert_eq!(laptop.id, "5c".repeat(32));
1712            assert_eq!(
1713                laptop.name, "Studio laptop",
1714                "trimmed, no control characters"
1715            );
1716            assert_eq!(laptop.short_id(), "5c5c5c5c");
1717            assert_eq!(laptop.label(), "Studio laptop");
1718            let unnamed = InvokerDevice::certified([0x40; 32], " ");
1719            assert_eq!(unnamed.label(), "40404040");
1720            let long = InvokerDevice::certified([1; 32], &"x".repeat(200));
1721            assert_eq!(long.name.chars().count(), MAX_DEVICE_NAME_CHARS);
1722        }
1723
1724        phase the_host_rewriting_the_invoker_drops_a_device_the_caller_put_there;
1725        {
1726            let smuggled = ActionContext::default().with_invoker(
1727                ActionInvoker::agent("mallory", "ada").from_device(Some(laptop())),
1728            );
1729            let hosted = smuggled.with_host_actor(&crate::Acting::agent("mallory", "ada"), None);
1730            assert_eq!(hosted.invoker.unwrap().device, None);
1731        }
1732
1733        phase a_delivered_invoker_keeps_the_device_only_for_the_named_actor;
1734        {
1735            let context = ActionContext::default().with_invoker(
1736                ActionInvoker::agent("task-7", "ada").from_device(Some(laptop())),
1737            );
1738            assert_eq!(
1739                ActionInvoker::delivered(&MemberId::agent("task-7", "ada").into(), Some(&context)).device,
1740                Some(laptop())
1741            );
1742            assert_eq!(
1743                ActionInvoker::delivered(&MemberId::agent("task-8", "ada").into(), Some(&context)).device,
1744                None,
1745                "another actor is not on that device because a context names it"
1746            );
1747            assert_eq!(ActionInvoker::delivered(&MemberId::agent("task-7", "ada").into(), None).device, None);
1748        }
1749
1750        phase invoker_round_trips_and_is_enriched_from_ambient;
1751        {
1752            let invoker = ActionInvoker::agent("alpha", "ada")
1753                .with_presence(PresenceId::new("task-7").unwrap());
1754            let context = ActionContext::for_resource("r", "k", "l").with_invoker(invoker.clone());
1755            let message = context.change_message().unwrap();
1756            assert_eq!(
1757                ActionContext::from_change_message(&message),
1758                Some(context.clone())
1759            );
1760            let enriched = ActionContext::default().enriched_by(&context);
1761            assert_eq!(enriched.invoker, Some(invoker));
1762        }
1763
1764        phase a_person_acting_for_themselves_records_nobody;
1765        {
1766            assert_eq!(
1767                ActionInvoker::person("ada").acting_for("ada").acting.acted_for_person(),
1768                None
1769            );
1770            let agent = ActionInvoker::agent("claude", "ada").acting_for("ada");
1771            assert!(agent.acting.is_agent());
1772            assert_eq!(agent.acting.acted_for_person(), Some("ada"));
1773        }
1774
1775        phase host_invoker_overwrites_a_forged_envelope_invoker;
1776        {
1777            let forged = ActionContext::for_resource("r", "k", "l").with_invoker(
1778                ActionInvoker::person("owner")
1779                    .acting_for("other")
1780                    .with_presence(PresenceId::new("owner-window").unwrap()),
1781            );
1782            let task = PresenceId::new("agent-alpha-view").unwrap();
1783            let rewritten = forged
1784                .clone()
1785                .with_host_actor(&crate::Acting::agent("alpha", "owner"), Some(task.clone()));
1786            assert_eq!(
1787                rewritten.invoker,
1788                Some(ActionInvoker::agent("alpha", "owner").with_presence(task))
1789            );
1790            let delegated = forged.with_host_actor(
1791                &crate::Acting::agent("alpha", "owner").acting_for(crate::Acting::person("owner")),
1792                None,
1793            );
1794            let invoker = delegated.invoker.unwrap();
1795            assert!(invoker.acting.is_agent());
1796            assert_eq!(
1797                invoker.acting.acted_for_person(),
1798                Some("owner"),
1799                "the host records whom the admitted actor acts for"
1800            );
1801        }
1802
1803        phase delivered_invoker_keeps_the_presence_only_for_the_delivered_actor;
1804        {
1805            let presence = PresenceId::new("agent-a-view").unwrap();
1806            let context =
1807                ActionContext::default()
1808                    .with_host_actor(&crate::Acting::agent("a", "ada"), Some(presence.clone()));
1809            assert_eq!(
1810                ActionInvoker::delivered(&MemberId::agent("a", "ada").into(), Some(&context)),
1811                ActionInvoker::agent("a", "ada").with_presence(presence)
1812            );
1813            // A context naming another actor never routes to a view, and the
1814            // actor always comes from the delivery.
1815            assert_eq!(
1816                ActionInvoker::delivered(&MemberId::person("b").into(), Some(&context)),
1817                ActionInvoker::person("b")
1818            );
1819            assert_eq!(
1820                ActionInvoker::delivered(&MemberId::person("b").into(), None),
1821                ActionInvoker::person("b")
1822            );
1823            // A Shortcut step is delivered as its person; the Shortcut acting for
1824            // exactly that person is kept, for anybody else it is not.
1825            let shortcut = ActionInvoker::automation("morning").acting_for("b");
1826            let run = ActionContext::default().with_invoker(shortcut.clone());
1827            assert_eq!(ActionInvoker::delivered(&MemberId::person("b").into(), Some(&run)), shortcut);
1828            assert_eq!(
1829                ActionInvoker::delivered(&MemberId::person("c").into(), Some(&run)),
1830                ActionInvoker::person("c")
1831            );
1832        }
1833
1834        phase presence_ids_are_bounded;
1835        {
1836            assert!(PresenceId::new("").is_err());
1837            assert!(PresenceId::new("has space").is_err());
1838            assert!(PresenceId::new("x".repeat(MAX_PRESENCE_ID_BYTES + 1)).is_err());
1839            assert!(PresenceId::new("x".repeat(MAX_PRESENCE_ID_BYTES)).is_ok());
1840            assert!(serde_json::from_str::<PresenceId>("\"\"").is_err());
1841        }
1842    }
1843
1844    tilo_test_env::scenario! {
1845        fn a_context_reads_back_from_its_change_message;
1846
1847        phase an_appearance_round_trips_through_the_change_message;
1848        {
1849            let appearance = crate::Appearance::new(
1850                "alice",
1851                None,
1852                Some(crate::Persona {
1853                    service: "discord".into(),
1854                    account: "80351110224678912".into(),
1855                    linked: None,
1856                }),
1857            )
1858            .unwrap();
1859            let entry = ActionContext::default().with_invoker(
1860                ActionInvoker::bot("7f1c")
1861                    .acting_for("ada")
1862                    .with_appearance(Some(appearance.clone())),
1863            );
1864            let read = ActionContext::from_change_message(&entry.change_message().unwrap()).unwrap();
1865            assert_eq!(read, entry);
1866            assert_eq!(read.invoker.unwrap().appearance, Some(appearance));
1867            let plain = ActionContext::default().with_invoker(ActionInvoker::person("ada"));
1868            let json = serde_json::to_string(&plain.invoker).unwrap();
1869            assert!(!json.contains("appearance"), "{json}");
1870        }
1871
1872        phase the_device_an_agent_works_from_round_trips_through_the_change_message;
1873        {
1874            let entry = ActionContext::default().with_invoker(
1875                ActionInvoker::agent("task-7", "ada")
1876                    .acting_for("ada")
1877                    .from_device(Some(laptop())),
1878            );
1879            let read = ActionContext::from_change_message(&entry.change_message().unwrap()).unwrap();
1880            assert_eq!(read, entry);
1881            assert_eq!(read.invoker.unwrap().device, Some(laptop()));
1882            // An actor on the host's own device says nothing of a device.
1883            let local = ActionContext::default().with_invoker(ActionInvoker::agent("task-8", "ada"));
1884            let json = serde_json::to_string(&local.invoker).unwrap();
1885            assert!(!json.contains("\"device\""), "{json}");
1886        }
1887
1888        phase a_cause_survives_the_change_message;
1889        {
1890            let context = ActionContext::for_app("so.tilo.chat", "Chat").with_caused_by(Some(Cause {
1891                installation: "4a6c0c49-8a0d-4c3e-9d55-0a1b2c3d4e5f".into(),
1892                event: "ab".repeat(32),
1893                depth: 3,
1894            }));
1895            let message = context.change_message().unwrap();
1896            let read = ActionContext::from_change_message(&message).unwrap();
1897            assert_eq!(read.caused_by, context.caused_by);
1898            // A context without a cause writes no key for it.
1899            let plain = ActionContext::for_app("so.tilo.chat", "Chat")
1900                .change_message()
1901                .unwrap();
1902            assert!(
1903                ActionContext::from_change_message(&plain)
1904                    .unwrap()
1905                    .caused_by
1906                    .is_none()
1907            );
1908        }
1909
1910        phase entries_round_trip_through_the_change_message;
1911        {
1912            let entry = ActionContext::for_resource("lib", "snippets.library", "Snippets")
1913                .with_app("org.tilo.Snippets", "Snippets")
1914                .with_described(starred())
1915                .with_group("run:7", "Tidy snippets", "agent-session")
1916                .with_invoker(
1917                    ActionInvoker::agent("claude", "ada").acting_for("ada"),
1918                )
1919                .with_source_invocation(Some(InvocationId(uuid::Uuid::from_u128(42))));
1920            let message = entry.change_message().unwrap();
1921            let read = ActionContext::from_change_message(&message).unwrap();
1922            assert_eq!(read, entry);
1923            assert!(read.acting().unwrap().is_agent());
1924            assert_eq!(
1925                read.acting().unwrap().acted_for_person(),
1926                Some("ada")
1927            );
1928            assert_eq!(read.described(), Some(starred()));
1929
1930            let verb = ActionContext::default().with_described(Described::new(Did::verb(
1931                ActionKey::new("snippets", "snippets.library", "new-snippet"),
1932                [("title".to_string(), Scalar::from("Deploy"))],
1933            )));
1934            let read = ActionContext::from_change_message(&verb.change_message().unwrap()).unwrap();
1935            assert_eq!(read, verb);
1936        }
1937
1938        phase an_entry_leaves_out_what_its_reader_derives_and_reads_back_the_same;
1939        {
1940            let action = crate::EncodedAction {
1941                type_id: "word-processor.edit".into(),
1942                payload: br#"{"op":"type","text":"a"}"#.to_vec(),
1943            };
1944            let entry = ActionContext {
1945                what: Some(Did::Edit(crate::FieldEdit {
1946                    ty: "document".into(),
1947                    field: "body".into(),
1948                    path: vec![PathStep::Field("body".into())],
1949                    op: crate::EditOp::Splice,
1950                    old: None,
1951                    new: None,
1952                    args: std::collections::BTreeMap::new(),
1953                })),
1954                kind: Some(ActionKind::Undoable),
1955                action: Some(action),
1956                gesture: Some(crate::ActionId::new()),
1957                ..ActionContext::for_resource("doc:1", "word-processor.document", "Plan")
1958                    .with_app("org.tilo.WordProcessor", "Word Processor")
1959            };
1960            let message = entry.change_message().unwrap();
1961            // An undoable kind and a path that is just the field are left out;
1962            // the payload is inline JSON.
1963            for derived in ["undoable", "path", "[123,"] {
1964                assert!(!message.contains(derived), "{derived} in {message}");
1965            }
1966            assert!(message.len() < 230, "{} B: {message}", message.len());
1967            let read = ActionContext::from_change_message(&message).unwrap();
1968            assert_eq!(read, entry);
1969            assert_eq!(
1970                read.change_message().unwrap(),
1971                message,
1972                "written again the same"
1973            );
1974            // No app at all stays no app.
1975            let bare = ActionContext { app: None, ..entry };
1976            let read = ActionContext::from_change_message(&bare.change_message().unwrap()).unwrap();
1977            assert_eq!(read, bare);
1978        }
1979
1980        phase a_group_writes_what_its_members_share_once;
1981        {
1982            let path = vec![
1983                PathStep::Field("sheets".into()),
1984                PathStep::Item("s1".into()),
1985                PathStep::Field("cells".into()),
1986            ];
1987            let edit = |op| {
1988                Did::Edit(FieldEdit {
1989                    ty: "sheet".into(),
1990                    field: "cells".into(),
1991                    path: path.clone(),
1992                    op,
1993                    old: None,
1994                    new: None,
1995                    args: std::collections::BTreeMap::new(),
1996                })
1997            };
1998            let mut entry =
1999                ActionContext::for_resource("sheets.workbook", "sheets.workbook", "Workbook");
2000            entry.what = Some(Did::group([edit(EditOp::InsertRow), edit(EditOp::SetCell)]));
2001            let message = entry.change_message().unwrap();
2002            assert!(!message.contains("distinct"), "{message}");
2003            assert_eq!(
2004                written(&message).matches("\"cells\"").count(),
2005                3,
2006                "the path once: {message}"
2007            );
2008            let read = ActionContext::from_change_message(&message).unwrap();
2009            assert_eq!(read, entry);
2010            assert_eq!(
2011                read.change_message().unwrap(),
2012                message,
2013                "written again the same"
2014            );
2015        }
2016
2017        phase an_edit_takes_its_path_from_the_action_it_carries;
2018        {
2019            let path = vec![
2020                PathStep::Field("pages".into()),
2021                PathStep::Item("p1".into()),
2022                PathStep::Field("body".into()),
2023            ];
2024            let mut entry = ActionContext::for_resource("notes.notebook", "notes.notebook", "Notebook");
2025            entry.what = Some(Did::Edit(FieldEdit {
2026                ty: "page".into(),
2027                field: "body".into(),
2028                path,
2029                op: EditOp::Splice,
2030                old: None,
2031                new: None,
2032                args: std::collections::BTreeMap::new(),
2033            }));
2034            entry.action = Some(crate::EncodedAction {
2035                type_id: "notes.notebook".into(),
2036                payload: br#"{"op":{"action":"field-edit","args":{"op":"rich","path":[{"field":"pages"},{"item":"p1"},{"field":"body"}]}},"at":0}"#.to_vec(),
2037            });
2038            entry.kind = Some(ActionKind::Undoable);
2039            let message = entry.change_message().unwrap();
2040            assert_eq!(
2041                written(&message).matches("\"pages\"").count(),
2042                1,
2043                "the path once: {message}"
2044            );
2045            assert!(
2046                message.len() * 10 < written(&message).len() * 7,
2047                "the compact form is well under the JSON one: {message}"
2048            );
2049            let read = ActionContext::from_change_message(&message).unwrap();
2050            assert_eq!(read, entry);
2051            assert_eq!(
2052                read.change_message().unwrap(),
2053                message,
2054                "written again the same"
2055            );
2056        }
2057
2058        phase an_item_named_by_its_resource_writes_its_id_once;
2059        {
2060            let mut entry =
2061                ActionContext::for_resource("notes.notebook/pages/p1", "tilo.rich-text", "Document");
2062            entry.item = Some(ActionItem {
2063                id: "p1".into(),
2064                label: "Plans".into(),
2065            });
2066            let message = entry.change_message().unwrap();
2067            assert_eq!(message.matches("p1").count(), 1, "the id once: {message}");
2068            let read = ActionContext::from_change_message(&message).unwrap();
2069            assert_eq!(read, entry);
2070            assert_eq!(
2071                read.change_message().unwrap(),
2072                message,
2073                "written again the same"
2074            );
2075            // An item the resource does not name keeps its id.
2076            entry.item = Some(ActionItem {
2077                id: "p2".into(),
2078                label: "Other".into(),
2079            });
2080            let read = ActionContext::from_change_message(&entry.change_message().unwrap()).unwrap();
2081            assert_eq!(read, entry);
2082        }
2083
2084        phase an_invoker_written_in_an_older_form_keeps_the_rest_of_its_entry;
2085        {
2086            let context = ActionContext::for_resource("r", "k", "l");
2087            let mut json: serde_json::Value =
2088                serde_json::from_str(&written(&context.change_message().unwrap())).unwrap();
2089            json["by"] = serde_json::json!({ "actor": "ada" });
2090            let message = format!("{CHANGE_MESSAGE_PREFIX}{}", crate::compact::encode(&json));
2091            assert_eq!(ActionContext::from_change_message(&message), Some(context));
2092        }
2093
2094        phase defaults_are_not_written;
2095        {
2096            let context = ActionContext::for_resource("r", "k", "l");
2097            let message = context.change_message().unwrap();
2098            let json: serde_json::Value = serde_json::from_str(&written(&message)).unwrap();
2099            let written: Vec<&str> = json
2100                .as_object()
2101                .unwrap()
2102                .keys()
2103                .map(String::as_str)
2104                .collect();
2105            assert_eq!(written, ["r"], "{message}");
2106            assert_eq!(ActionContext::from_change_message(&message), Some(context));
2107            let outside = ActionContext::default().with_change(ChangeKind::External);
2108            let mut outside = outside;
2109            outside.kind = Some(ActionKind::Outside);
2110            let read = ActionContext::from_change_message(&outside.change_message().unwrap()).unwrap();
2111            assert_eq!(read.kind, Some(ActionKind::Outside));
2112            assert!(
2113                !read.is_activity(),
2114                "what came from outside is not activity"
2115            );
2116        }
2117
2118        phase housekeeping_is_carried;
2119        {
2120            let content = ActionContext::for_resource("r", "k", "l");
2121            let marker = content.clone().with_change(ChangeKind::Housekeeping);
2122            let message = marker.change_message().unwrap();
2123            let read = ActionContext::from_change_message(&message).unwrap();
2124            assert!(read.is_housekeeping());
2125            assert_eq!(read, marker);
2126            let bare = ActionContext::default().with_change(ChangeKind::Housekeeping);
2127            assert!(
2128                bare.change_message().is_some(),
2129                "housekeeping alone is still written"
2130            );
2131            assert!(
2132                !ActionContext::from_change_message(&content.change_message().unwrap())
2133                    .unwrap()
2134                    .is_housekeeping()
2135            );
2136        }
2137
2138        phase unrelated_or_malformed_messages_are_not_entries;
2139        {
2140            assert!(ActionContext::from_change_message("saved draft").is_none());
2141            assert!(ActionContext::from_change_message("tilo.entry/1 {").is_none());
2142            assert!(ActionContext::default().change_message().is_none());
2143        }
2144    }
2145
2146    tilo_test_env::scenario! {
2147        fn ambient_context_fills_what_the_action_leaves_open;
2148
2149        phase ambient_context_fills_intent_without_overwriting_the_action;
2150        {
2151            let action = ActionContext::for_resource("file:1", "file", "brief.md")
2152                .with_app("org.tilo.Code", "Code");
2153            let ambient = ActionContext::default()
2154                .with_purpose("Prepare launch")
2155                .with_group("issue:42", "Launch", "issue")
2156                .with_app("wrong", "Wrong");
2157            let merged = action.enriched_by(&ambient);
2158            assert_eq!(
2159                merged.app.as_ref().map(|app| app.id.as_str()),
2160                Some("org.tilo.Code")
2161            );
2162            assert_eq!(merged.purpose.as_deref(), Some("Prepare launch"));
2163            assert_eq!(
2164                merged.group.as_ref().map(|group| group.id.as_str()),
2165                Some("issue:42")
2166            );
2167        }
2168    }
2169
2170    #[test]
2171    fn a_keystroke_continues_its_writers_last_entry_with_its_gesture_bytes_and_claim() {
2172        let typed = |letter: &str, gesture: u128| ActionContext {
2173            action: Some(crate::EncodedAction {
2174                type_id: "notes.notebook".into(),
2175                payload: format!(
2176                    r#"{{"SpliceText":{{"at":12,"ins":{letter}}},"path":[{{"item":"8dc4"}}]}}"#
2177                )
2178                .into_bytes(),
2179            }),
2180            ..ActionContext::default()
2181                .with_described(starred())
2182                .in_gesture(Some(crate::ActionId(uuid::Uuid::from_u128(gesture))))
2183        };
2184        // The next word's first letter starts its own gesture.
2185        let (first, next) = (typed(r#""n""#, 7), typed(r#""é \"q\"""#, 8));
2186        let message = next.continuation_of(&first).unwrap();
2187        assert_eq!(
2188            message,
2189            r#"tilo.cont/3 U8000000000000000000000 e::fsnippets/is1/ffavorite 30 28 é \"q\""#
2190        );
2191        assert_eq!(
2192            ContinuedAction::of_message(&message),
2193            Some(ContinuedAction::Edit {
2194                kind: String::new(),
2195                path: vec![
2196                    PathStep::Field("snippets".into()),
2197                    PathStep::Item("s1".into()),
2198                    PathStep::Field("favorite".into()),
2199                ],
2200            })
2201        );
2202        assert_eq!(
2203            ActionContext::continued(&message, &first),
2204            Some(next),
2205            "read back byte for byte"
2206        );
2207    }
2208}