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