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