Skip to main content

tilo_actions/
contract.rs

1//! Machine-readable operational semantics for exported actions.
2//!
3//! Labels explain an action to a person. This module explains it to callers
4//! that must plan safely without seeing the application: whether it is
5//! currently available, what confirmation it needs, whether a failed call may
6//! be retried, how it completes, and what it returns.
7
8use serde::{Deserialize, Serialize};
9pub use tilo_action_policy::ActionKind;
10
11use crate::action::{OperationKind, undo_takes_back};
12use crate::context::ChangeKind;
13
14/// Whether an action can be invoked in the resource's current state.
15#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(remote = "Self", tag = "state", rename_all = "snake_case")]
17pub enum Availability {
18    #[default]
19    Available,
20    Unavailable {
21        /// Stable programmatic reason such as `offline` or `selection_empty`.
22        code: String,
23        /// Localised explanation suitable for a person or an agent transcript.
24        reason: String,
25    },
26}
27
28read_through_json_value!(Availability);
29
30impl Availability {
31    /// The code of an action its caller's permissions deny ([`Self::not_allowed`]).
32    pub const NOT_ALLOWED: &'static str = "not_allowed";
33
34    pub fn is_available(&self) -> bool {
35        matches!(self, Self::Available)
36    }
37
38    /// An action an agent's permissions deny it, as it is listed to the agent: told, in one
39    /// sentence, what refuses it (`by`, where the check knows) and where that is changed, rather
40    /// than left to read the action's absence as there being no such action.
41    #[must_use]
42    pub fn not_allowed(by: Option<tilo_action_policy::Refuser>) -> Self {
43        let reason = match by {
44            Some(tilo_action_policy::Refuser::Settings) => {
45                "the person you work for set this to Deny for you in this workspace; they can \
46                 change it under Workspace settings → Agents"
47            }
48            Some(tilo_action_policy::Refuser::Workspace) => {
49                "this workspace's own rules don't let agents or keys do this here"
50            }
51            None => Self::NOT_ALLOWED_HERE,
52        };
53        Self::Unavailable {
54            code: Self::NOT_ALLOWED.to_owned(),
55            reason: reason.to_owned(),
56        }
57    }
58
59    /// What an action refused by a check that does not say which rule refused it is told.
60    pub const NOT_ALLOWED_HERE: &'static str = "this workspace's permissions don't let you do \
61         this here; the person you work for can change what you may do under Workspace \
62         settings → Agents";
63
64    /// The code of an action only the person at its device invokes
65    /// ([`Self::shown_here`]).
66    pub const PRIVATE_VIEW: &'static str = "private_view";
67
68    /// An action that only changes what the person at its device sees (a
69    /// form it opens, a place it shows), as an agent that names it is told
70    /// of it: never listed to it, and refused as that person's alone rather
71    /// than as an action the app does not have.
72    #[must_use]
73    pub fn shown_here() -> Self {
74        Self::Unavailable {
75            code: Self::PRIVATE_VIEW.to_owned(),
76            reason: Self::SHOWN_HERE.to_owned(),
77        }
78    }
79
80    /// Why an action [`Self::shown_here`] is refused to anyone but the
81    /// person at its device.
82    pub const SHOWN_HERE: &'static str =
83        "only changes what the person at this device sees; only they invoke it";
84
85    /// The code and reason of an action listed to an agent as refused
86    /// ([`Self::not_allowed`], [`Self::shown_here`]), when it is.
87    #[must_use]
88    pub fn refusal(&self) -> Option<(&str, &str)> {
89        match self {
90            Self::Unavailable { code, reason }
91                if code == Self::NOT_ALLOWED || code == Self::PRIVATE_VIEW =>
92            {
93                Some((code, reason))
94            }
95            Self::Available | Self::Unavailable { .. } => None,
96        }
97    }
98}
99
100/// Consequence class used by policy, confirmation UI, and audit logs.
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
102#[serde(rename_all = "snake_case")]
103pub enum RiskLevel {
104    /// Presentation-only or otherwise observational.
105    None,
106    /// A reversible edit or ordinary external effect.
107    #[default]
108    Low,
109    /// Deletes, overwrites, publishes, purchases, or otherwise causes a
110    /// consequential change that is not cheaply reversible.
111    Destructive,
112    /// Crosses an administrative or security boundary.
113    Privileged,
114    /// Reads or exports private user data. It needs an explicit confirmation,
115    /// but unlike deletion it does not itself alter the source resource.
116    ///
117    /// This is deliberately appended: `RiskLevel` is also encoded by compact
118    /// serde formats, where reordering variants would reinterpret old audit
119    /// records and envelopes.
120    Sensitive,
121}
122
123impl RiskLevel {
124    /// Whether a change of this class must be explicitly confirmed before it
125    /// runs: deletions and overwrites, crossings of a security boundary, and
126    /// exports of private data.
127    pub fn requires_confirmation(self) -> bool {
128        matches!(self, Self::Destructive | Self::Privileged | Self::Sensitive)
129    }
130
131    /// Whether a change of this class that `can_be_undone` must be
132    /// confirmed before it runs. Undo is a system service: a deletion Undo
133    /// takes back runs at once and offers Undo, and is never asked about.
134    /// What Undo cannot take back is still asked: an irreversible deletion,
135    /// a crossing of a security boundary, an export of private data.
136    #[must_use]
137    pub fn requires_confirmation_when(self, can_be_undone: bool) -> bool {
138        match self {
139            Self::Destructive => !can_be_undone,
140            Self::Privileged | Self::Sensitive => true,
141            Self::None | Self::Low => false,
142        }
143    }
144
145    /// The level's name, as it is written outside a typed message (a
146    /// question a host relays, an activity facet).
147    #[must_use]
148    pub const fn name(self) -> &'static str {
149        match self {
150            Self::None => "none",
151            Self::Low => "low",
152            Self::Destructive => "destructive",
153            Self::Privileged => "privileged",
154            Self::Sensitive => "sensitive",
155        }
156    }
157
158    /// The level [`Self::name`] names; `None` for any other word.
159    #[must_use]
160    pub fn from_name(name: &str) -> Option<Self> {
161        [
162            Self::None,
163            Self::Low,
164            Self::Destructive,
165            Self::Privileged,
166            Self::Sensitive,
167        ]
168        .into_iter()
169        .find(|level| level.name() == name)
170    }
171}
172
173/// [`ActionContract::tags`] entry of an action any member of a workspace may ask
174/// the workspace's host to run for themselves on a record of the workspace (linking
175/// their own account elsewhere). The host runs it as that member, under
176/// their own access, so the action's API and its own checks decide what
177/// it may do; its answer goes back to the asking device alone.
178pub const MEMBER_OWN_TAG: &str = "host:member-own";
179
180/// [`ActionContract::tags`] entry of an effect a host answers in a render
181/// service of its own rather than in the record's confined app worker:
182/// rendering a timeline to video needs a GPU and a media stack, which a
183/// confined worker has neither of. A host without such a service leaves the
184/// effect out of what its agents are offered.
185pub const HOST_RENDER_TAG: &str = "host:render";
186
187/// [`ActionContract::tags`] entry of an action for [`Audience::Agents`].
188pub const AGENTS_AUDIENCE_TAG: &str = "audience:agents";
189
190/// [`ActionContract::tags`] entry of an action for [`Audience::People`].
191pub const PEOPLE_AUDIENCE_TAG: &str = "audience:people";
192
193/// Who an action is listed for. The app declares it. Most actions are for
194/// [`Everyone`](Self::Everyone), which is the default. An action outside a
195/// listing's audience stays published, resolvable and invocable by address,
196/// under the same permission, confirmation and history rules as any other.
197/// It just isn't offered there.
198#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
199#[serde(rename_all = "snake_case")]
200pub enum Audience {
201    #[default]
202    Everyone,
203    /// Listed for people only: an action whose point is what a person sees
204    /// or does next, such as copying a link to the clipboard. Agent listings
205    /// leave it out.
206    People,
207    /// Listed for agents, scripts and the controls that submit it, never for
208    /// a person to pick (the palette, menus). Examples: reading a message's
209    /// content, revealing a text range by offsets, an edit addressed by an
210    /// internal part number.
211    Agents,
212}
213
214impl Audience {
215    /// Whether people's listings (the palette, menus) offer it.
216    pub const fn reaches_people(self) -> bool {
217        !matches!(self, Self::Agents)
218    }
219
220    /// Whether agents' listings offer it.
221    pub const fn reaches_agents(self) -> bool {
222        !matches!(self, Self::People)
223    }
224
225    /// The contract tag recording it, `None` for everyone.
226    pub const fn tag(self) -> Option<&'static str> {
227        match self {
228            Self::Everyone => None,
229            Self::People => Some(PEOPLE_AUDIENCE_TAG),
230            Self::Agents => Some(AGENTS_AUDIENCE_TAG),
231        }
232    }
233}
234
235/// [`ActionContract::tags`] entry of an action whose result carries content
236/// from outside the user's own data (a web page's text, its logs): data for
237/// the caller to reason about, never instructions to follow.
238pub const UNTRUSTED_CONTENT_TAG: &str = "content:untrusted";
239
240/// [`ActionContract::tags`] entry of an action whose risk, and therefore
241/// whether it needs confirmation, depends on the arguments it is invoked
242/// with (a generic edit that may delete). The publishing host classifies each
243/// invocation; a caller that cannot classify arguments treats the action as
244/// requiring confirmation (see [`ActionContract::advertised_confirmation`]).
245pub const ARGUMENT_RISK_TAG: &str = "confirmation:by-argument";
246
247/// [`ActionContract::tags`] entry of an action that carries its resource's
248/// other actions (a generic typed edit, a group of edits) and is no verb of
249/// its own: what it does is what it carries. Whoever decides for such an
250/// action or words it for a person reads the actions it carries; a lasting
251/// permission is for the action that asked, never for what carried it. See
252/// [`ActionSpec::carrying`](crate::ActionSpec::carrying).
253pub const CARRIER_TAG: &str = "carries:actions";
254
255/// The parameter of a generic field edit that carries the edit.
256pub const FIELD_EDIT_PARAM: &str = "edit";
257
258/// The operation and path of a field edit in its JSON form
259/// (`{path: [{field: name} | {item: id} | {key: k} | {cell: ..}], op, ..}`).
260fn edit_parts(
261    edit: &serde_json::Value,
262) -> Option<(&str, Vec<tilo_action_policy::edits::EditStep<'_>>)> {
263    use tilo_action_policy::edits::EditStep;
264    let op = edit.get("op")?.as_str()?;
265    let path = edit
266        .get("path")?
267        .as_array()?
268        .iter()
269        .map(|step| {
270            let (kind, value) = step.as_object()?.iter().next()?;
271            Some(match kind.as_str() {
272                "field" => EditStep::Field(value.as_str()?),
273                _ => EditStep::Item,
274            })
275        })
276        .collect::<Option<Vec<_>>>()?;
277    Some((op, path))
278}
279
280/// [`ActionContract::tags`] entry of a document action carried out on another
281/// document than the one its resource is kept in ([`crate::ActionSpec::routed`]):
282/// published as an effect so that the app keeping that document applies it,
283/// it is still only a change of a document. It reads none of the content its
284/// resource refers to, so nothing hands it that content, as for any document
285/// change: finding that content reads every part the resource keeps.
286pub const ROUTED_CHANGE_TAG: &str = "routed:document-change";
287
288/// [`ActionContract::tags`] entry of the read-only action that answers, when
289/// invoked with no arguments, the first page of the document an app has
290/// open (a word processor's text, a sheet's used cells, a deck's outline).
291/// A caller that just opened a file reads it through this action without
292/// knowing the app.
293pub const DOCUMENT_READ_TAG: &str = "read:document";
294
295/// [`ActionContract::tags`] entry of a read-only action that reads what its
296/// record holds (a version of it, a review of one) and moves nothing, though
297/// it takes arguments and so is no [`DOCUMENT_READ_TAG`] a caller reads a
298/// document's first page through. Like a document read, it is anyone's to
299/// run who may read the record, and it discloses the record it sits on to
300/// them: History's `review-restore`, a step for agents, is how an agent is
301/// shown a record that has no document read (Terminal's session).
302pub const RESOURCE_READ_TAG: &str = "read:record";
303
304/// [`ActionContract::tags`] entry of the action that opens the file its
305/// `path` parameter names in this app instance, reading it inside the app's
306/// sandbox. A caller that launched the app with a file opens it through
307/// this action, and only through an action that declares it: one taking a
308/// `path` for another purpose (importing an installer image, exporting)
309/// is never guessed from its name.
310pub const OPENS_PATH_TAG: &str = "open:path";
311
312/// Prefix of the [`ActionContract::tags`] entries naming a capability of
313/// the host the action needs: `requires-host:native-paths`. On a host
314/// without it the action is published unavailable, coded
315/// [`HOST_UNSUPPORTED_CODE`], and so refused, wherever it is offered: an
316/// app declares what its action needs once instead of hiding it per host.
317/// A requirement the host does not know is one it lacks.
318pub const REQUIRES_HOST_PREFIX: &str = "requires-host:";
319
320/// [`REQUIRES_HOST_PREFIX`] entry of an action that reaches files through
321/// their file system path, as importing a folder by its path does; browser
322/// storage has no paths.
323pub const REQUIRES_NATIVE_PATHS_TAG: &str = "requires-host:native-paths";
324
325/// [`Availability::Unavailable`] code of an action whose
326/// [`REQUIRES_HOST_PREFIX`] requirement this host cannot meet.
327pub const HOST_UNSUPPORTED_CODE: &str = "host_unsupported";
328
329/// Prefix of the [`ActionContract::tags`] entries naming the file
330/// extensions (lowercase, without the dot) an [`OPENS_PATH_TAG`] action
331/// opens: `open:path-ext:csv`. An opener naming none opens any file.
332pub const OPENS_PATH_EXTENSION_PREFIX: &str = "open:path-ext:";
333
334/// Prefix of the [`ActionContract::tags`] entries naming an outside capability
335/// an action's body hands an effect to with `outside(capability, ...)`:
336/// `outside:youtube.search`. A query naming a kind of an outside service (a
337/// `youtube.channel`) finds, through this, the app's own action that asks its
338/// origin for what the query names — the service's `search` capability.
339pub const OUTSIDE_CAPABILITY_PREFIX: &str = "outside:";
340
341/// The tag of an action an app declares as its search over a remote service (`search: Found`):
342/// the system's search asks it for what its query names, and the records it writes are its
343/// answers.
344pub const SEARCH_TAG: &str = "search";
345
346/// The tag naming the kind an app's declared search answers with, after this prefix
347/// (`search_kind:tl.so.tilo.ebook.Found`): the type its `search:` names.
348pub const SEARCH_KIND_PREFIX: &str = "search_kind:";
349
350/// Facet the executor writes on a change made by a verb its app marks
351/// `#[action(incoming_message)]`: a message someone received. The
352/// `IncomingMessage` trigger fires on it without knowing the app's schema.
353pub const INCOMING_MESSAGE_FACET: &str = "incoming-message";
354/// Contract tag on the declaration of such a verb, so a surface and a
355/// catalogue show it.
356pub const INCOMING_MESSAGE_TAG: &str = "trigger:incoming-message";
357/// Facet a writer sets on a change that copies another member's change (a
358/// service mirroring a message back in, a sync of something written
359/// elsewhere): the actor bytes of the member whose change it copies
360/// (`agent:<id>`, a person's id). A trigger tells a copy of a change from a
361/// new one by it, whoever wrote the copy.
362pub const ORIGIN_FACET: &str = "origin";
363
364/// Facet the executor writes on a change of what only some members read
365/// ([`Action::readers`](crate::Action::readers)): the members who alone read
366/// it, as a JSON list of what each member's changes are named by
367/// ([`MemberId::actor_bytes`](crate::MemberId::actor_bytes)). History lists
368/// the change to them alone ([`reads_change`]).
369pub const READERS_FACET: &str = "readers";
370
371/// The value of a [`READERS_FACET`] naming `readers`.
372#[must_use]
373pub fn readers_facet(readers: &[crate::MemberId]) -> String {
374    let named: Vec<String> = readers.iter().map(reader_name).collect();
375    serde_json::Value::from(named).to_string()
376}
377
378/// How a [`READERS_FACET`] names `member`.
379#[must_use]
380pub fn reader_name(member: &crate::MemberId) -> String {
381    String::from_utf8_lossy(&member.actor_bytes()).into_owned()
382}
383
384/// The names of the members who alone read a change whose context has
385/// `facets` ([`READERS_FACET`]); `None` when every member reads it. A facet
386/// that does not read as a list of names names nobody: never everyone.
387#[must_use]
388pub fn readers_named(facets: &[crate::ActionFacet]) -> Option<Vec<String>> {
389    let facet = facets.iter().find(|facet| facet.key == READERS_FACET)?;
390    Some(tilo_failure::ignored!(
391        "a readers list that does not read names nobody, which keeps the change from everyone",
392        serde_json::from_str(&facet.value).unwrap_or_default()
393    ))
394}
395
396/// Whether `reader` reads a change whose context has `facets`: every member
397/// reads a change no [`READERS_FACET`] marks; one it marks, only the members
398/// it names ([`readers_named`]).
399#[must_use]
400pub fn reads_change(facets: &[crate::ActionFacet], reader: Option<&crate::MemberId>) -> bool {
401    readers_named(facets)
402        .is_none_or(|named| reader.is_some_and(|reader| named.contains(&reader_name(reader))))
403}
404
405/// [`ActionContract::tags`] entry of an action that reaches outside its
406/// document through a queue (a file rename the device carries out) and whose
407/// undo queues the compensating change. It is still an
408/// [`Outside`](ActionKind::Outside) action for the grants deciding it, but it
409/// can be taken back: a person reviewing it is told it changes their work,
410/// not that it sends something away.
411pub const COMPENSATED_UNDO_TAG: &str = "undo:compensated";
412
413/// [`ActionContract::tags`] entry of an action whose document change Undo
414/// reverts but which also loses something Undo cannot bring back (an
415/// account's secret every device forgets): it cannot be taken back, so a
416/// destructive one is confirmed through every API.
417pub const IRREVERSIBLE_TAG: &str = "undo:irreversible";
418
419/// Contract tag on the declaration of a housekeeping verb: a change about the
420/// record rather than to it (`#[action(housekeeping)]`, such as marking a
421/// channel read). An app does these on its own, so nobody is asked to review
422/// or confirm one: one an app emits while History shows a past version is
423/// dropped, and the app does it again once the person is back.
424pub const HOUSEKEEPING_TAG: &str = "change:housekeeping";
425
426/// What one invocation of an action is, for the grants deciding it: its kind,
427/// the one field of its resource it writes when it writes only one (a reply
428/// writes the `comments`), which places it below that field in the tree, and
429/// whether it is privileged ([`RiskLevel::Privileged`]): it exercises
430/// authority over the workspace or others in it, so the person's own grants must
431/// allow it (`tilo_action_policy::Verdict::privileged`).
432#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
433pub struct ActionNeed {
434    pub kind: ActionKind,
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub field: Option<String>,
437    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
438    pub privileged: bool,
439}
440
441/// The node of the resource `resource` (of kind `resource_kind`) the app
442/// `app` publishes, below `base` (a workspace, or the root for a path relative to
443/// one): where a reading of it is decided, as an action of it is at
444/// [`action_node`].
445#[must_use]
446pub fn resource_node(
447    base: &tilo_action_policy::TreePath,
448    app: &str,
449    resource_kind: &str,
450    resource: &str,
451) -> tilo_action_policy::TreePath {
452    let (resource_kind, resource) =
453        if tilo_action_policy::roles::is_workspace_moderation(app, resource)
454            || (resource_kind == "tilo.moderation"
455                && resource == resource_kind
456                && tilo_action_policy::roles::is_workspace_moderation(
457                    app,
458                    tilo_action_policy::roles::WORKSPACE_MODERATION_DOCUMENT,
459                ))
460        {
461            ("chat.workspace", "")
462        } else {
463            (resource_kind, resource)
464        };
465    base.clone().app(app).kind(resource_kind).resource(resource)
466}
467
468/// The node of the action `action` on the resource `resource` (of kind
469/// `resource_kind`) the app `app` publishes, below `base` (a workspace, or the
470/// root for a path relative to one), and below the one `field` it writes if
471/// any: where every API decides it.
472#[must_use]
473pub fn action_node(
474    base: &tilo_action_policy::TreePath,
475    app: &str,
476    resource_kind: &str,
477    resource: &str,
478    field: Option<&str>,
479    action: &str,
480) -> tilo_action_policy::TreePath {
481    let node = resource_node(base, app, resource_kind, resource);
482    match field {
483        Some(field) => node.field(field),
484        None => node,
485    }
486    .action(action)
487}
488
489impl ActionNeed {
490    /// An action of `kind` on the resource as a whole.
491    #[must_use]
492    pub const fn of(kind: ActionKind) -> Self {
493        Self {
494            kind,
495            field: None,
496            privileged: false,
497        }
498    }
499
500    /// An undoable change of the resource's comments: what someone who may
501    /// only comment may do.
502    #[must_use]
503    pub fn comments() -> Self {
504        Self {
505            kind: ActionKind::Undoable,
506            field: Some(tilo_action_policy::roles::COMMENTS_FIELD.to_owned()),
507            privileged: false,
508        }
509    }
510
511    /// An undoable change of reactions, wherever they are: what someone who
512    /// may only comment may do too.
513    #[must_use]
514    pub fn reactions() -> Self {
515        Self {
516            kind: ActionKind::Undoable,
517            field: Some(tilo_action_policy::roles::REACTIONS_FIELD.to_owned()),
518            privileged: false,
519        }
520    }
521
522    /// An undoable change under the resource's `moderation` node: acting on
523    /// other people's content, which Moderators and the owner may do.
524    #[must_use]
525    pub fn moderation() -> Self {
526        Self {
527            kind: ActionKind::Undoable,
528            field: Some(tilo_action_policy::roles::MODERATION_FIELD.to_owned()),
529            privileged: false,
530        }
531    }
532}
533
534const fn undoable() -> ActionKind {
535    ActionKind::Undoable
536}
537
538/// Confirmation required after argument binding and immediately before run.
539#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
540#[serde(remote = "Self", tag = "mode", rename_all = "snake_case")]
541pub enum ConfirmationPolicy {
542    #[default]
543    None,
544    Confirm,
545    /// Requires an exact phrase, useful for irreversible bulk operations.
546    Phrase {
547        phrase: String,
548    },
549}
550
551read_through_json_value!(ConfirmationPolicy);
552
553/// Words that confirm without naming anything: typing one proves only that
554/// the person can read the prompt.
555const GENERIC_CONFIRMATION_WORDS: &[&str] = &[
556    "confirm",
557    "confirmed",
558    "yes",
559    "ok",
560    "okay",
561    "sure",
562    "agree",
563    "i agree",
564    "continue",
565    "proceed",
566    "accept",
567    "delete",
568    "remove",
569    "erase",
570    "wipe",
571    "reset",
572    "destroy",
573];
574
575/// Whether a typed confirmation `phrase` names what the action destroys
576/// (a drive's name, an app's name), rather than a generic word such as
577/// "CONFIRM". A typed phrase is for irreversible, high-risk actions, and
578/// its point is that the person reads what they are about to lose.
579#[must_use]
580pub fn phrase_is_meaningful(phrase: &str) -> bool {
581    let phrase = phrase.trim();
582    !phrase.is_empty()
583        && !GENERIC_CONFIRMATION_WORDS
584            .iter()
585            .any(|word| phrase.eq_ignore_ascii_case(word))
586}
587
588/// What a caller may safely do after losing the completion response.
589#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
590#[serde(rename_all = "snake_case")]
591pub enum RetryPolicy {
592    /// Repeating the call has the same externally observable result.
593    Idempotent,
594    /// The implementation deduplicates calls by invocation id.
595    RetryWithInvocationId,
596    /// Never automatically repeat; the first call may have completed.
597    #[default]
598    AtMostOnce,
599}
600
601/// Completion behavior advertised before invocation.
602#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
603#[serde(remote = "Self", tag = "mode", rename_all = "snake_case")]
604pub enum ExecutionMode {
605    /// Expected to finish in the request/response window.
606    #[default]
607    Immediate,
608    /// Returns a durable job handle and may report progress.
609    Background { cancellable: bool },
610    /// Produces ordered values, each checked against `item_schema`, until a
611    /// terminal result.
612    Streaming {
613        cancellable: bool,
614        item_schema: serde_json::Value,
615    },
616    /// A read that stays current: each item, checked against
617    /// `item_schema`, is the whole result as it is now, sent again whenever
618    /// the provider's answer changes. It ends only when the caller cancels
619    /// it, its permission is withdrawn, or the provider fails.
620    Live { item_schema: serde_json::Value },
621}
622
623read_through_json_value!(ExecutionMode);
624
625impl ExecutionMode {
626    /// Whether a caller may cancel a running invocation.
627    #[must_use]
628    pub const fn cancellable(&self) -> bool {
629        matches!(
630            self,
631            Self::Background { cancellable: true }
632                | Self::Streaming {
633                    cancellable: true,
634                    ..
635                }
636                | Self::Live { .. }
637        )
638    }
639
640    /// What each item of a streaming or live invocation must match; `None`
641    /// for a mode that sends no items.
642    #[must_use]
643    pub const fn item_schema(&self) -> Option<&serde_json::Value> {
644        match self {
645            Self::Streaming { item_schema, .. } | Self::Live { item_schema } => Some(item_schema),
646            Self::Immediate | Self::Background { .. } => None,
647        }
648    }
649}
650
651/// Shape of a successful result. Schemas use JSON Schema so non-Rust callers
652/// do not need a parallel Tilo-only type system.
653#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
654#[serde(remote = "Self", tag = "type", rename_all = "snake_case")]
655pub enum ResultSpec {
656    #[default]
657    None,
658    Json {
659        schema: serde_json::Value,
660    },
661    Resource {
662        resource_kind: String,
663    },
664    Job,
665}
666
667read_through_json_value!(ResultSpec);
668
669/// The fields a write adds beside the answer it declared: the ids it minted
670/// (`minted`), each item it made, with the item's id and the address it is
671/// published under (`made`), and the text it wrote (`wrote`,
672/// [`crate::ActionOutput::wrote`]). What a write answers its caller, whether or
673/// not its action declares a result.
674pub const MADE_FIELDS: [&str; 3] = ["made", "minted", "wrote"];
675
676impl crate::ActionOutput {
677    /// The answer the action declared, without what a write adds beside it
678    /// ([`MADE_FIELDS`]): `None` when it declared nothing.
679    #[must_use]
680    pub fn declared(&self) -> Option<serde_json::Value> {
681        let value = self.value.as_ref()?;
682        let Some(fields) = value.as_object() else {
683            return Some(value.clone());
684        };
685        let kept: serde_json::Map<String, serde_json::Value> = fields
686            .iter()
687            .filter(|(key, _)| !MADE_FIELDS.contains(&key.as_str()))
688            .map(|(key, value)| (key.clone(), value.clone()))
689            .collect();
690        if fields.is_empty() {
691            // An empty answer is the empty result it always was.
692            return Some(serde_json::Value::Object(kept));
693        }
694        // An answer holding only what the write made declared nothing.
695        (!kept.is_empty()).then_some(serde_json::Value::Object(kept))
696    }
697}
698
699impl ResultSpec {
700    /// Check that a completed action returned the shape it advertised.
701    pub fn validate(&self, output: &crate::ActionOutput) -> Result<(), String> {
702        // What the write made rides beside whatever it declared, so an action
703        // with no result may still answer what it created.
704        let declared = output.declared();
705        match self {
706            Self::None | Self::Job if declared.is_none() => Ok(()),
707            Self::None => Err("action declared no result but returned one".into()),
708            // An absent value is `null`: a result its schema lets be null may be
709            // left out by an executor with nothing to report. An answer that
710            // holds only what the write made is still the object it answered.
711            Self::Json { schema } => match declared.or_else(|| output.value.clone()) {
712                Some(value) => crate::params::validate_schema(&value, schema),
713                None => crate::params::validate_schema(&serde_json::Value::Null, schema)
714                    .map_err(|_| "action did not return its declared JSON result".to_string()),
715            },
716            Self::Resource { resource_kind }
717                if !output.resources.is_empty()
718                    && output.resources.iter().all(|address| {
719                        address == resource_kind
720                            || address.strip_prefix(resource_kind).is_some_and(|suffix| {
721                                suffix.starts_with(':') || suffix.starts_with('/')
722                            })
723                    }) =>
724            {
725                Ok(())
726            }
727            Self::Resource { resource_kind } => Err(format!(
728                "action did not return a `{resource_kind}` resource address"
729            )),
730            // The broker assigns and returns the durable invocation id at
731            // admission. Applications must not mint a second, unrelated job
732            // identity merely to satisfy the result validator.
733            Self::Job => Err("job action returned an undeclared terminal value".into()),
734        }
735    }
736}
737
738/// The contract tag of an action that needs its person attending: it opens
739/// a chooser for them, asks them for a credential or a sign-in, or shows
740/// something only they may see. Whoever acts for a person (an agent, a bot,
741/// an app) is always asked first, and no answer allows it unasked, not even
742/// one given for that very action. The person's own click needs no workspace's
743/// consent: the chooser, the sign-in or the reveal in front of them is
744/// their decision, so like an effect of [`OWN_DEVICE_SCOPE`] it needs only
745/// what reading needs and runs only on the device of whoever starts it.
746pub const ATTENDED_TAG: &str = "tilo.attended";
747
748/// The contract tag of an effect that only changes what is on the screen it is
749/// invoked on, as its app declares it (`#[effect(screen)]`): a form it opens, a
750/// panel or a place it shows. It reads and answers nothing. Only the person at
751/// that screen invokes it, and no agent is listed it: anyone else would move
752/// their window and learn nothing ([`ActionContract::only_shows`]).
753pub const SCREEN_TAG: &str = "tilo.screen";
754
755/// The contract tag of an effect of [`SCREEN_TAG`] offered on a row or item
756/// (`#[effect(screen, on = Row)]`), which shows the row it is offered on. It is
757/// answered against its caller's view: anyone else is placed at that row in
758/// their own view of the window, where the person sees their presence, and the
759/// person's own screen does not move. So it is not the person's alone
760/// ([`ActionContract::only_shows`]).
761pub const SCREEN_PLACE_TAG: &str = "tilo.screen.place";
762
763/// The contract tag of an action whose answer is a secret (recovery words, a sealed backup): it
764/// is handed to its caller once, and whatever dispatches it keeps no copy of it, in no cache of
765/// answers, invocation record or history. What is kept says only that it was given
766/// ([`ActionContract::answers_a_secret`]).
767pub const SECRET_ANSWER_TAG: &str = "tilo.answer.secret";
768
769/// The contract tag of an action only the person's root signs: taking a key back, certifying an
770/// agent's. A device that keeps no root of its person's is capped for it
771/// (`tilo_action_policy::Cap`), and the call is answered at one of their devices that keeps it
772/// ([`ActionContract::root_only`]).
773pub const ROOT_ONLY_TAG: &str = "tilo.root-only";
774
775/// The contract tag of an effect whose whole scope is the invoking
776/// person's own device: it touches nothing a workspace shares and no one else
777/// (their clipboard, their own appearance, a network test from their own
778/// browser, a draft of their own). A workspace's grants have nothing to consent
779/// to, so it needs only what reading needs ([`ActionContract::need`]), and
780/// a guest presses it as the workspace's owner does. Whatever shared it goes on
781/// to change goes through that change's own action and is decided there.
782/// Being the invoker's own device, it runs only for the person at the
783/// device it acts on and those acting for them. An effect that reaches
784/// other people (a direct message, a call, a shared live context) is not of
785/// this scope.
786pub const OWN_DEVICE_SCOPE: &str = "tilo.scope.own-device";
787
788/// Complete operational contract copied into every inert descriptor.
789#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
790pub struct ActionContract {
791    #[serde(default)]
792    pub availability: Availability,
793    /// What the action is able to do: read, change only the document, or
794    /// reach outside it. Whether Undo takes it back and whether it asks
795    /// first follow from it. What a grant must allow is its
796    /// [`need`](Self::need), which every API decides with the action's
797    /// place in the published tree: the kind, unless the action's scope
798    /// reaches nothing a workspace governs ([`Self::scoped`]).
799    #[serde(default = "undoable")]
800    pub kind: ActionKind,
801    /// The one field of its resource the action writes, when it writes only
802    /// one: the action sits below that field in the tree, so a grant on the
803    /// field (commenting is writing `comments`) reaches it.
804    #[serde(default, skip_serializing_if = "Option::is_none")]
805    pub field: Option<String>,
806    #[serde(default)]
807    pub risk: RiskLevel,
808    #[serde(default)]
809    pub confirmation: ConfirmationPolicy,
810    #[serde(default)]
811    pub retry: RetryPolicy,
812    #[serde(default)]
813    pub execution: ExecutionMode,
814    #[serde(default)]
815    pub result: ResultSpec,
816    #[serde(default, skip_serializing_if = "Vec::is_empty")]
817    pub tags: Vec<String>,
818    /// The action is heavy enough to run on another of the invoker's devices,
819    /// and how: see [`Offload`]. `None` (the default) runs it where it is
820    /// invoked, always.
821    #[serde(default, skip_serializing_if = "Option::is_none")]
822    pub offload: Option<Offload>,
823    /// The kind of step it takes, as its declaration names it
824    /// ([`crate::StepKind`]): what presence says in the
825    /// reader's language ("Writing in Trip plan", "Schreibt in Trip plan").
826    /// `None` for an action whose declaration names none, whose step reads as
827    /// the part of the record it acts on.
828    #[serde(default, skip_serializing_if = "Option::is_none")]
829    pub step: Option<crate::StepKind>,
830    /// The collection of its resource a create adds to (`writes = issues`),
831    /// when its declaration names one: what it makes, which presence says by
832    /// that collection's own noun ("Creating an issue in Issues"). `None` for
833    /// an action that makes nothing, or whose declaration names no collection.
834    #[serde(default, skip_serializing_if = "Option::is_none")]
835    pub creates: Option<String>,
836    /// The collection whose item the action acts on, when its declaration
837    /// says it acts on one (`item = issues`) and no item is bound to it yet:
838    /// "Open issue" on the tracker itself. It is offered only where an item
839    /// is in hand, bound on that item, so a listing that holds none (a
840    /// palette with nothing selected, an agent's listing of the tracker)
841    /// leaves it out ([`Self::needs_an_item`]). A caller that names the
842    /// action and its item still invokes it here. `None` for an action that
843    /// needs no item, or one already bound to its item.
844    #[serde(default, skip_serializing_if = "Option::is_none")]
845    pub item: Option<String>,
846    /// The arguments the person reads before answering, when the action
847    /// asks first ([`ConfirmationPolicy::Confirm`]): what admission shows on
848    /// its ask, read from the call itself.
849    #[serde(default, skip_serializing_if = "Vec::is_empty")]
850    pub shows: Vec<crate::remote::asked::Shown>,
851    /// What the person types where they answer its ask, in order: a site's user name and
852    /// password, a passphrase. It reaches the action with their approve
853    /// ([`crate::remote::asked::Approval::typed`]), never as an argument of the call, so a secret
854    /// is in no record of it.
855    #[serde(default, skip_serializing_if = "Vec::is_empty")]
856    pub takes: Vec<crate::remote::asked::Take>,
857    /// What it writes beside its own resource, each as the app, kind and verb of the step it
858    /// takes there ([`crate::ActionEffect`]). What a caller reads to know what the action
859    /// changes; what a device reading such a record checks to admit a step the call itself does
860    /// not name; and what a call its app makes for one of its invocations is held to: a call to
861    /// an action named here is covered by the yes that invocation was given and asks nobody
862    /// again, a call to any other action asks as any call does. Never from the call, always from
863    /// this declaration.
864    #[serde(default, skip_serializing_if = "Vec::is_empty")]
865    pub effects: Vec<crate::ActionEffect>,
866}
867
868/// Largest CPU time an [`Offload`] may declare: a compute job's ceiling.
869pub const MAX_OFFLOAD_CPU_TIME_MS: u64 = 5 * 60 * 1_000;
870/// Largest memory an [`Offload`] may declare: a compute job's ceiling.
871pub const MAX_OFFLOAD_MEMORY_BYTES: u64 = 8 * 1024 * 1024 * 1024;
872/// Smallest memory an [`Offload`] may declare: a compute job's floor.
873pub const MIN_OFFLOAD_MEMORY_BYTES: u64 = 16 * 1024 * 1024;
874/// Largest output an [`Offload`] may declare: a compute job's ceiling.
875pub const MAX_OFFLOAD_OUTPUT_BYTES: u64 = 16 * 1024 * 1024;
876
877/// What an offloadable action needs of the device that runs it.
878///
879/// An offloadable action is a pure content transform: its inputs are
880/// content (files the invoker can read), its outputs are content, and the
881/// outputs are a function of the inputs alone, byte for byte, whichever
882/// device computes them. That is what lets the system run it on the
883/// invoker's best-placed device: the action itself is dispatched to that
884/// device's provider — a tilolang app or an engine alike — under the
885/// caller's grants, and answers exactly what a local run returns. When no
886/// device is better placed, or the offload fails for any reason other than
887/// the action's own, it runs locally.
888///
889/// The declaration names no package and no command line: it says what the
890/// work needs of a device, and the action runs there as itself.
891#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
892pub struct Offload {
893    /// Whether it needs a GPU.
894    ///
895    /// Encoded always, false or not: the declaration travels inside frames of
896    /// formats that carry no field names or lengths, where a field skipped
897    /// when absent is read out of the next field's bytes.
898    #[serde(default)]
899    pub gpu: bool,
900    pub cpu_time_ms: u64,
901    /// Memory ceiling, in bytes. The inputs count against it.
902    pub memory_bytes: u64,
903    /// Ceiling on all outputs together, in bytes.
904    pub output_bytes: u64,
905}
906
907impl Offload {
908    /// Why this declaration is outside the bounds of the work a device takes,
909    /// if it is.
910    #[must_use]
911    pub fn validate(&self) -> Vec<String> {
912        let mut errors = Vec::new();
913        if self.cpu_time_ms == 0 || self.cpu_time_ms > MAX_OFFLOAD_CPU_TIME_MS {
914            errors.push("offload cpu time is outside the compute bounds".into());
915        }
916        if !(MIN_OFFLOAD_MEMORY_BYTES..=MAX_OFFLOAD_MEMORY_BYTES).contains(&self.memory_bytes) {
917            errors.push("offload memory is outside the compute bounds".into());
918        }
919        if self.output_bytes == 0 || self.output_bytes > MAX_OFFLOAD_OUTPUT_BYTES {
920            errors.push("offload output is outside the compute bounds".into());
921        }
922        errors
923    }
924}
925
926impl Default for ActionContract {
927    fn default() -> Self {
928        Self {
929            availability: Availability::Available,
930            kind: ActionKind::Undoable,
931            field: None,
932            risk: RiskLevel::Low,
933            confirmation: ConfirmationPolicy::None,
934            retry: RetryPolicy::AtMostOnce,
935            execution: ExecutionMode::Immediate,
936            result: ResultSpec::None,
937            tags: Vec::new(),
938            offload: None,
939            step: None,
940            creates: None,
941            item: None,
942            shows: Vec::new(),
943            takes: Vec::new(),
944            effects: Vec::new(),
945        }
946    }
947}
948
949impl ActionContract {
950    /// Whether it declares the call of `provider`'s `address` as one of its own steps
951    /// ([`Self::effects`]).
952    #[must_use]
953    pub fn declares(&self, provider: &str, address: &crate::ActionAddress) -> bool {
954        self.effects.iter().any(|effect| {
955            effect.app == provider
956                && effect.kind == address.resource
957                && effect.verb == address.action
958        })
959    }
960
961    /// What an invocation needs when its value does not say otherwise: its
962    /// kind, [`scoped`](Self::scoped).
963    #[must_use]
964    pub fn need(&self) -> ActionNeed {
965        self.scoped(ActionNeed {
966            kind: self.kind,
967            field: self.field.clone(),
968            privileged: self.risk == RiskLevel::Privileged,
969        })
970    }
971
972    /// The authority `need` asks of a workspace once this action's scope is
973    /// accounted for. The kind says what the action does (whether Undo takes
974    /// it back, whether it asks first); the need says what a grant must
975    /// allow, and the scope is where they part: an outside effect on the
976    /// person's own device ([`OWN_DEVICE_SCOPE`], [`ATTENDED_TAG`]) reaches
977    /// nothing a workspace's grants govern, so it needs only what reading
978    /// needs. Every change of a record is the workspace's to decide.
979    #[must_use]
980    pub fn scoped(&self, mut need: ActionNeed) -> ActionNeed {
981        if need.kind == ActionKind::Outside && self.runs_on_invokers_device() {
982            need.kind = ActionKind::Read;
983        }
984        need
985    }
986
987    /// Safe defaults for a presentation-only operation.
988    pub fn view() -> Self {
989        Self {
990            risk: RiskLevel::None,
991            kind: ActionKind::Read,
992            retry: RetryPolicy::Idempotent,
993            ..Self::default()
994        }
995    }
996
997    /// A view whose result stays current ([`ExecutionMode::Live`]), each
998    /// item matching `item_schema`.
999    pub fn live_view(item_schema: serde_json::Value) -> Self {
1000        Self {
1001            execution: ExecutionMode::Live { item_schema },
1002            ..Self::view()
1003        }
1004    }
1005
1006    /// Whether the action's result stays current ([`ExecutionMode::Live`]).
1007    #[must_use]
1008    pub const fn is_live(&self) -> bool {
1009        matches!(self.execution, ExecutionMode::Live { .. })
1010    }
1011
1012    /// The defaults for an operation of `operation`'s kind: a view reads, a
1013    /// document operation changes only the document, an effect reaches
1014    /// outside it.
1015    pub fn for_operation(operation: OperationKind) -> Self {
1016        match operation {
1017            OperationKind::View => Self::view(),
1018            OperationKind::Document => Self::default(),
1019            OperationKind::Effect => Self {
1020                kind: ActionKind::Outside,
1021                ..Self::default()
1022            },
1023        }
1024    }
1025
1026    /// Whether the effect's scope is the invoking person's own device and
1027    /// nothing shared. See [`OWN_DEVICE_SCOPE`].
1028    pub fn is_own_device(&self) -> bool {
1029        self.tags.iter().any(|tag| tag == OWN_DEVICE_SCOPE)
1030    }
1031
1032    /// Whether the action needs its person attending. See [`ATTENDED_TAG`].
1033    pub fn is_attended(&self) -> bool {
1034        self.tags.iter().any(|tag| tag == ATTENDED_TAG)
1035    }
1036
1037    /// Whether the action acts on the device of whoever invokes it, so only
1038    /// the person at that device (and those acting for them) runs it: an
1039    /// effect of [`OWN_DEVICE_SCOPE`] or one its person attends
1040    /// ([`ATTENDED_TAG`]).
1041    pub fn runs_on_invokers_device(&self) -> bool {
1042        self.is_own_device() || self.is_attended()
1043    }
1044
1045    /// Whether an effect under this contract only changes what is on the
1046    /// screen it is invoked on, as its app declares ([`SCREEN_TAG`]): a form it
1047    /// opens, a panel or a place it shows. Only the person at that screen
1048    /// invokes it; for anyone else it would move their window and tell the
1049    /// caller nothing. Nothing else about the contract decides it: an effect
1050    /// that reads and answers nothing may still write, and is decided as
1051    /// what it declares.
1052    pub fn only_shows(&self) -> bool {
1053        self.tags.iter().any(|tag| tag == SCREEN_TAG) && !self.shows_a_place()
1054    }
1055
1056    /// Whether only the person's root signs it ([`ROOT_ONLY_TAG`]).
1057    pub fn root_only(&self) -> bool {
1058        self.tags.iter().any(|tag| tag == ROOT_ONLY_TAG)
1059    }
1060
1061    /// Whether its answer is a secret, handed over once and kept nowhere ([`SECRET_ANSWER_TAG`]).
1062    pub fn answers_a_secret(&self) -> bool {
1063        self.tags.iter().any(|tag| tag == SECRET_ANSWER_TAG)
1064    }
1065
1066    /// Whether the effect shows the row it is offered on, answered against its
1067    /// caller's view ([`SCREEN_PLACE_TAG`]).
1068    pub fn shows_a_place(&self) -> bool {
1069        self.tags.iter().any(|tag| tag == SCREEN_PLACE_TAG)
1070    }
1071
1072    /// Safe defaults for an effect that only changes what is on the screen it
1073    /// is invoked on ([`Self::only_shows`]).
1074    pub fn screen() -> Self {
1075        let mut contract = Self::view();
1076        contract.tags.push(SCREEN_TAG.to_owned());
1077        contract
1078    }
1079
1080    /// Who the action is listed for, as its tags record it. See [`Audience`].
1081    pub fn audience(&self) -> Audience {
1082        if self.tags.iter().any(|tag| tag == AGENTS_AUDIENCE_TAG) {
1083            Audience::Agents
1084        } else if self.tags.iter().any(|tag| tag == PEOPLE_AUDIENCE_TAG) {
1085            Audience::People
1086        } else {
1087            Audience::Everyone
1088        }
1089    }
1090
1091    /// Record `audience` in the tags, replacing any audience before it.
1092    pub fn set_audience(&mut self, audience: Audience) {
1093        self.tags
1094            .retain(|tag| tag != AGENTS_AUDIENCE_TAG && tag != PEOPLE_AUDIENCE_TAG);
1095        if let Some(tag) = audience.tag() {
1096            self.tags.push(tag.to_owned());
1097        }
1098    }
1099
1100    /// Whether people's listings offer it. See [`Audience::reaches_people`].
1101    pub fn reaches_people(&self) -> bool {
1102        self.audience().reaches_people()
1103    }
1104
1105    /// Whether agents' listings offer it. See [`Audience::reaches_agents`].
1106    pub fn reaches_agents(&self) -> bool {
1107        self.audience().reaches_agents()
1108    }
1109
1110    /// Whether it acts on an item it has not been given ([`Self::item`]):
1111    /// what only a place holding an item offers.
1112    #[must_use]
1113    pub fn needs_an_item(&self) -> bool {
1114        self.item.is_some()
1115    }
1116
1117    /// Whether a listing that holds no item offers it to a person: one for
1118    /// people that needs no item ([`Self::needs_an_item`]). The palette with
1119    /// nothing selected, a window's controls and a search list this.
1120    #[must_use]
1121    pub fn offered_to_people(&self) -> bool {
1122        self.reaches_people() && !self.needs_an_item()
1123    }
1124
1125    /// Whether a person may take it from a list now: offered to people
1126    /// ([`Self::offered_to_people`]) and with something to act on in the
1127    /// window's state. One that can only say why it cannot run (an event's
1128    /// `Invite` with no event selected) takes no row: the person who typed its
1129    /// name meant the thing that works.
1130    #[must_use]
1131    pub fn a_person_can_take_now(&self) -> bool {
1132        self.offered_to_people() && self.availability.is_available()
1133    }
1134
1135    /// [`Self::offered_to_people`] for agents: what an agent's listing of a
1136    /// resource offers it, an action that needs an item being offered on
1137    /// the item.
1138    #[must_use]
1139    pub fn offered_to_agents(&self) -> bool {
1140        self.reaches_agents() && !self.needs_an_item()
1141    }
1142
1143    /// Whether the action reads the open document's first page. See
1144    /// [`DOCUMENT_READ_TAG`].
1145    pub fn reads_document(&self) -> bool {
1146        self.tags.iter().any(|tag| tag == DOCUMENT_READ_TAG)
1147    }
1148
1149    /// Whether the action reads what its record holds and moves nothing: a
1150    /// document read ([`DOCUMENT_READ_TAG`]) or another read of the record's
1151    /// state ([`RESOURCE_READ_TAG`]).
1152    pub fn reads_resource(&self) -> bool {
1153        self.reads_document() || self.tags.iter().any(|tag| tag == RESOURCE_READ_TAG)
1154    }
1155
1156    /// Whether a view under this contract shows its resource to callers other
1157    /// than its publisher: a read of the record ([`Self::reads_resource`]) or
1158    /// the caller's own presence view. Any other view changes only what
1159    /// its caller sees, and keeps the resource it alone discloses private
1160    /// (the action directory's disclosure, `agent_disclosure`).
1161    pub fn discloses_resource(&self) -> bool {
1162        self.reads_resource() || self.is_presence_view()
1163    }
1164
1165    /// Which of a resource's views the action directory discloses it
1166    /// through, lowest first and the first of equals: a document read, then
1167    /// another read of the record, then any other view.
1168    pub fn disclosure_rank(&self) -> u8 {
1169        if self.reads_document() {
1170            0
1171        } else if self.reads_resource() {
1172            1
1173        } else {
1174            2
1175        }
1176    }
1177
1178    /// Whether the action opens the file its `path` names. See
1179    /// [`OPENS_PATH_TAG`].
1180    pub fn opens_path(&self) -> bool {
1181        self.tags.iter().any(|tag| tag == OPENS_PATH_TAG)
1182    }
1183
1184    /// The file extensions an [`opens_path`](Self::opens_path) action is
1185    /// declared for; none means any file. See
1186    /// [`OPENS_PATH_EXTENSION_PREFIX`].
1187    pub fn opened_extensions(&self) -> impl Iterator<Item = &str> {
1188        self.tags
1189            .iter()
1190            .filter_map(|tag| tag.strip_prefix(OPENS_PATH_EXTENSION_PREFIX))
1191    }
1192
1193    /// Whether the action's result carries content from outside the user's
1194    /// own data. See [`UNTRUSTED_CONTENT_TAG`].
1195    pub fn carries_untrusted_content(&self) -> bool {
1196        self.tags.iter().any(|tag| tag == UNTRUSTED_CONTENT_TAG)
1197    }
1198
1199    /// Whether the action carries its resource's other actions and is no
1200    /// verb of its own. See [`CARRIER_TAG`].
1201    #[must_use]
1202    pub fn carries_actions(&self) -> bool {
1203        self.tags.iter().any(|tag| tag == CARRIER_TAG)
1204    }
1205
1206    /// The outside capabilities the action hands an effect to
1207    /// (`youtube.search`), as its tags record them. See
1208    /// [`OUTSIDE_CAPABILITY_PREFIX`].
1209    pub fn outside_capabilities(&self) -> impl Iterator<Item = &str> {
1210        self.tags
1211            .iter()
1212            .filter_map(|tag| tag.strip_prefix(OUTSIDE_CAPABILITY_PREFIX))
1213    }
1214
1215    /// Whether the action, once taken, can be undone: the host's undo
1216    /// reverts an [`Undoable`](ActionKind::Undoable) change, and an outside
1217    /// one declared with its compensation ([`COMPENSATED_UNDO_TAG`]) is
1218    /// undone by queueing it. One that also loses what Undo cannot bring
1219    /// back ([`IRREVERSIBLE_TAG`]) cannot.
1220    pub fn can_be_undone(&self) -> bool {
1221        (self.kind == ActionKind::Undoable
1222            || self.tags.iter().any(|tag| tag == COMPENSATED_UNDO_TAG))
1223            && !self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG)
1224    }
1225
1226    /// Whether an invocation of this action must be confirmed before it
1227    /// runs: its risk asks for it and Undo cannot take it back
1228    /// ([`RiskLevel::requires_confirmation_when`]).
1229    #[must_use]
1230    pub fn requires_confirmation(&self) -> bool {
1231        self.risk.requires_confirmation_when(self.can_be_undone())
1232    }
1233
1234    /// Bring the declared policy in line with the risk and whether Undo
1235    /// takes the action back: a deletion Undo takes back asks nothing, one
1236    /// it cannot asks with a click. An explicit typed phrase, and the policy
1237    /// of any other risk, stay as declared. Every builder that changes the
1238    /// risk, the undo or the tags calls this, so the order they are called
1239    /// in never decides whether a person is asked.
1240    ///
1241    /// The kind is read through
1242    /// [`settled_kind`](Self::settled_kind), so a deletion built before the
1243    /// kind that makes it undoable still ends up asking nothing, and one a
1244    /// declaration says reaches outside still asks.
1245    pub fn settle_confirmation(&mut self) {
1246        if self.risk != RiskLevel::Destructive {
1247            return;
1248        }
1249        let undoable = undo_takes_back(
1250            self.settled_kind(),
1251            ChangeKind::Content,
1252            self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG),
1253        );
1254        match (&self.confirmation, undoable) {
1255            (ConfirmationPolicy::Confirm, true) => self.confirmation = ConfirmationPolicy::None,
1256            (ConfirmationPolicy::None, false) => self.confirmation = ConfirmationPolicy::Confirm,
1257            _ => {}
1258        }
1259    }
1260
1261    /// The kind this contract says the action is, where [`kind`](Self::kind)
1262    /// cannot say it alone: a change to its own document is undoable unless
1263    /// it keeps something Undo cannot bring back ([`IRREVERSIBLE_TAG`]), or
1264    /// unless it reaches outside and queues its compensation
1265    /// ([`COMPENSATED_UNDO_TAG`]).
1266    #[must_use]
1267    pub fn settled_kind(&self) -> ActionKind {
1268        let irreversible = self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG);
1269        let undoable = self.kind == ActionKind::Undoable
1270            || self.tags.iter().any(|tag| tag == COMPENSATED_UNDO_TAG);
1271        if undoable && !irreversible {
1272            return ActionKind::Undoable;
1273        }
1274        if self.kind == ActionKind::Undoable {
1275            return ActionKind::Outside;
1276        }
1277        self.kind
1278    }
1279
1280    /// The kind of a deletion, which has to say which it is: what its kind
1281    /// settles to, less where Undo cannot take the change back at all.
1282    #[must_use]
1283    pub fn deletion_kind(&self) -> ActionKind {
1284        let irreversible = self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG);
1285        let kind = self.settled_kind();
1286        if undo_takes_back(kind, ChangeKind::Content, irreversible) {
1287            kind
1288        } else {
1289            ActionKind::Outside
1290        }
1291    }
1292
1293    /// Whether confirmation depends on the invocation's arguments. See
1294    /// [`ARGUMENT_RISK_TAG`].
1295    pub fn confirmation_depends_on_arguments(&self) -> bool {
1296        self.tags.iter().any(|tag| tag == ARGUMENT_RISK_TAG)
1297    }
1298
1299    /// The confirmation a caller that cannot classify arguments must assume:
1300    /// the declared policy, or [`ConfirmationPolicy::Confirm`] for an action
1301    /// whose risk depends on its arguments. A trust boundary that only sees
1302    /// this inert contract (the session broker) waits for it; the publishing
1303    /// host, which can classify, asks
1304    /// [`ActionSpec::confirmation_for_json`](crate::ActionSpec::confirmation_for_json).
1305    pub fn advertised_confirmation(&self) -> ConfirmationPolicy {
1306        // An action whose risk depends on its arguments is a generic edit or
1307        // a verb that may delete: what Undo takes back asks nothing,
1308        // whichever value it carries.
1309        if self.confirmation == ConfirmationPolicy::None
1310            && self.confirmation_depends_on_arguments()
1311            && !self.can_be_undone()
1312        {
1313            ConfirmationPolicy::Confirm
1314        } else {
1315            self.confirmation.clone()
1316        }
1317    }
1318
1319    /// Whether an invocation with `argument` asks the person an agent acts
1320    /// for, whatever their broader answers allow: it needs a confirmation
1321    /// ([`Self::confirmation_for_argument`]) or its person attending
1322    /// ([`Self::is_attended`]).
1323    pub fn asks_for_argument(&self, argument: Option<&str>) -> bool {
1324        self.is_attended() || self.confirmation_for_argument(argument) != ConfirmationPolicy::None
1325    }
1326
1327    /// The confirmation an invocation with `argument` (the wire argument:
1328    /// typed JSON behind [`ARGUMENTS_JSON_PREFIX`](crate::ARGUMENTS_JSON_PREFIX))
1329    /// needs, decided without the publishing app's code: the declared
1330    /// policy; for a generic field edit, the edit itself read by
1331    /// [`tilo_action_policy::edits::field_edit_asks`]; for any other action
1332    /// whose risk depends on its arguments, [`Self::advertised_confirmation`].
1333    pub fn confirmation_for_argument(&self, argument: Option<&str>) -> ConfirmationPolicy {
1334        if self.confirmation != ConfirmationPolicy::None
1335            || !self.confirmation_depends_on_arguments()
1336            || !self
1337                .tags
1338                .iter()
1339                .any(|tag| tag == tilo_action_policy::edits::FIELD_EDIT_TAG)
1340        {
1341            return self.advertised_confirmation();
1342        }
1343        let edit = argument
1344            .and_then(|text| text.strip_prefix(crate::ARGUMENTS_JSON_PREFIX))
1345            .and_then(|json| serde_json::from_str::<serde_json::Value>(json).ok())
1346            .and_then(|arguments| arguments.get(FIELD_EDIT_PARAM).cloned());
1347        let tagged = |prefix: &str| -> Vec<&str> {
1348            self.tags
1349                .iter()
1350                .filter_map(|tag| tag.strip_prefix(prefix))
1351                .collect()
1352        };
1353        let quiet = tagged(tilo_action_policy::edits::QUIET_REMOVAL_TAG);
1354        let guarded = tagged(tilo_action_policy::edits::GUARDED_FIELD_TAG);
1355        let weakening: Vec<_> = tagged(tilo_action_policy::edits::WEAKENING_FIELD_TAG)
1356            .into_iter()
1357            .filter_map(tilo_action_policy::edits::WeakeningField::parse)
1358            .collect();
1359        let value = edit
1360            .as_ref()
1361            .and_then(|edit| edit.get("value"))
1362            .map(serde_json::Value::to_string);
1363        // Whatever a generic edit of an undoable record removes, Undo puts
1364        // back: only a field that exposes the person or weakens their
1365        // security still asks.
1366        let undoable = self.can_be_undone();
1367        let asks = |op: &str, path: &[tilo_action_policy::edits::EditStep<'_>]| {
1368            if undoable {
1369                tilo_action_policy::edits::guarded_at(path, &guarded)
1370            } else {
1371                tilo_action_policy::edits::field_edit_asks(op, path, &quiet, &guarded)
1372            }
1373        };
1374        match edit.as_ref().and_then(edit_parts) {
1375            Some((op, path))
1376                if !asks(op, &path)
1377                    && !tilo_action_policy::edits::weakening_edit(
1378                        op,
1379                        &path,
1380                        value.as_deref(),
1381                        &weakening,
1382                    ) =>
1383            {
1384                ConfirmationPolicy::None
1385            }
1386            // An edit nobody can read asks, unless the record has no field
1387            // that exposes the person or weakens their security and Undo
1388            // takes back whatever it changes.
1389            None if undoable && guarded.is_empty() && weakening.is_empty() => {
1390                ConfirmationPolicy::None
1391            }
1392            _ => ConfirmationPolicy::Confirm,
1393        }
1394    }
1395
1396    /// Validate the contract as inert protocol data. This is intentionally
1397    /// usable at both publication ends: a well-behaved app checks before it
1398    /// sends, and the broker repeats the check at its trust boundary.
1399    pub fn validate_declaration(&self) -> Vec<String> {
1400        let mut errors = Vec::new();
1401        if let Availability::Unavailable { code, reason } = &self.availability
1402            && (code.trim().is_empty() || reason.trim().is_empty())
1403        {
1404            errors.push("unavailable action needs a code and reason".into());
1405        }
1406        if self.requires_confirmation() && matches!(self.confirmation, ConfirmationPolicy::None) {
1407            errors.push("consequential action requires confirmation".into());
1408        }
1409        if let ConfirmationPolicy::Phrase { phrase } = &self.confirmation {
1410            if phrase.trim().is_empty() {
1411                errors.push("confirmation phrase must not be empty".into());
1412            } else if !phrase_is_meaningful(phrase) {
1413                errors.push(format!(
1414                    "confirmation phrase \"{phrase}\" says nothing about what is lost; name it (the drive, the app, the item)"
1415                ));
1416            }
1417            if self.can_be_undone() {
1418                errors.push(
1419                    "an action Undo takes back is never confirmed by typing; it runs at once and offers Undo".into(),
1420                );
1421            }
1422        }
1423        if matches!(self.retry, RetryPolicy::RetryWithInvocationId) {
1424            errors.push(
1425                "retry_with_invocation_id requires a caller-supplied deduplication key, which this transport does not yet expose".into(),
1426            );
1427        }
1428        if matches!(self.execution, ExecutionMode::Background { .. })
1429            && matches!(self.result, ResultSpec::None)
1430        {
1431            errors.push("background action must declare a result or job".into());
1432        }
1433        if matches!(self.execution, ExecutionMode::Immediate)
1434            && matches!(self.result, ResultSpec::Job)
1435        {
1436            errors.push("immediate action cannot declare a background job result".into());
1437        }
1438        if let Some(item_schema) = self.execution.item_schema()
1439            && let Err(reason) = crate::params::validate_schema_definition(item_schema)
1440        {
1441            errors.push(format!("invalid streaming item {reason}"));
1442        }
1443        if self.is_live() && self.kind != ActionKind::Read {
1444            errors.push("a live result must be a read".into());
1445        }
1446        if let ResultSpec::Json { schema } = &self.result
1447            && let Err(reason) = crate::params::validate_schema_definition(schema)
1448        {
1449            errors.push(format!("invalid result {reason}"));
1450        }
1451        if self.tags.iter().any(|tag| tag.trim().is_empty()) {
1452            errors.push("contract tags must not be empty".into());
1453        }
1454        let unique_tags = self.tags.iter().collect::<std::collections::HashSet<_>>();
1455        if unique_tags.len() != self.tags.len() {
1456            errors.push("contract tags must be unique".into());
1457        }
1458        if let Some(offload) = &self.offload {
1459            errors.extend(offload.validate());
1460            // A transform of content: it changes nothing where it runs.
1461            if self.kind != ActionKind::Read {
1462                errors.push("an offloadable action must be a read".into());
1463            }
1464        }
1465        errors
1466    }
1467}
1468
1469#[cfg(test)]
1470mod tests {
1471    use super::*;
1472
1473    fn risk_level_keeps_existing_compact_wire_discriminants() {
1474        // `RiskLevel` appears in recorded action contracts. Postcard encodes
1475        // enum variants by ordinal, so the old values are a compatibility
1476        // boundary rather than an implementation detail.
1477        assert_eq!(postcard::to_allocvec(&RiskLevel::None).unwrap(), vec![0]);
1478        assert_eq!(postcard::to_allocvec(&RiskLevel::Low).unwrap(), vec![1]);
1479        assert_eq!(
1480            postcard::to_allocvec(&RiskLevel::Destructive).unwrap(),
1481            vec![2]
1482        );
1483        assert_eq!(
1484            postcard::to_allocvec(&RiskLevel::Privileged).unwrap(),
1485            vec![3]
1486        );
1487        assert_eq!(
1488            postcard::from_bytes::<RiskLevel>(&[2]).unwrap(),
1489            RiskLevel::Destructive
1490        );
1491        assert_eq!(
1492            postcard::from_bytes::<RiskLevel>(&[3]).unwrap(),
1493            RiskLevel::Privileged
1494        );
1495    }
1496
1497    fn broker_owned_job_identity_is_not_a_second_application_result() {
1498        assert!(
1499            ResultSpec::Job
1500                .validate(&crate::ActionOutput::default())
1501                .is_ok()
1502        );
1503        assert!(
1504            ResultSpec::Job
1505                .validate(&crate::ActionOutput {
1506                    value: Some(serde_json::json!("a second job id")),
1507                    resources: Vec::new(),
1508                })
1509                .is_err()
1510        );
1511    }
1512
1513    /// A write answers what it made beside whatever it declared, so an
1514    /// action that declares no result may still say which items it created —
1515    /// and one that declares a result is judged on that result alone.
1516    #[test]
1517    fn what_a_write_made_rides_beside_the_result_it_declared() {
1518        let made = crate::ActionOutput {
1519            value: Some(serde_json::json!({
1520                "made": [{"id": "a1", "address": "notes.page/pages/a1"}],
1521                "minted": ["a1"],
1522            })),
1523            resources: vec!["notes.page/pages/a1".into()],
1524        };
1525        assert!(ResultSpec::None.validate(&made).is_ok());
1526        assert!(ResultSpec::Job.validate(&made).is_ok());
1527        let schema = serde_json::json!({"type": "object", "required": ["count"],
1528            "properties": {"count": {"type": "integer"}}});
1529        let with_count = crate::ActionOutput {
1530            value: Some(serde_json::json!({
1531                "count": 2,
1532                "made": [{"id": "a1", "address": "notes.page/pages/a1"}],
1533            })),
1534            resources: Vec::new(),
1535        };
1536        assert!(ResultSpec::Json { schema }.validate(&with_count).is_ok());
1537        assert!(
1538            ResultSpec::None
1539                .validate(&crate::ActionOutput {
1540                    value: Some(serde_json::json!({"count": 2})),
1541                    resources: Vec::new(),
1542                })
1543                .is_err(),
1544            "a result an action did not declare is still refused"
1545        );
1546    }
1547
1548    tilo_test_env::scenario! {
1549        fn a_contract_declares_consent_audience_and_wire_shape;
1550
1551        phase an_attended_or_own_device_effect_needs_no_workspace_consent;
1552        // An outside effect the person attends (their chooser, a sign-in) or
1553        // one on their own device needs only what reading needs, so a workspace's
1554        // guest starts it with no workspace consent; it runs on the device of
1555        // whoever starts it. Any other outside effect still reaches outside.
1556        {
1557            let outside = ActionContract::for_operation(OperationKind::Effect);
1558            assert_eq!(outside.need().kind, ActionKind::Outside);
1559            assert!(!outside.runs_on_invokers_device());
1560            for tag in [ATTENDED_TAG, OWN_DEVICE_SCOPE] {
1561                let mut contract = outside.clone();
1562                contract.tags.push(tag.to_owned());
1563                assert_eq!(contract.need().kind, ActionKind::Read, "{tag}");
1564                assert!(contract.runs_on_invokers_device(), "{tag}");
1565            }
1566        }
1567
1568        phase undoable_deletes_ask_nothing_and_typed_phrases_name_what_is_lost;
1569        // Undoable actions run at once and offer Undo, with no confirmation.
1570        // A typed confirmation is for irreversible, high-risk actions only, and
1571        // its word names what is lost (the item's name), never a generic word.
1572        {
1573            // A deletion Undo takes back asks nothing, whichever order the
1574            // contract learned it was a deletion and that Undo takes it back.
1575            let mut contract = ActionContract {
1576                risk: RiskLevel::Destructive,
1577                ..ActionContract::default()
1578            };
1579            contract.settle_confirmation();
1580            assert_eq!(contract.confirmation, ConfirmationPolicy::None);
1581            assert!(!contract.requires_confirmation());
1582            assert!(contract.validate_declaration().is_empty());
1583            let mut compensated = ActionContract {
1584                risk: RiskLevel::Destructive,
1585                confirmation: ConfirmationPolicy::Confirm,
1586                tags: vec![COMPENSATED_UNDO_TAG.to_owned()],
1587                ..ActionContract::default()
1588            };
1589            compensated.settle_confirmation();
1590            assert_eq!(compensated.confirmation, ConfirmationPolicy::None);
1591
1592            // One Undo cannot take back still asks, with a click: an effect
1593            // reaches outside the state its resource owns, so nothing brings
1594            // back what it did, and the declaration says as much by naming it.
1595            let mut irreversible = ActionContract {
1596                kind: ActionKind::Outside,
1597                risk: RiskLevel::Destructive,
1598                ..ActionContract::default()
1599            };
1600            irreversible.settle_confirmation();
1601            assert_eq!(irreversible.confirmation, ConfirmationPolicy::Confirm);
1602            assert!(irreversible.requires_confirmation());
1603            // Nor can it take back what the document change lost outside it (a
1604            // secret every device forgot), however the change itself reverts.
1605            let mut forgets = ActionContract {
1606                kind: ActionKind::Outside,
1607                risk: RiskLevel::Destructive,
1608                tags: vec![IRREVERSIBLE_TAG.to_owned()],
1609                ..ActionContract::default()
1610            };
1611            forgets.settle_confirmation();
1612            assert_eq!(forgets.confirmation, ConfirmationPolicy::Confirm);
1613            // Crossing a security boundary or exporting private data asks even
1614            // when Undo would take the change back.
1615            assert!(RiskLevel::Privileged.requires_confirmation_when(true));
1616            assert!(RiskLevel::Sensitive.requires_confirmation_when(true));
1617
1618            // A generic edit of an undoable record asks nothing for any value.
1619            let edit = ActionContract {
1620                tags: vec![
1621                    ARGUMENT_RISK_TAG.to_owned(),
1622                    tilo_action_policy::edits::FIELD_EDIT_TAG.to_owned(),
1623                ],
1624                ..ActionContract::default()
1625            };
1626            assert_eq!(edit.advertised_confirmation(), ConfirmationPolicy::None);
1627            assert_eq!(
1628                edit.confirmation_for_argument(None),
1629                ConfirmationPolicy::None
1630            );
1631
1632            // A typed phrase is refused on an undoable action, and when it names
1633            // nothing.
1634            let phrase = |phrase: &str, kind: ActionKind| ActionContract {
1635                risk: RiskLevel::Destructive,
1636                kind,
1637                confirmation: ConfirmationPolicy::Phrase {
1638                    phrase: phrase.into(),
1639                },
1640                ..ActionContract::default()
1641            };
1642            assert!(
1643                phrase("Hacker News", ActionKind::Undoable)
1644                    .validate_declaration()
1645                    .iter()
1646                    .any(|error| error.contains("Undo takes back"))
1647            );
1648            for generic in ["CONFIRM", "yes", "Delete"] {
1649                assert!(
1650                    phrase(generic, ActionKind::Outside)
1651                        .validate_declaration()
1652                        .iter()
1653                        .any(|error| error.contains("says nothing")),
1654                    "{generic}"
1655                );
1656            }
1657            assert!(
1658                phrase("nvme0n1", ActionKind::Outside)
1659                    .validate_declaration()
1660                    .is_empty()
1661            );
1662            assert!(phrase_is_meaningful("Windows 11"));
1663            assert!(!phrase_is_meaningful(" confirm "));
1664        }
1665
1666        phase an_actions_audience_decides_whose_listings_offer_it;
1667        // An action is for everyone unless the app says otherwise, and the
1668        // audience it says replaces the one before: people's listings leave out
1669        // what is for agents, agents' leave out what is for people.
1670        {
1671            let mut contract = ActionContract::default();
1672            assert_eq!(contract.audience(), Audience::Everyone);
1673            assert!(contract.reaches_people() && contract.reaches_agents());
1674            contract.set_audience(Audience::Agents);
1675            assert_eq!(contract.audience(), Audience::Agents);
1676            assert!(!contract.reaches_people() && contract.reaches_agents());
1677            contract.set_audience(Audience::People);
1678            assert_eq!(contract.audience(), Audience::People);
1679            assert!(contract.reaches_people() && !contract.reaches_agents());
1680            assert_eq!(
1681                contract
1682                    .tags
1683                    .iter()
1684                    .filter(|tag| tag.starts_with("audience:"))
1685                    .count(),
1686                1,
1687                "one audience at a time: {:?}",
1688                contract.tags
1689            );
1690            contract.set_audience(Audience::Everyone);
1691            assert!(
1692                contract
1693                    .tags
1694                    .iter()
1695                    .all(|tag| !tag.starts_with("audience:"))
1696            );
1697        }
1698
1699        phase the_contract_keeps_wire_discriminants_and_one_job_identity;
1700        // Risk levels keep their compact wire discriminants and a broker-owned job identity is not a
1701        // second application result.
1702        // Runs each phase below in order; every phase builds its own fixture.
1703        {
1704            risk_level_keeps_existing_compact_wire_discriminants();
1705            broker_owned_job_identity_is_not_a_second_application_result();
1706        }
1707
1708        phase only_a_nullable_json_result_may_be_left_out;
1709        {
1710            let nullable = ResultSpec::Json {
1711                schema: serde_json::json!({"type": ["string", "null"]}),
1712            };
1713            let required = ResultSpec::Json {
1714                schema: serde_json::json!({"type": "string"}),
1715            };
1716            let none = crate::ActionOutput::default();
1717            assert!(nullable.validate(&none).is_ok());
1718            assert!(required.validate(&none).is_err());
1719            let text = crate::ActionOutput {
1720                value: Some(serde_json::json!("changed")),
1721                resources: Vec::new(),
1722            };
1723            assert!(nullable.validate(&text).is_ok());
1724            assert!(required.validate(&text).is_ok());
1725        }
1726
1727        phase offload_is_an_additive_bounded_declaration_on_reads;
1728        // An offload declaration is additive on the wire, bounded like a
1729        // compute job, and only declarable on a read that may leave the device.
1730        {
1731            let local = ActionContract::view();
1732            let json = serde_json::to_value(&local).unwrap();
1733            assert!(json.get("offload").is_none(), "absent stays off the wire");
1734            let old: ActionContract = serde_json::from_value(json).unwrap();
1735            assert_eq!(old.offload, None);
1736
1737            let offload = Offload {
1738                gpu: false,
1739                cpu_time_ms: 60_000,
1740                memory_bytes: 512 * 1024 * 1024,
1741                output_bytes: 8 * 1024 * 1024,
1742            };
1743            let heavy = ActionContract {
1744                offload: Some(offload.clone()),
1745                ..ActionContract::view()
1746            };
1747            assert!(heavy.validate_declaration().is_empty());
1748            let round: ActionContract =
1749                serde_json::from_value(serde_json::to_value(&heavy).unwrap()).unwrap();
1750            assert_eq!(round, heavy);
1751
1752            let unbounded = ActionContract {
1753                offload: Some(Offload {
1754                    cpu_time_ms: 0,
1755                    memory_bytes: MAX_OFFLOAD_MEMORY_BYTES + 1,
1756                    output_bytes: MAX_OFFLOAD_OUTPUT_BYTES + 1,
1757                    ..offload
1758                }),
1759                ..ActionContract::view()
1760            };
1761            assert_eq!(unbounded.validate_declaration().len(), 3);
1762            let writes = ActionContract {
1763                offload: Some(offload),
1764                ..ActionContract::default()
1765            };
1766            assert_eq!(
1767                writes.validate_declaration(),
1768                vec!["an offloadable action must be a read".to_string()]
1769            );
1770        }
1771    }
1772}