Skip to main content

tilo_actions/
api.rs

1//! **The action API**: how a member that is not the app enumerates what
2//! it has open and performs one of its exported operations.
3//!
4//! [`ResourceSpec`] trees already describe an app's surface and
5//! [`dispatch`](crate::executor::dispatch) already performs one
6//! operation on it; the missing step was naming a thing from outside the
7//! process that built it — without which collaboration, agency and
8//! scripting stay per-app features.
9//!
10//! [`survey`] and [`invoke`] stay separate so enumeration can never
11//! cause an effect: a descriptor carries no callback, token or handle,
12//! so read-only is the shape of the type, not a promise in a comment.
13//!
14//! Authority stays with the host, which resolves the caller against the
15//! workspace's capability model before offering an address: an
16//! operation the caller may not perform is *absent* from the survey,
17//! never a flag to ignore.
18
19use crate::ActionContract;
20use crate::ActionParam;
21use crate::action::{EncodedAction, ExecutionLocus, OperationKind};
22use crate::context::ActionContext;
23use crate::entry::Described;
24use crate::executor::{ActionTransport, Dispatched, dispatch_by_with_context};
25use crate::registry::ActionRegistry;
26use crate::resource::{
27    ActionInput, ActionSpec, Collects, ResourceSpec, ResourceViewMountSpec, ResourceViewRangeSpec,
28};
29use serde::{Deserialize, Serialize};
30
31/// The code a resource answers a write with when what it changes is still on
32/// its way from the workspace: nothing was made, and the same call under the
33/// same invocation is asked again once that is here.
34pub const NOT_READY: &str = "not_ready";
35
36/// What such a write says in words, beside [`NOT_READY`]. A resource answers
37/// it as the whole reason its operation failed, and the toolkit turns that
38/// reason into [`ApiError::Unavailable`] with [`NOT_READY`]: a caller is told
39/// to ask again, never that a write made nothing.
40pub const NOT_READY_REASON: &str = "what this changes has not arrived from the workspace yet; ask \
41     again";
42
43pub use tilo_action_types::ActionAddress;
44
45/// What an invocation of one action must carry, advertised on the
46/// descriptor rather than discovered by trying — enumeration is the only
47/// thing a caller that can't see the screen has to work from.
48#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
49pub enum InputSpec {
50    /// Takes nothing. The majority.
51    None,
52    /// Takes one text argument. `prompt` and `placeholder` are the app's own
53    /// words for it — the ones the palette would show a person — and `collects`
54    /// says what kind of thing it names.
55    Text {
56        prompt: String,
57        placeholder: String,
58        collects: Collects,
59    },
60}
61
62impl ActionDescriptor {
63    /// What the action writes besides its own resource, as a reader is told it: `None` for an
64    /// action that declares nothing else ([`ActionContract::effects`]).
65    #[must_use]
66    pub fn writes(&self) -> Option<String> {
67        if self.contract.effects.is_empty() {
68            return None;
69        }
70        let steps: Vec<String> = self
71            .contract
72            .effects
73            .iter()
74            .map(ToString::to_string)
75            .collect();
76        Some(format!("Writes: {}.", steps.join(", ")))
77    }
78
79    /// Whether this action changes only a document: a document operation, or
80    /// one carried out on another document than the one its resource is kept
81    /// in ([`crate::ROUTED_CHANGE_TAG`]). Such an action reads none of the
82    /// content its resource refers to.
83    #[must_use]
84    pub fn changes_only_a_document(&self) -> bool {
85        self.kind == OperationKind::Document
86            || self
87                .contract
88                .tags
89                .iter()
90                .any(|tag| tag == crate::ROUTED_CHANGE_TAG)
91    }
92
93    /// The parameter this action's one line of typed text goes into, when it
94    /// is a prompted action: what an agent or a host holding only the
95    /// descriptor learns instead of assuming a name.
96    #[must_use]
97    pub fn prompt_param(&self) -> Option<&str> {
98        match self.input {
99            InputSpec::Text { .. } => self
100                .params
101                .iter()
102                .find(|param| param.entry)
103                .or_else(|| self.params.iter().find(|param| param.required))
104                .or_else(|| self.params.first())
105                .map(|param| param.name.as_ref()),
106            InputSpec::None => None,
107        }
108    }
109
110    /// The resource's own id, not the transport alias the window published
111    /// it under (`ResourceSpec::domain_name`): the address a directory row
112    /// carries, resolved back to its alias where the window published one.
113    #[must_use]
114    pub fn domain_resource(&self) -> &str {
115        match &self.semantic_identity {
116            Some(identity) if identity.is_valid() => identity.key.as_str(),
117            _ => self.address.resource.as_str(),
118        }
119    }
120
121    /// The parameter one line of typed text fills, when the action is a
122    /// capture: it declares an entry (`title: Text (entry)`), what a person
123    /// writes down from wherever they are and what a palette offers as "New
124    /// task", run with the line they typed.
125    #[must_use]
126    pub fn entry_param(&self) -> Option<&str> {
127        self.params
128            .iter()
129            .find(|param| param.entry)
130            .map(|param| param.name.as_ref())
131    }
132
133    /// `arguments` as this action takes them. A text argument on the wire
134    /// (`InvokeArgument::Text`) names no parameter and reaches a host as a lone
135    /// [`PROMPTED_PARAM`](crate::PROMPTED_PARAM); it is moved under this
136    /// action's own prompt parameter. Anything else is returned as given.
137    #[must_use]
138    pub fn bind_prompt_text(
139        &self,
140        mut arguments: serde_json::Map<String, serde_json::Value>,
141    ) -> serde_json::Map<String, serde_json::Value> {
142        if arguments.len() == 1
143            && let Some(name) = self.prompt_param()
144            && name != crate::PROMPTED_PARAM
145            && let Some(text) = arguments.remove(crate::PROMPTED_PARAM)
146        {
147            arguments.insert(name.to_owned(), text);
148        }
149        arguments
150    }
151}
152
153impl InputSpec {
154    fn of(input: ActionInput<'_>) -> Self {
155        match input {
156            ActionInput::Immediate(_) | ActionInput::Deferred { .. } => InputSpec::None,
157            ActionInput::Prompted {
158                prompt,
159                placeholder,
160                collects,
161            } => InputSpec::Text {
162                prompt: prompt.to_owned(),
163                placeholder: placeholder.to_owned(),
164                collects,
165            },
166        }
167    }
168
169    /// Whether an invocation must supply text.
170    pub fn wants_text(&self) -> bool {
171        matches!(self, InputSpec::Text { .. })
172    }
173
174    /// Whether the text it wants is the address of content rather than
175    /// words — words can be quoted out of the request, a content hash cannot.
176    pub fn wants_content(&self) -> bool {
177        matches!(
178            self,
179            InputSpec::Text {
180                collects: Collects::Content,
181                ..
182            }
183        )
184    }
185}
186
187/// One exported operation, as inert data: everything a caller needs to
188/// decide whether to perform it, nothing that could perform it — an
189/// [`ActionSpec`]'s closure never appears here or crosses a boundary,
190/// only the address does.
191#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
192pub struct ActionDescriptor {
193    pub address: ActionAddress,
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub semantic_identity: Option<crate::ResourceSemanticIdentity>,
196    /// The publishing resource's stable kind tag (`word_processor.section`,
197    /// `files.entry`), shared with the OS-wide type registry so the same kind
198    /// means the same thing across apps.
199    pub resource_kind: String,
200    /// The resource's human label, as the app words it.
201    pub resource_label: String,
202    pub action_label: String,
203    /// The other words people use for the action ([`ActionSpec::keywords`]),
204    /// published with its label so every search ranks them as it ranks the
205    /// label.
206    #[serde(default, skip_serializing_if = "Vec::is_empty")]
207    pub keywords: Vec<String>,
208    /// What the action did, said after who did it ([`ActionSpec::did`]):
209    /// the past-tense form its app declares, when it declares one.
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub did: Option<String>,
212    /// The action's own picture ([`ActionSpec::icon`]), by its Lucide name.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub icon: Option<String>,
215    pub description: Option<String>,
216    /// What the action's row shows of the state it acts on
217    /// ([`ActionSpec::state`](crate::ActionType::state)).
218    #[serde(default, skip_serializing_if = "crate::ActionState::is_empty")]
219    pub state: crate::ActionState,
220    pub locus: ExecutionLocus,
221    pub kind: OperationKind,
222    pub contract: ActionContract,
223    pub input: InputSpec,
224    /// Canonical typed invocation surface. `input` remains the palette-facing
225    /// projection for compatibility; headless callers use these parameters.
226    pub params: Vec<ActionParam>,
227    /// The explicit resource view opened by this action. Mount actions and
228    /// unrelated local view operations carry `None`.
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub view: Option<ResourceViewDescriptor>,
231}
232
233/// One step an action takes on a record other than the resource it is declared on: the app
234/// whose record it writes, the record's kind, and the verb it runs there. A step that is an
235/// action a device's provider offers names that provider as its app and the resource it
236/// offers the action on as its kind.
237#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
238pub struct ActionEffect {
239    pub app: String,
240    pub kind: String,
241    pub verb: String,
242}
243
244impl ActionEffect {
245    /// The verb of an undo declared as a step ([`Self::undo`]).
246    pub const UNDO: &'static str = "undo";
247
248    /// Taking back changes of the records `app` keeps, whichever kinds the changes wrote: an undo
249    /// declared as an action's step, which a reader admits as it admits any declared step.
250    #[must_use]
251    pub fn undo(app: impl Into<String>) -> Self {
252        Self::new(app, "", Self::UNDO)
253    }
254
255    /// Whether this is the undo of `app`'s records ([`Self::undo`]).
256    #[must_use]
257    pub fn undoes_in(&self, app: &str) -> bool {
258        self.app == app && self.kind.is_empty() && self.verb == Self::UNDO
259    }
260
261    /// The step `verb` on records of `kind` that `app` keeps.
262    #[must_use]
263    pub fn new(app: impl Into<String>, kind: impl Into<String>, verb: impl Into<String>) -> Self {
264        Self {
265            app: app.into(),
266            kind: kind.into(),
267            verb: verb.into(),
268        }
269    }
270}
271
272impl std::fmt::Display for ActionEffect {
273    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        // An undo names no kind: it takes back changes of the app's records, whichever.
275        if self.kind.is_empty() {
276            return write!(formatter, "{}#{}", self.app, self.verb);
277        }
278        write!(formatter, "{} {}#{}", self.app, self.kind, self.verb)
279    }
280}
281
282/// Serializable data describing one explicitly declared resource view.
283///
284/// This is projected only onto the descriptor for `open_action`, keeping the
285/// view identity independent from the operation used to present it.
286#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
287#[serde(deny_unknown_fields)]
288pub struct ResourceViewDescriptor {
289    pub id: String,
290    pub label: String,
291    pub description: Option<String>,
292    pub open_action: String,
293    pub primary: bool,
294    pub mount: Option<ResourceViewMountSpec>,
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub range: Option<ResourceViewRangeSpec>,
297    /// The view opens on the whole desktop ([`crate::ResourceViewSpec::desktop`]).
298    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
299    pub desktop: bool,
300}
301
302impl ResourceViewDescriptor {
303    /// The view `resource` declares for `action_id`, when that action is a
304    /// view's open action.
305    #[must_use]
306    pub fn declared_for(resource: &ResourceSpec, action_id: &str) -> Option<Self> {
307        resource
308            .views
309            .iter()
310            .find(|view| view.open_action == action_id)
311            .map(|view| Self {
312                id: view.id.clone(),
313                label: view.label.clone(),
314                description: view.description.clone(),
315                open_action: view.open_action.clone(),
316                primary: view.primary,
317                mount: view.mount.clone(),
318                range: view.range.clone(),
319                desktop: view.desktop,
320            })
321    }
322}
323
324/// Why answering a question was refused: it is the asked person's to answer, and the caller is
325/// not them. A question a request raised is the person's decision, never its asker's, and no
326/// agent answers another's on their behalf ([`ApiError::Refused`]'s code).
327pub const NOT_THE_ASKED_PERSON: &str = "question-not-yours";
328
329/// Why an address could not be performed. `Unknown` is "nothing publishes this address"; an action
330/// published there that the caller's permissions keep from them is refused as `permission_denied`
331/// ([`ApiError::Unavailable`]), saying why.
332#[derive(Clone, Debug, PartialEq, Eq)]
333pub enum ApiError {
334    /// Nothing in the tree carries this address.
335    Unknown(ActionAddress),
336    /// The action takes text and none was supplied.
337    MissingArgument(ActionAddress),
338    /// The action takes nothing and an argument was supplied. Refused, not
339    /// dropped — a silently ignored argument leaves the caller believing it
340    /// asked for something it didn't get.
341    UnexpectedArgument(ActionAddress),
342    /// Typed arguments failed the action's declared schema.
343    InvalidArguments(String),
344    /// A typed argument is a number outside the range its parameter
345    /// declares: [`InvalidArguments`](Self::InvalidArguments) whose bound
346    /// reaches the caller as data ([`ApiError::failure_details`]).
347    ArgumentOutOfRange {
348        param: String,
349        violation: crate::params::ArgViolation,
350    },
351    /// The address exists and is intentionally advertised, but its current
352    /// precondition is not satisfied.
353    Unavailable { code: String, reason: String },
354    /// The action contract requires an explicit confirmation step that this
355    /// invocation did not carry.
356    ConfirmationRequired,
357    /// The app never registered a decoder for the action's type, so the API
358    /// can't prove what it would run. Fail-closed: a refusal, not a
359    /// best-effort apply.
360    UnregisteredType(String),
361    /// The app declined for a reason it named by a stable code (the thing it
362    /// would add is there already, say), in words beside it for whoever
363    /// reads: a caller decides on the code without reading the words.
364    Refused { code: String, reason: String },
365    /// The action ran and failed.
366    Failed(String),
367}
368
369impl ApiError {
370    /// Why an encoded action could not be turned back into one: no decoder
371    /// for its type, or a payload the registered decoder does not read (the
372    /// code that encoded it and the code decoding it disagree). The second is
373    /// a fault of its own and says so; reporting it as an unknown type sends
374    /// whoever reads it looking for a registration that is there.
375    pub fn decoding(error: crate::action::ActionError) -> Self {
376        match error {
377            crate::action::ActionError::UnknownType(type_id) => ApiError::UnregisteredType(type_id),
378            other => ApiError::refused(other),
379        }
380    }
381
382    /// `error` as the caller reads it: an app that named why keeps its code
383    /// as data, so a caller decides on it without reading the words.
384    pub fn refused(error: crate::action::ActionError) -> Self {
385        match error {
386            crate::action::ActionError::Unavailable { code, message } => ApiError::Refused {
387                code,
388                reason: message,
389            },
390            other => ApiError::Failed(other.to_string()),
391        }
392    }
393
394    /// Stable machine-readable code, distinguishing "I addressed this
395    /// wrongly" from "it ran and could not do its job".
396    pub fn code(&self) -> &str {
397        match self {
398            ApiError::Unknown(_) | ApiError::UnregisteredType(_) => "unknown_action",
399            ApiError::MissingArgument(_)
400            | ApiError::UnexpectedArgument(_)
401            | ApiError::InvalidArguments(_)
402            | ApiError::ArgumentOutOfRange { .. } => "invalid_arguments",
403            ApiError::Unavailable { .. } => "action_unavailable",
404            // The app's own code, which is why it gave one.
405            ApiError::Refused { code, .. } => code,
406            ApiError::ConfirmationRequired => "action_confirmation_required",
407            ApiError::Failed(_) => "action_failed",
408        }
409    }
410
411    /// What an [`ActionFailure`](crate::ActionFailure) reporting this
412    /// refusal carries beside its message, for a caller to act on without
413    /// reading prose: `{"param": …, "violation": …}` for an argument out of
414    /// its declared range, `{"code": …, "reason": …}` for an action that is unavailable, so a
415    /// caller tells why (the person's own view, a policy) by its code.
416    #[must_use]
417    pub fn failure_details(&self) -> Option<serde_json::Value> {
418        match self {
419            ApiError::ArgumentOutOfRange { param, violation } => {
420                Some(serde_json::json!({ "param": param, "violation": violation }))
421            }
422            ApiError::Unavailable { code, reason } => {
423                Some(serde_json::json!({ "code": code, "reason": reason }))
424            }
425            _ => None,
426        }
427    }
428}
429
430/// An argument out of its declared range keeps its bound as data; every
431/// other argument refusal is reported in words.
432impl From<crate::params::ArgError> for ApiError {
433    fn from(error: crate::params::ArgError) -> Self {
434        match error {
435            crate::params::ArgError::OutOfRange { name, violation } => {
436                ApiError::ArgumentOutOfRange {
437                    param: name,
438                    violation,
439                }
440            }
441            error => ApiError::InvalidArguments(error.to_string()),
442        }
443    }
444}
445
446impl std::fmt::Display for ApiError {
447    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448        match self {
449            ApiError::Unknown(a) => {
450                write!(f, "no action addressed by ({}, {})", a.resource, a.action)
451            }
452            ApiError::MissingArgument(a) => write!(
453                f,
454                "action ({}, {}) needs a text argument and none was given",
455                a.resource, a.action
456            ),
457            ApiError::UnexpectedArgument(a) => {
458                write!(f, "action ({}, {}) takes no argument", a.resource, a.action)
459            }
460            ApiError::InvalidArguments(why) | ApiError::Failed(why) => write!(f, "{why}"),
461            ApiError::Refused { reason, .. } => f.write_str(reason),
462            ApiError::ArgumentOutOfRange { param, violation } => {
463                write!(f, "argument `{param}` {violation}")
464            }
465            ApiError::Unavailable { code, reason } => write!(f, "{code}: {reason}"),
466            ApiError::ConfirmationRequired => {
467                f.write_str("this action requires explicit confirmation")
468            }
469            ApiError::UnregisteredType(t) => {
470                write!(f, "no decoder registered for action type `{t}`")
471            }
472        }
473    }
474}
475
476impl std::error::Error for ApiError {}
477
478/// Walk a resource forest and describe every operation it exports.
479/// Depth-first, parents before children, matching
480/// [`flatten`](crate::resource::flatten)'s order. Borrows the tree,
481/// returns owned data — nothing handed back can act on what it described.
482pub fn survey(resources: &[ResourceSpec]) -> Vec<ActionDescriptor> {
483    survey_placed(resources)
484        .into_iter()
485        .map(|row| row.action)
486        .collect()
487}
488
489/// Whether `a` and `b` publish the same: every resource as a reader sees it and every action as
490/// a survey describes it. A target bound anew to the same item publishes the same, so a surface
491/// that described itself again after drawing is told from one whose offer moved.
492#[must_use]
493pub fn publishes_same(a: &[ResourceSpec], b: &[ResourceSpec]) -> bool {
494    a.len() == b.len()
495        && a.iter().zip(b).all(|(a, b)| {
496            a.id == b.id
497                && a.kind == b.kind
498                && a.label == b.label
499                && a.presentation == b.presentation
500                && a.semantic_identity == b.semantic_identity
501                && a.app_id == b.app_id
502                && a.views == b.views
503                && a.personal == b.personal
504                && a.workspace == b.workspace
505                && a.resource_type == b.resource_type
506                && a.actions.len() == b.actions.len()
507                && a.actions
508                    .iter()
509                    .zip(&b.actions)
510                    .all(|(x, y)| x.bound() == y.bound() && describe(a, x) == describe(b, y))
511                && publishes_same(&a.children, &b.children)
512        })
513}
514
515/// One exported operation of a surveyed forest, in the row it stands in: the
516/// resource of the level above it, and whether its own resource holds rows
517/// below it, which a listing asked with that resource as its parent answers.
518#[derive(Clone, Debug, PartialEq, Eq)]
519pub struct PlacedAction {
520    /// The resource this row hangs under; empty at the top level.
521    pub parent: String,
522    /// Whether a query with this row's resource as parent answers more rows.
523    pub has_children: bool,
524    pub action: ActionDescriptor,
525}
526
527/// Walk a resource forest and describe every operation it exports, each in
528/// the row a listing publishes it in: [`survey`] flattened, with the resource
529/// it stands under and whether its own resource holds rows below it, so a
530/// caller reading a level at a time knows where a level continues.
531#[must_use]
532pub fn survey_placed(resources: &[ResourceSpec]) -> Vec<PlacedAction> {
533    let mut out = Vec::new();
534    let _ = survey_placed_each(resources, &mut |placed| {
535        out.push(placed);
536        true
537    });
538    out
539}
540
541/// [`survey_placed`], one row at a time and only as far as `visit` asks:
542/// it answers whether to go on, so a caller listing a page of a record that
543/// publishes thousands of actions builds the rows up to its page and no
544/// more. `false` when it stopped, `true` when it saw every row.
545pub fn survey_placed_each(
546    resources: &[ResourceSpec],
547    visit: &mut dyn FnMut(PlacedAction) -> bool,
548) -> bool {
549    resources
550        .iter()
551        .all(|resource| placed_each(resource, "", visit))
552}
553
554/// [`survey_placed_each`] of one level: the rows of `children`, the
555/// resources `parent` holds (`""` for the top), and none further down, which
556/// stand under those. What a listing of one level walks, however much its
557/// resources hold. `false` when `visit` stopped it.
558pub fn survey_placed_level(
559    children: &[ResourceSpec],
560    parent: &str,
561    visit: &mut dyn FnMut(PlacedAction) -> bool,
562) -> bool {
563    survey_placed_level_items(children, parent, &mut |_, placed| visit(placed))
564}
565
566/// [`survey_placed_level`] with where each row stands: `visit` is told the
567/// index in `children` of the resource the action is on, so a caller listing
568/// a page counts what each resource admits and keeps its place from one page
569/// to the next. `false` when `visit` stopped it.
570pub fn survey_placed_level_items(
571    children: &[ResourceSpec],
572    parent: &str,
573    visit: &mut dyn FnMut(usize, PlacedAction) -> bool,
574) -> bool {
575    children.iter().enumerate().all(|(at, child)| {
576        let has_children = !child.children.is_empty();
577        child.actions.iter().all(|action| {
578            visit(
579                at,
580                PlacedAction {
581                    parent: parent.to_owned(),
582                    has_children,
583                    action: describe(child, action),
584                },
585            )
586        })
587    })
588}
589
590/// [`survey_placed_each`] for one resource's subtree, as a child of
591/// `parent`: the items a listing keeps past the published page, walked as
592/// the tree would walk them.
593pub fn survey_placed_under(
594    resource: &ResourceSpec,
595    parent: &str,
596    visit: &mut dyn FnMut(PlacedAction) -> bool,
597) -> bool {
598    placed_each(resource, parent, visit)
599}
600
601fn placed_each(
602    resource: &ResourceSpec,
603    parent: &str,
604    visit: &mut dyn FnMut(PlacedAction) -> bool,
605) -> bool {
606    let has_children = !resource.children.is_empty();
607    for action in &resource.actions {
608        let go_on = visit(PlacedAction {
609            parent: parent.to_owned(),
610            has_children,
611            action: describe(resource, action),
612        });
613        if !go_on {
614            return false;
615        }
616    }
617    for child in &resource.children {
618        if !placed_each(child, resource.id.as_str(), visit) {
619            return false;
620        }
621    }
622    true
623}
624
625/// `action` of `resource`, as inert data: what a survey hands back.
626/// The action at `address` in the forest `resources`, as a survey describes it.
627#[must_use]
628pub fn described(resources: &[ResourceSpec], address: &ActionAddress) -> Option<ActionDescriptor> {
629    locate(resources, address).map(|(resource, action)| describe(resource, action))
630}
631
632fn describe(resource: &ResourceSpec, action: &ActionSpec) -> ActionDescriptor {
633    let view = ResourceViewDescriptor::declared_for(resource, &action.id);
634    ActionDescriptor {
635        address: ActionAddress::new(resource.id.as_str(), &action.id),
636        semantic_identity: resource.semantic_identity.clone(),
637        resource_kind: resource.kind.clone(),
638        resource_label: resource.label.clone(),
639        action_label: action.label.clone(),
640        keywords: action.keywords.clone(),
641        did: action.did.clone(),
642        icon: action.icon.clone(),
643        description: action.description.clone(),
644        state: action.state.clone(),
645        locus: action.locus,
646        kind: action.kind,
647        contract: action.contract.clone(),
648        input: InputSpec::of(action.input()),
649        params: action.params().to_vec(),
650        view,
651    }
652}
653
654/// Resolve `address` against `resources` without running anything, so a caller
655/// can check what an address currently names before committing to it.
656pub fn resolve<'a>(
657    resources: &'a [ResourceSpec],
658    address: &ActionAddress,
659) -> Option<&'a ActionSpec> {
660    locate(resources, address).map(|(_, spec)| spec)
661}
662
663/// [`resolve`], with the resource that publishes the action: what the API
664/// needs to place the action in the tree it grants over.
665pub fn locate<'a>(
666    resources: &'a [ResourceSpec],
667    address: &ActionAddress,
668) -> Option<(&'a ResourceSpec, &'a ActionSpec)> {
669    fn walk<'a>(
670        r: &'a ResourceSpec,
671        address: &ActionAddress,
672    ) -> Option<(&'a ResourceSpec, &'a ActionSpec)> {
673        if r.id.as_str() == address.resource
674            && let Some(spec) = r.actions.iter().find(|a| a.id == address.action)
675        {
676            return Some((r, spec));
677        }
678        r.children.iter().find_map(|c| walk(c, address))
679    }
680    resources.iter().find_map(|r| walk(r, address))
681}
682
683/// The address of the action `action` that the resource `resource` in the
684/// tree `resources` publishes, or `None` when the tree publishes no such
685/// action: a caller holding a published tree takes its addresses from it
686/// (see [`ResourceSpec::action_address`]).
687pub fn published(
688    resources: &[ResourceSpec],
689    resource: &str,
690    action: &str,
691) -> Option<ActionAddress> {
692    fn walk(r: &ResourceSpec, resource: &str, action: &str) -> Option<ActionAddress> {
693        if r.id.as_str() == resource
694            && let Some(address) = r.action_address(action)
695        {
696            return Some(address);
697        }
698        r.children.iter().find_map(|c| walk(c, resource, action))
699    }
700    resources.iter().find_map(|r| walk(r, resource, action))
701}
702
703/// The action `action` that the resource `resource` in the tree `resources`
704/// publishes, or `None`: [`resolve`] of the address the tree publishes it at
705/// ([`published`]).
706pub fn spec_of<'a>(
707    resources: &'a [ResourceSpec],
708    resource: &str,
709    action: &str,
710) -> Option<&'a ActionSpec> {
711    published(resources, resource, action).and_then(|address| resolve(resources, &address))
712}
713
714/// Turn an address plus its argument into the replayable action it
715/// names. Split out from [`invoke`] so a host can build/inspect/route
716/// the encoded action itself, and so argument rules are checked in one
717/// place. Binding happens *before* anything runs, so a bad call is a
718/// refusal with the document untouched, never a half-applied edit.
719///
720/// # Errors
721///
722/// Returns [`ApiError::Unknown`] if `address` names no resource/action
723/// in `resources`; [`ApiError::UnexpectedArgument`] if `argument` is
724/// `Some` for an [`ActionInput::Immediate`] action; or
725/// [`ApiError::MissingArgument`] if it's `None` for an
726/// [`ActionInput::Prompted`] one whose text is required.
727pub fn encode(
728    resources: &[ResourceSpec],
729    address: &ActionAddress,
730    argument: Option<&str>,
731) -> Result<EncodedAction, ApiError> {
732    let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
733    ensure_available(spec)?;
734    spec.validate_deferred_shape()
735        .map_err(|error| ApiError::InvalidArguments(error.to_string()))?;
736    match (spec.input(), argument) {
737        (ActionInput::Deferred { type_id }, None) => {
738            let Some(encoded) = spec.build_deferred() else {
739                return Err(ApiError::Unknown(address.clone()));
740            };
741            if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
742                return Err(ApiError::InvalidArguments(
743                    String::from_utf8_lossy(&encoded.payload).into_owned(),
744                ));
745            }
746            if encoded.type_id != *type_id {
747                return Err(ApiError::InvalidArguments(format!(
748                    "builder returned `{}` but declared `{type_id}`",
749                    encoded.type_id
750                )));
751            }
752            Ok(encoded)
753        }
754        (ActionInput::Deferred { .. }, Some(_)) => {
755            Err(ApiError::UnexpectedArgument(address.clone()))
756        }
757        (ActionInput::Immediate(_), None) => spec
758            .encode_immediate()
759            .map(std::sync::Arc::unwrap_or_clone)
760            .ok_or_else(|| ApiError::Unknown(address.clone())),
761        (ActionInput::Immediate(_), Some(_)) => Err(ApiError::UnexpectedArgument(address.clone())),
762        (ActionInput::Prompted { .. }, Some(text)) => {
763            let Some(encoded) = spec.build_text(text) else {
764                return Err(ApiError::Unknown(address.clone()));
765            };
766            if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
767                return Err(ApiError::InvalidArguments(
768                    String::from_utf8_lossy(&encoded.payload).into_owned(),
769                ));
770            }
771            Ok(encoded)
772        }
773        // A prompt whose text is optional (a choice with a default) is
774        // invoked without it through the typed parameters, as any caller
775        // omitting an optional argument is.
776        (ActionInput::Prompted { .. }, None)
777            if !spec.params().is_empty() && spec.params().iter().all(|param| !param.required) =>
778        {
779            let encoded = spec
780                .build_json(&serde_json::Map::new())
781                .map_err(ApiError::from)?;
782            if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
783                return Err(ApiError::InvalidArguments(
784                    String::from_utf8_lossy(&encoded.payload).into_owned(),
785                ));
786            }
787            Ok(encoded)
788        }
789        (ActionInput::Prompted { .. }, None) => Err(ApiError::MissingArgument(address.clone())),
790    }
791}
792
793/// Build an action from the canonical typed JSON argument object advertised
794/// by [`ActionDescriptor::params`]. Binding is strict and completes before any
795/// document mutation or application effect is attempted.
796///
797/// # Errors
798///
799/// Returns [`ApiError::Unknown`] when the address is not published,
800/// [`ApiError::Unavailable`] when policy currently disables it, or
801/// [`ApiError::InvalidArguments`] (or [`ApiError::ArgumentOutOfRange`])
802/// when the object violates its parameter contract.
803pub fn encode_json(
804    resources: &[ResourceSpec],
805    address: &ActionAddress,
806    arguments: &serde_json::Map<String, serde_json::Value>,
807) -> Result<EncodedAction, ApiError> {
808    let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
809    ensure_available(spec)?;
810    let encoded = spec.build_json(arguments).map_err(ApiError::from)?;
811    if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
812        return Err(ApiError::InvalidArguments(
813            String::from_utf8_lossy(&encoded.payload).into_owned(),
814        ));
815    }
816    Ok(encoded)
817}
818
819/// Admit one invocation of `address` with `arguments` against the tree `resources` publishes, as
820/// a provider serving that tree answers a caller: resolved, available, confirmed as its contract
821/// asks of these arguments by `confirmation` (the phrase the caller typed, or the person's
822/// approve of the asked record the call was kept as, which only the dispatch hands back and every
823/// frame entry refuses otherwise, [`admit_frame`](crate::remote::asked::admit_frame)), and
824/// bound strictly into the action's own encoded form. Nothing a caller writes is a yes.
825///
826/// # Errors
827///
828/// [`ApiError::Unknown`] for an address the tree does not offer, [`ApiError::Unavailable`] for an
829/// action that cannot run now, [`ApiError::ConfirmationRequired`] when the confirmation is missing
830/// or wrong, and any error [`encode_json`] documents for the arguments.
831pub fn admit(
832    resources: &[ResourceSpec],
833    address: &ActionAddress,
834    arguments: &serde_json::Map<String, serde_json::Value>,
835    confirmation: Option<&crate::remote::Confirmation>,
836) -> Result<EncodedAction, ApiError> {
837    let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
838    ensure_available(spec)?;
839    if !spec.confirmation_for_json(arguments).met_by(confirmation) {
840        return Err(ApiError::ConfirmationRequired);
841    }
842    encode_json(resources, address, arguments)
843}
844
845fn ensure_available(spec: &ActionSpec) -> Result<(), ApiError> {
846    match &spec.contract.availability {
847        crate::Availability::Available => Ok(()),
848        crate::Availability::Unavailable { code, reason } => Err(ApiError::Unavailable {
849            code: code.clone(),
850            reason: reason.clone(),
851        }),
852    }
853}
854
855/// Caller identity and optional semantic context for an invoked action.
856///
857/// Every API entry point takes one, so an invocation made inside a task or
858/// agent run — confirmed or not, text or typed arguments — is recorded with
859/// that run's context rather than only the resource's own.
860#[derive(Clone, Copy, Debug)]
861pub struct InvocationProvenance<'a> {
862    /// Automerge actor bytes attributed to the resulting change.
863    pub actor: &'a [u8],
864    /// Task or session context used to enrich the resource's own context.
865    pub ambient: Option<&'a ActionContext>,
866}
867
868impl<'a> InvocationProvenance<'a> {
869    /// Provenance naming only the caller, for an invocation made outside any
870    /// task or run.
871    #[must_use]
872    pub const fn caller(actor: &'a [u8]) -> Self {
873        Self {
874            actor,
875            ambient: None,
876        }
877    }
878
879    /// The same caller acting within `ambient`, e.g. an agent run's intent
880    /// group.
881    #[must_use]
882    pub const fn within(self, ambient: &'a ActionContext) -> Self {
883        Self {
884            actor: self.actor,
885            ambient: Some(ambient),
886        }
887    }
888}
889
890/// Perform the operation `address` names, attributed to
891/// `provenance.actor`. Resolve, bind, decode through the app's own registry,
892/// then [`dispatch_by`](crate::executor::dispatch_by) honouring the action's locus. The actor is the
893/// caller's Automerge actor bytes, so the workspace's history names who asked;
894/// `provenance.ambient` carries the task or run the call belongs to. The
895/// resource's concrete action label and address remain authoritative; app,
896/// purpose, group, and facets of the ambient context fill only fields the
897/// resource did not supply.
898///
899/// `resources` must be a tree built *now*, not the one an earlier
900/// [`survey`] walked — re-resolving turns an address that has since
901/// stopped naming anything into a refusal rather than an edit to
902/// whatever took its place. Decoding through `registry` (rather than
903/// trusting the tree) makes this fail-closed: an unregistered action
904/// type can't run, and the decoder used here is the one a replaying peer
905/// would use too.
906///
907/// # Errors
908///
909/// Returns any error [`encode`] documents; [`ApiError::ConfirmationRequired`]
910/// when the action's effective confirmation for this argument is not
911/// [`None`](crate::ConfirmationPolicy::None) and the caller does not say the person's answer for
912/// this call came through the system's own question (`confirmed`);
913/// [`ApiError::UnregisteredType`] if `registry` has no decoder for the
914/// encoded action's type; or [`ApiError::Failed`] if [`dispatch_by`](crate::executor::dispatch_by) fails
915/// once decoded.
916pub fn invoke(
917    doc: &mut crate::action::Doc,
918    resources: &[ResourceSpec],
919    address: &ActionAddress,
920    argument: Option<&str>,
921    (provenance, confirmed): (InvocationProvenance<'_>, bool),
922    registry: &ActionRegistry,
923    transport: &mut dyn ActionTransport,
924) -> Result<Dispatched, ApiError> {
925    ensure_confirmation(resources, address, confirmed, |spec| {
926        spec.confirmation_for_argument(argument)
927    })?;
928    ensure_deferred_local_owner(resources, address, registry)?;
929    let encoded = encode(resources, address, argument)?;
930    dispatch_encoded_with_context(
931        doc, resources, address, encoded, provenance, registry, transport,
932    )
933}
934
935/// Typed-argument counterpart to [`invoke`].
936///
937/// # Errors
938///
939/// As [`invoke`].
940pub fn invoke_json(
941    doc: &mut crate::action::Doc,
942    resources: &[ResourceSpec],
943    address: &ActionAddress,
944    arguments: &serde_json::Map<String, serde_json::Value>,
945    (provenance, confirmed): (InvocationProvenance<'_>, bool),
946    registry: &ActionRegistry,
947    transport: &mut dyn ActionTransport,
948) -> Result<Dispatched, ApiError> {
949    ensure_confirmation(resources, address, confirmed, |spec| {
950        spec.confirmation_for_json(arguments)
951    })?;
952    ensure_deferred_local_owner(resources, address, registry)?;
953    let encoded = encode_json(resources, address, arguments)?;
954    dispatch_encoded_with_context(
955        doc, resources, address, encoded, provenance, registry, transport,
956    )
957}
958
959/// Refuse an unconfirmed invocation whose effective confirmation — for these
960/// exact arguments — is not [`None`](crate::ConfirmationPolicy::None).
961fn ensure_confirmation(
962    resources: &[ResourceSpec],
963    address: &ActionAddress,
964    confirmed: bool,
965    policy: impl FnOnce(&ActionSpec) -> crate::ConfirmationPolicy,
966) -> Result<(), ApiError> {
967    let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
968    if !matches!(policy(spec), crate::ConfirmationPolicy::None) && !confirmed {
969        return Err(ApiError::ConfirmationRequired);
970    }
971    Ok(())
972}
973
974// This low-level transport accepts already encoded actions. A Deferred server
975// operation must instead reach the SDK's address-based broker API before mint.
976fn ensure_deferred_local_owner(
977    resources: &[ResourceSpec],
978    address: &ActionAddress,
979    registry: &ActionRegistry,
980) -> Result<(), ApiError> {
981    let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
982    if spec.deferred_invocation_type().is_some()
983        || matches!(spec.input(), ActionInput::Deferred { .. })
984    {
985        spec.validate_deferred_shape()
986            .map_err(|error| ApiError::InvalidArguments(error.to_string()))?;
987        if spec.kind != OperationKind::Document || spec.locus != ExecutionLocus::ClientLocal {
988            return Err(ApiError::Unavailable {
989                code: "deferred_owner_required".into(),
990                reason: "This creation must use the owning application's address-based action API"
991                    .into(),
992            });
993        }
994        if let Some(type_id) = spec.deferred_invocation_type()
995            && !registry.contains(type_id)
996        {
997            return Err(ApiError::UnregisteredType(type_id.into()));
998        }
999    }
1000    Ok(())
1001}
1002
1003fn dispatch_encoded_with_context(
1004    doc: &mut crate::action::Doc,
1005    resources: &[ResourceSpec],
1006    address: &ActionAddress,
1007    encoded: EncodedAction,
1008    provenance: InvocationProvenance<'_>,
1009    registry: &ActionRegistry,
1010    transport: &mut dyn ActionTransport,
1011) -> Result<Dispatched, ApiError> {
1012    let resource = find_resource(resources, &address.resource)
1013        .ok_or_else(|| ApiError::Unknown(address.clone()))?;
1014    let spec = resource
1015        .actions
1016        .iter()
1017        .find(|candidate| candidate.id == address.action)
1018        .ok_or_else(|| ApiError::Unknown(address.clone()))?;
1019    if spec.kind != OperationKind::Document {
1020        return Err(ApiError::Failed(format!(
1021            "{} operation must be handled by the owning application",
1022            spec.kind.as_str()
1023        )));
1024    }
1025    let mut context = spec.history_context(resource.id.as_str(), &resource.kind, &resource.label);
1026    if let Some(ambient) = provenance.ambient {
1027        context = context.enriched_by(ambient);
1028    }
1029    // The published action is the verb history names, unless the value
1030    // describes itself or the action only carries others.
1031    if !spec.carries_actions()
1032        && let Some(described) = Described::of_published(
1033            &encoded,
1034            crate::ActionKey::new("", &resource.kind, &spec.id),
1035        )
1036    {
1037        context = context.with_described(described);
1038    }
1039    let action = registry.decode(&encoded).map_err(ApiError::decoding)?;
1040    if spec.deferred_invocation_type().is_some() && action.locus() != spec.locus {
1041        return Err(ApiError::Failed(
1042            "Deferred action locus differs from its declaration".into(),
1043        ));
1044    }
1045    dispatch_by_with_context(
1046        doc,
1047        action.as_ref(),
1048        encoded,
1049        transport,
1050        Some(provenance.actor),
1051        context,
1052    )
1053    .map_err(ApiError::refused)
1054}
1055
1056/// The resource `id` in `resources` or among their children.
1057#[must_use]
1058pub fn find_resource<'a>(resources: &'a [ResourceSpec], id: &str) -> Option<&'a ResourceSpec> {
1059    fn walk<'a>(resource: &'a ResourceSpec, id: &str) -> Option<&'a ResourceSpec> {
1060        if resource.id.as_str() == id {
1061            return Some(resource);
1062        }
1063        resource.children.iter().find_map(|child| walk(child, id))
1064    }
1065    resources.iter().find_map(|resource| walk(resource, id))
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use super::*;
1071    use crate::action::{Action, ActionError, Doc};
1072    use crate::executor::{LocalTransport, replay};
1073    use automerge::transaction::Transactable;
1074    use automerge::{AutoCommit, ROOT, ReadDoc, ScalarValue};
1075    use serde::{Deserialize, Serialize};
1076
1077    const NOTE_TYPE: &str = "test.note";
1078
1079    #[derive(Debug, Clone, Serialize, Deserialize)]
1080    enum Note {
1081        Star,
1082        Retitle(String),
1083    }
1084
1085    impl Action for Note {
1086        fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
1087            match self {
1088                Note::Star => {
1089                    doc.put(&ROOT, "starred", ScalarValue::Boolean(true))?;
1090                }
1091                Note::Retitle(title) => {
1092                    doc.put(&ROOT, "title", ScalarValue::Str(title.as_str().into()))?;
1093                }
1094            }
1095            Ok(())
1096        }
1097    }
1098
1099    fn registry() -> ActionRegistry {
1100        let mut r = ActionRegistry::new();
1101        r.register::<Note>(NOTE_TYPE);
1102        r
1103    }
1104
1105    fn encoded(action: &Note) -> EncodedAction {
1106        EncodedAction::encode(NOTE_TYPE, action).unwrap()
1107    }
1108
1109    /// One note publishing an immediate action and a prompted one, as an app
1110    /// would. `star_does` / `retitle_does` decide what each *performs* while
1111    /// leaving every id and label identical.
1112    fn note(star_does: &Note, retitle_does: fn(&str) -> Note) -> Vec<ResourceSpec> {
1113        vec![
1114            ResourceSpec::new("notes.note:1", "notes.note", "Harbour")
1115                .with_action(ActionSpec::immediate("star", "Star", NOTE_TYPE, star_does).unwrap())
1116                .with_action(ActionSpec::prompted_param(
1117                    "retitle",
1118                    "Rename",
1119                    ActionParam::required("title", crate::ParamType::Text, "New title"),
1120                    "title",
1121                    ExecutionLocus::ClientLocal,
1122                    move |text| encoded(&retitle_does(text)),
1123                )),
1124        ]
1125    }
1126
1127    fn open() -> Vec<ResourceSpec> {
1128        note(&Note::Star, |text| Note::Retitle(text.to_string()))
1129    }
1130
1131    fn star() -> ActionAddress {
1132        ActionAddress::new("notes.note:1", "star")
1133    }
1134
1135    fn retitle() -> ActionAddress {
1136        ActionAddress::new("notes.note:1", "retitle")
1137    }
1138
1139    fn perform(
1140        doc: &mut Doc,
1141        tree: &[ResourceSpec],
1142        address: &ActionAddress,
1143        argument: Option<&str>,
1144    ) -> Result<Dispatched, ApiError> {
1145        invoke(
1146            doc,
1147            tree,
1148            address,
1149            argument,
1150            (InvocationProvenance::caller(b"caller-key"), false),
1151            &registry(),
1152            &mut LocalTransport::new(),
1153        )
1154    }
1155
1156    /// A descriptor carries no live handle: two trees whose actions *do
1157    /// different things* survey to equal descriptors — only the address
1158    /// reaches the closure, and only against a tree handed in again.
1159    fn a_descriptor_carries_nothing_that_could_act() {
1160        let honest = open();
1161        let hijacked = note(&Note::Retitle("hijacked".into()), |_| Note::Star);
1162        assert_eq!(
1163            survey(&honest),
1164            survey(&hijacked),
1165            "descriptors that differ only in what they would run must not differ"
1166        );
1167
1168        let mut a = AutoCommit::new();
1169        perform(&mut a, &honest, &star(), None).unwrap();
1170        let mut b = AutoCommit::new();
1171        perform(&mut b, &hijacked, &star(), None).unwrap();
1172
1173        assert_eq!(
1174            a.get(&ROOT, "starred").unwrap().unwrap().0.as_bool(),
1175            Some(true)
1176        );
1177        assert!(b.get(&ROOT, "starred").unwrap().is_none());
1178        assert_eq!(
1179            b.get(&ROOT, "title")
1180                .unwrap()
1181                .unwrap()
1182                .0
1183                .into_string()
1184                .unwrap(),
1185            "hijacked",
1186            "the same descriptor performed a different operation — so it holds none of it"
1187        );
1188
1189        // Owned data: the descriptions outlive the tree they came from.
1190        let described = survey(&honest);
1191        drop(honest);
1192        assert_eq!(described.len(), 2);
1193    }
1194
1195    tilo_test_env::scenario! {
1196        fn a_survey_describes_without_acting;
1197
1198        phase surveying_through_the_api_describes_without_acting;
1199        // A descriptor carries nothing that could act, survey annotates only the declared view-open
1200        // action, and enumeration leaves the document untouched.
1201        // Runs each phase below in order; every phase builds its own fixture.
1202        {
1203            a_descriptor_carries_nothing_that_could_act();
1204            survey_annotates_only_the_declared_view_open_action();
1205            enumeration_leaves_the_document_untouched();
1206        }
1207
1208        phase a_survey_names_the_row_each_action_stands_in;
1209        // A survey names the row each action stands in: the resource of the level above it, and
1210        // whether its own resource holds rows below it, so a reader asking a level at a time knows
1211        // where the listing continues and where it ends.
1212        {
1213            let leaf = ResourceSpec::new("notes.note:1", "notes.note", "Harbour")
1214                .with_action(ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap());
1215            let folder = ResourceSpec::new("notes.folder:a", "notes.folder", "Trips")
1216                .with_action(
1217                    ActionSpec::immediate("archive", "Archive", NOTE_TYPE, &Note::Star).unwrap(),
1218                )
1219                .with_child(leaf);
1220            let placed = survey_placed(std::slice::from_ref(&folder));
1221            let at = |action: &str| {
1222                placed
1223                    .iter()
1224                    .find(|placed| placed.action.address.action == action)
1225                    .expect("the action was surveyed")
1226            };
1227            let archived = at("archive");
1228            assert_eq!(archived.parent, "", "the folder stands at the top level");
1229            assert!(archived.has_children, "the folder holds the note below it");
1230            let starred = at("star");
1231            assert_eq!(starred.parent, "notes.folder:a", "the note is under it");
1232            assert!(
1233                !starred.has_children,
1234                "nothing stands below the note: the listing ends here"
1235            );
1236            // The flat survey is the same actions, in the same order, without the rows.
1237            assert_eq!(
1238                survey(std::slice::from_ref(&folder))
1239                    .iter()
1240                    .map(|descriptor| descriptor.address.action.clone())
1241                    .collect::<Vec<_>>(),
1242                placed
1243                    .iter()
1244                    .map(|placed| placed.action.address.action.clone())
1245                    .collect::<Vec<_>>(),
1246            );
1247        }
1248    }
1249
1250    fn survey_annotates_only_the_declared_view_open_action() {
1251        let open =
1252            ActionSpec::operation("open", "Open", OperationKind::View, "notes.open", &()).unwrap();
1253        let select =
1254            ActionSpec::operation("select", "Select", OperationKind::View, "notes.select", &())
1255                .unwrap();
1256        let resource = ResourceSpec::new("note:1", "notes.note", "Harbour")
1257            .with_action(open)
1258            .with_action(select)
1259            .with_view(
1260                crate::ResourceViewSpec::new("editor", "Editor", "open")
1261                    .with_description("Edit the note")
1262                    .with_primary(true),
1263            );
1264
1265        let descriptors = survey(&[resource]);
1266        let open = descriptors
1267            .iter()
1268            .find(|descriptor| descriptor.address.action == "open")
1269            .unwrap();
1270        assert_eq!(
1271            open.view,
1272            Some(ResourceViewDescriptor {
1273                id: "editor".into(),
1274                label: "Editor".into(),
1275                description: Some("Edit the note".into()),
1276                open_action: "open".into(),
1277                primary: true,
1278                range: None,
1279                mount: None,
1280                desktop: false,
1281            })
1282        );
1283        assert!(
1284            descriptors
1285                .iter()
1286                .find(|descriptor| descriptor.address.action == "select")
1287                .unwrap()
1288                .view
1289                .is_none()
1290        );
1291    }
1292
1293    /// A tree is per-frame presentation, so an address is re-resolved against a
1294    /// freshly built one. An address whose resource has gone is refused, not
1295    /// applied to whatever is open in its place.
1296    fn an_address_that_no_longer_resolves_is_refused_not_redirected() {
1297        let address = survey(&open())[0].address.clone();
1298        assert_eq!(address, star());
1299
1300        // The note closed; a different one is open, exporting the same action id.
1301        let now = vec![
1302            ResourceSpec::new("notes.note:2", "notes.note", "Log").with_action(
1303                ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap(),
1304            ),
1305        ];
1306        assert!(resolve(&now, &address).is_none());
1307
1308        let mut doc = AutoCommit::new();
1309        let before = doc.get_heads();
1310        let err = perform(&mut doc, &now, &address, None).unwrap_err();
1311
1312        assert_eq!(err, ApiError::Unknown(address));
1313        assert_eq!(err.code(), "unknown_action");
1314        assert_eq!(doc.get_heads(), before, "a refused address left no change");
1315        assert!(doc.get(&ROOT, "starred").unwrap().is_none());
1316    }
1317
1318    /// Argument rules are checked both directions: a missing declared
1319    /// argument, and one supplied where none was declared. Neither is
1320    /// quietly tolerated.
1321    fn an_argument_that_does_not_match_the_declaration_is_refused() {
1322        let tree = open();
1323        let described = survey(&tree);
1324        let spec = described.iter().find(|d| d.address == retitle()).unwrap();
1325        assert!(spec.input.wants_text());
1326        assert!(!spec.input.wants_content());
1327
1328        let mut doc = AutoCommit::new();
1329        let before = doc.get_heads();
1330
1331        let err = perform(&mut doc, &tree, &retitle(), None).unwrap_err();
1332        assert_eq!(err, ApiError::MissingArgument(retitle()));
1333        assert_eq!(err.code(), "invalid_arguments");
1334
1335        let err = perform(&mut doc, &tree, &star(), Some("Log")).unwrap_err();
1336        assert_eq!(err, ApiError::UnexpectedArgument(star()));
1337        assert_eq!(err.code(), "invalid_arguments");
1338
1339        assert_eq!(doc.get_heads(), before, "a refused call left no change");
1340        assert!(doc.get(&ROOT, "title").unwrap().is_none());
1341        assert!(doc.get(&ROOT, "starred").unwrap().is_none());
1342    }
1343
1344    /// An action the app never registered a decoder for cannot be run, even
1345    /// though its own tree offers it: the API will not dispatch what it cannot
1346    /// reconstruct the way a replaying peer would.
1347    fn an_unregistered_action_type_is_refused_rather_than_applied() {
1348        let tree = open();
1349        let mut doc = AutoCommit::new();
1350        let before = doc.get_heads();
1351
1352        let err = invoke(
1353            &mut doc,
1354            &tree,
1355            &star(),
1356            None,
1357            (InvocationProvenance::caller(b"caller-key"), false),
1358            &ActionRegistry::new(),
1359            &mut LocalTransport::new(),
1360        )
1361        .unwrap_err();
1362
1363        assert_eq!(err, ApiError::UnregisteredType(NOTE_TYPE.into()));
1364        assert_eq!(doc.get_heads(), before);
1365        assert!(doc.get(&ROOT, "starred").unwrap().is_none());
1366    }
1367
1368    /// The type is registered, but by code that reads another shape (as after
1369    /// the code that encodes it changed): the refusal names the payload, not a
1370    /// missing registration, and nothing is applied.
1371    fn a_payload_its_decoder_cannot_read_is_not_called_unregistered() {
1372        #[derive(Debug, Serialize, Deserialize)]
1373        struct OtherShape {
1374            // Only its shape is decoded.
1375            #[serde(rename = "pinned")]
1376            _pinned: bool,
1377        }
1378        impl Action for OtherShape {
1379            fn apply(&self, _doc: &mut Doc) -> Result<(), ActionError> {
1380                Ok(())
1381            }
1382        }
1383        let tree = open();
1384        let mut doc = AutoCommit::new();
1385        let before = doc.get_heads();
1386        let mut other = ActionRegistry::new();
1387        other.register::<OtherShape>(NOTE_TYPE);
1388
1389        let err = invoke(
1390            &mut doc,
1391            &tree,
1392            &star(),
1393            None,
1394            (InvocationProvenance::caller(b"caller-key"), false),
1395            &other,
1396            &mut LocalTransport::new(),
1397        )
1398        .unwrap_err();
1399
1400        let ApiError::Failed(why) = &err else {
1401            panic!("a payload the decoder cannot read is its own failure: {err:?}");
1402        };
1403        assert!(why.contains(NOTE_TYPE), "{why}");
1404        assert_eq!(doc.get_heads(), before);
1405    }
1406
1407    /// Build the tree by reading the document, so enumeration exercises the
1408    /// path an app actually takes.
1409    fn notes(doc: &AutoCommit) -> Vec<ResourceSpec> {
1410        let label = doc
1411            .get(&ROOT, "title")
1412            .ok()
1413            .flatten()
1414            .and_then(|(v, _)| v.into_string().ok())
1415            .unwrap_or_else(|| "Untitled".into());
1416        vec![
1417            ResourceSpec::new("notes.note:1", "notes.note", label).with_action(
1418                ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap(),
1419            ),
1420        ]
1421    }
1422
1423    /// Asking what can be done here is not doing it: building the tree and
1424    /// surveying it twice leaves the document byte-identical, so a caller may
1425    /// explore an unfamiliar app without changing it.
1426    fn enumeration_leaves_the_document_untouched() {
1427        let mut doc = AutoCommit::new();
1428        doc.put(&ROOT, "title", ScalarValue::Str("Harbour".into()))
1429            .unwrap();
1430        doc.commit();
1431        let heads = doc.get_heads();
1432        let saved = doc.save();
1433
1434        let first = survey(&notes(&doc));
1435        let second = survey(&notes(&doc));
1436
1437        assert_eq!(first, second);
1438        assert_eq!(
1439            first.len(),
1440            1,
1441            "the survey found something to be side-effect free about"
1442        );
1443        assert_eq!(
1444            first[0].resource_label, "Harbour",
1445            "it really read the document"
1446        );
1447        assert_eq!(doc.get_heads(), heads);
1448        assert_eq!(doc.save(), saved, "surveying rewrote the document");
1449    }
1450
1451    /// A change made through the API commits under the *caller's* actor, so
1452    /// history names who asked rather than the app — and since the actor
1453    /// rides the envelope, a peer still replays to the identical document.
1454    fn a_change_through_the_api_is_attributed_to_the_caller() {
1455        let mut doc = AutoCommit::new();
1456        doc.put(&ROOT, "seed", ScalarValue::Str("s".into()))
1457            .unwrap();
1458        doc.commit();
1459        let app_actor = doc.get_actor().clone();
1460        let mut peer = AutoCommit::load(&doc.save()).unwrap();
1461
1462        let caller: &[u8] = b"maren-device-key";
1463        // A caller names the app its change belongs to, as a record's host does.
1464        let notes = ActionContext::default().with_app("org.tilo.Notes", "Notes");
1465        let mut transport = LocalTransport::new();
1466        let dispatched = invoke(
1467            &mut doc,
1468            &open(),
1469            &star(),
1470            None,
1471            (InvocationProvenance::caller(caller).within(&notes), false),
1472            &registry(),
1473            &mut transport,
1474        )
1475        .unwrap();
1476
1477        assert!(dispatched.mutated_local());
1478        let env = dispatched.envelope().clone();
1479        assert_eq!(env.actor.as_deref(), Some(caller));
1480        let context = env.context.as_ref().expect("the API supplies provenance");
1481        assert_eq!(published_verb(context), "star");
1482        assert_eq!(
1483            context
1484                .resource
1485                .as_ref()
1486                .map(|resource| resource.id.as_str()),
1487            Some("notes.note:1")
1488        );
1489
1490        let heads = doc.get_heads();
1491        let change = doc.get_change_by_hash(&heads[0]).unwrap();
1492        assert_eq!(change.actor_id().to_bytes(), caller);
1493        assert_eq!(
1494            change
1495                .message()
1496                .and_then(ActionContext::from_change_message),
1497            env.context,
1498            "semantic provenance survives as part of the durable change"
1499        );
1500        assert_ne!(change.actor_id(), &app_actor, "not the app's own actor");
1501        assert_ne!(
1502            change.actor_id().to_bytes(),
1503            &env.id.actor_bytes()[..],
1504            "not the action id's derived actor"
1505        );
1506
1507        replay(&mut peer, &env, &registry()).unwrap();
1508        assert_eq!(
1509            peer.get_heads(),
1510            heads,
1511            "attribution must not cost the identical replay"
1512        );
1513        assert_eq!(transport.replicated.len(), 1);
1514    }
1515
1516    fn ambient_task_context_reaches_api_actions_without_overwriting_resource() {
1517        let mut doc = AutoCommit::new();
1518        let mut transport = LocalTransport::new();
1519        let ambient = ActionContext::default()
1520            .with_app("org.tilo.Notes", "Notes")
1521            .with_purpose("Prepare launch")
1522            .with_group("issue:42", "Launch", "issue");
1523        let dispatched = invoke(
1524            &mut doc,
1525            &open(),
1526            &star(),
1527            None,
1528            (
1529                InvocationProvenance {
1530                    actor: b"agent:ada",
1531                    ambient: Some(&ambient),
1532                },
1533                false,
1534            ),
1535            &registry(),
1536            &mut transport,
1537        )
1538        .expect("the API answered");
1539
1540        let context = dispatched.envelope().context.as_ref().expect("context");
1541        assert_eq!(published_verb(context), "star");
1542        assert_eq!(context.purpose.as_deref(), Some("Prepare launch"));
1543        assert_eq!(
1544            context.group.as_ref().map(|group| group.id.as_str()),
1545            Some("issue:42")
1546        );
1547        assert_eq!(
1548            context
1549                .resource
1550                .as_ref()
1551                .map(|resource| resource.id.as_str()),
1552            Some("notes.note:1")
1553        );
1554    }
1555
1556    fn consequential_actions_cannot_cross_the_api_without_consent() {
1557        let resources = vec![
1558            ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
1559                ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star)
1560                    .unwrap()
1561                    .with_contract(ActionContract {
1562                        confirmation: crate::ConfirmationPolicy::Confirm,
1563                        ..ActionContract::default()
1564                    }),
1565            ),
1566        ];
1567        let mut doc = AutoCommit::new();
1568        let mut transport = LocalTransport::new();
1569
1570        let refusal = invoke(
1571            &mut doc,
1572            &resources,
1573            &star(),
1574            None,
1575            (InvocationProvenance::caller(b"caller-key"), false),
1576            &registry(),
1577            &mut transport,
1578        )
1579        .unwrap_err();
1580        assert_eq!(refusal, ApiError::ConfirmationRequired);
1581        assert!(doc.get(&ROOT, "starred").unwrap().is_none());
1582
1583        invoke(
1584            &mut doc,
1585            &resources,
1586            &star(),
1587            None,
1588            (InvocationProvenance::caller(b"caller-key"), true),
1589            &registry(),
1590            &mut transport,
1591        )
1592        .expect("a policy check may explicitly attest confirmation");
1593        assert_eq!(
1594            doc.get(&ROOT, "starred").unwrap().unwrap().0.as_bool(),
1595            Some(true)
1596        );
1597    }
1598
1599    /// A generic edit whose value decides its risk: clearing the title is
1600    /// destructive, renaming is not.
1601    fn edit_by_value() -> Vec<ResourceSpec> {
1602        vec![
1603            ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
1604                ActionSpec::typed(
1605                    "edit",
1606                    "Edit",
1607                    "title",
1608                    ExecutionLocus::ClientLocal,
1609                    vec![ActionParam::required(
1610                        "title",
1611                        crate::ParamType::Text,
1612                        "Title",
1613                    )],
1614                    |args| encoded(&Note::Retitle(args.text("title").unwrap_or("").to_owned())),
1615                )
1616                .for_audience(crate::Audience::Agents)
1617                .with_risk(|args| {
1618                    if args.text("title").is_some_and(str::is_empty) {
1619                        crate::RiskLevel::Destructive
1620                    } else {
1621                        crate::RiskLevel::Low
1622                    }
1623                }),
1624            ),
1625        ]
1626    }
1627
1628    fn edit() -> ActionAddress {
1629        ActionAddress::new("notes.note:1", "edit")
1630    }
1631
1632    fn title(value: &str) -> serde_json::Map<String, serde_json::Value> {
1633        serde_json::Map::from_iter([("title".to_owned(), serde_json::json!(value))])
1634    }
1635
1636    fn stored_title(doc: &AutoCommit) -> Option<String> {
1637        doc.get(&ROOT, "title")
1638            .unwrap()
1639            .and_then(|(value, _)| value.into_string().ok())
1640    }
1641
1642    fn a_value_classified_as_destructive_needs_the_same_consent() {
1643        let resources = edit_by_value();
1644        let mut doc = AutoCommit::new();
1645        let mut transport = LocalTransport::new();
1646        let registry = registry();
1647        let mut run = |doc: &mut AutoCommit, value: &str, confirmed: bool| {
1648            invoke_json(
1649                doc,
1650                &resources,
1651                &edit(),
1652                &title(value),
1653                (InvocationProvenance::caller(b"caller-key"), confirmed),
1654                &registry,
1655                &mut transport,
1656            )
1657            .map(|_| ())
1658        };
1659
1660        run(&mut doc, "Harbour", false).expect("an ordinary value runs");
1661        assert_eq!(
1662            run(&mut doc, "", false).unwrap_err(),
1663            ApiError::ConfirmationRequired
1664        );
1665        assert_eq!(
1666            stored_title(&doc).as_deref(),
1667            Some("Harbour"),
1668            "the refused value changed nothing"
1669        );
1670        run(&mut doc, "", true).expect("a confirmed destructive value runs");
1671        assert_eq!(stored_title(&doc).as_deref(), Some(""));
1672
1673        let mut transport = LocalTransport::new();
1674        assert_eq!(
1675            invoke(
1676                &mut doc,
1677                &resources,
1678                &edit(),
1679                Some(""),
1680                (InvocationProvenance::caller(b"caller-key"), false),
1681                &registry,
1682                &mut transport,
1683            )
1684            .unwrap_err(),
1685            ApiError::ConfirmationRequired
1686        );
1687    }
1688
1689    /// The context an agent run hands every invocation it makes.
1690    fn agent_session() -> ActionContext {
1691        ActionContext::default()
1692            .with_app("org.tilo.Agent", "Agent")
1693            .with_purpose("Remove the draft marks")
1694            .with_group("agent-session:7", "Remove the draft marks", "agent-session")
1695    }
1696
1697    /// Read the durable change the API just committed back from its message,
1698    /// and require it to carry both the resource's own context and the run's.
1699    /// The published action an entry names, with the resource kind it was
1700    /// published on.
1701    fn published_verb(context: &ActionContext) -> &str {
1702        let Some(crate::Did::Verb(verb)) = &context.what else {
1703            panic!("a verb: {context:?}");
1704        };
1705        assert_eq!(verb.action.kind, "notes.note");
1706        assert!(!verb.action.app.is_empty(), "the app is filled in");
1707        &verb.action.action
1708    }
1709
1710    fn assert_recorded_within_run(doc: &mut AutoCommit, action: &str) {
1711        let heads = doc.get_heads();
1712        let change = doc
1713            .get_change_by_hash(&heads[0])
1714            .expect("the API committed");
1715        assert_eq!(change.actor_id().to_bytes(), b"agent:ada");
1716        let context = change
1717            .message()
1718            .and_then(ActionContext::from_change_message)
1719            .expect("the change carries its semantic provenance");
1720        assert_eq!(published_verb(&context), action);
1721        assert_eq!(
1722            context
1723                .resource
1724                .as_ref()
1725                .map(|resource| resource.id.as_str()),
1726            Some("notes.note:1"),
1727            "the resource stays authoritative"
1728        );
1729        let group = context.group.as_ref().expect("the run's group is recorded");
1730        assert_eq!(group.id, "agent-session:7");
1731        assert_eq!(group.kind, "agent-session");
1732        assert_eq!(context.purpose.as_deref(), Some("Remove the draft marks"));
1733    }
1734
1735    tilo_test_env::scenario! {
1736        fn an_invocation_through_the_api_is_checked_and_recorded;
1737
1738        phase invoking_through_the_api_refuses_mismatches_and_attributes_the_caller;
1739        // Stale addresses, mismatched arguments and unregistered action types are refused rather than
1740        // redirected or applied; an accepted change is attributed to the caller and ambient task
1741        // context reaches it without overwriting the resource.
1742        // Runs each phase below in order; every phase builds its own fixture.
1743        {
1744            an_address_that_no_longer_resolves_is_refused_not_redirected();
1745            an_argument_that_does_not_match_the_declaration_is_refused();
1746            an_unregistered_action_type_is_refused_rather_than_applied();
1747            a_payload_its_decoder_cannot_read_is_not_called_unregistered();
1748            a_change_through_the_api_is_attributed_to_the_caller();
1749            ambient_task_context_reaches_api_actions_without_overwriting_resource();
1750        }
1751
1752        phase an_optional_only_prompt_runs_without_its_argument;
1753        // A prompt whose only parameter is optional runs when the caller omits
1754        // it, bound through the typed parameters exactly as an omitted optional
1755        // argument is; a required one is still refused.
1756        {
1757            let tree = vec![
1758                ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
1759                    ActionSpec::prompted_param(
1760                        "retitle",
1761                        "Rename",
1762                        ActionParam::optional("title", crate::ParamType::Text, "New title"),
1763                        "title",
1764                        ExecutionLocus::ClientLocal,
1765                        |text| encoded(&Note::Retitle(format!("[{text}]"))),
1766                    ),
1767                ),
1768            ];
1769            let mut doc = AutoCommit::new();
1770            perform(&mut doc, &tree, &retitle(), None).unwrap();
1771            assert_eq!(
1772                doc.get(&ROOT, "title")
1773                    .unwrap()
1774                    .unwrap()
1775                    .0
1776                    .into_string()
1777                    .unwrap(),
1778                "[]",
1779                "the omitted optional text binds as nothing typed"
1780            );
1781
1782            let mut doc = AutoCommit::new();
1783            let err = perform(&mut doc, &open(), &retitle(), None).unwrap_err();
1784            assert_eq!(err, ApiError::MissingArgument(retitle()));
1785        }
1786
1787        phase a_wire_text_argument_goes_under_the_actions_own_prompt_parameter;
1788        // A text argument on the wire names no parameter; the descriptor says
1789        // where it goes.
1790        {
1791            let tree = open();
1792            let described = survey(&tree);
1793            let retitle_spec = described.iter().find(|d| d.address == retitle()).unwrap();
1794            assert_eq!(retitle_spec.prompt_param(), Some("title"));
1795            let lone = serde_json::json!({ crate::PROMPTED_PARAM: "Log" })
1796                .as_object()
1797                .unwrap()
1798                .clone();
1799            assert_eq!(
1800                retitle_spec.bind_prompt_text(lone.clone()),
1801                serde_json::json!({"title": "Log"})
1802                    .as_object()
1803                    .unwrap()
1804                    .clone()
1805            );
1806            // Already named, or more than one argument: left as given.
1807            let named = serde_json::json!({"title": "Log"})
1808                .as_object()
1809                .unwrap()
1810                .clone();
1811            assert_eq!(retitle_spec.bind_prompt_text(named.clone()), named);
1812            // An action that collects no text has no prompt parameter.
1813            let star_spec = described.iter().find(|d| d.address == star()).unwrap();
1814            assert_eq!(star_spec.prompt_param(), None);
1815            assert_eq!(star_spec.bind_prompt_text(lone.clone()), lone);
1816        }
1817
1818        phase consequential_api_actions_need_consent_whatever_form_the_argument_takes;
1819        // Consequential actions and values classified destructive need consent, and effective
1820        // confirmation reads every argument form.
1821        // Runs each phase below in order; every phase builds its own fixture.
1822        {
1823            consequential_actions_cannot_cross_the_api_without_consent();
1824            a_value_classified_as_destructive_needs_the_same_consent();
1825            effective_confirmation_reads_every_argument_form();
1826        }
1827
1828        phase a_confirmed_invocation_inside_a_run_is_recorded_with_its_group;
1829        // A destructive operation an agent run performs after its policy check
1830        // confirmed it is recorded within the run, exactly like an unconfirmed
1831        // one — consent is not a reason to lose whose task the change belongs to.
1832        {
1833            let resources = vec![
1834                ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
1835                    ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star)
1836                        .unwrap()
1837                        .destructive(),
1838                ),
1839            ];
1840            let run = agent_session();
1841            let provenance = InvocationProvenance::caller(b"agent:ada").within(&run);
1842            let mut doc = AutoCommit::new();
1843            let mut transport = LocalTransport::new();
1844
1845            assert_eq!(
1846                invoke(
1847                    &mut doc,
1848                    &resources,
1849                    &star(),
1850                    None,
1851                    (provenance, false),
1852                    &registry(),
1853                    &mut transport,
1854                )
1855                .unwrap_err(),
1856                ApiError::ConfirmationRequired
1857            );
1858            let dispatched = invoke(
1859                &mut doc,
1860                &resources,
1861                &star(),
1862                None,
1863                (provenance, true),
1864                &registry(),
1865                &mut transport,
1866            )
1867            .expect("a confirmed destructive action runs");
1868
1869            assert_eq!(
1870                dispatched
1871                    .envelope()
1872                    .context
1873                    .as_ref()
1874                    .and_then(|context| context.group.as_ref())
1875                    .map(|group| group.id.as_str()),
1876                Some("agent-session:7"),
1877                "the replicated envelope carries the run too"
1878            );
1879            assert_recorded_within_run(&mut doc, "star");
1880        }
1881
1882        phase typed_invocations_inside_a_run_are_recorded_with_its_group;
1883        // Both typed-argument calls record the run's context: the
1884        // ordinary value through [`invoke_json`] and the destructive one through
1885        // [`invoke_json`], confirmed.
1886        {
1887            let resources = edit_by_value();
1888            let run = agent_session();
1889            let provenance = InvocationProvenance::caller(b"agent:ada").within(&run);
1890            let mut doc = AutoCommit::new();
1891            let mut transport = LocalTransport::new();
1892
1893            invoke_json(
1894                &mut doc,
1895                &resources,
1896                &edit(),
1897                &title("Harbour"),
1898                (provenance, false),
1899                &registry(),
1900                &mut transport,
1901            )
1902            .expect("an ordinary value runs");
1903            assert_recorded_within_run(&mut doc, "edit");
1904
1905            invoke_json(
1906                &mut doc,
1907                &resources,
1908                &edit(),
1909                &title(""),
1910                (provenance, true),
1911                &registry(),
1912                &mut transport,
1913            )
1914            .expect("a confirmed destructive value runs");
1915            assert_eq!(stored_title(&doc).as_deref(), Some(""));
1916            assert_recorded_within_run(&mut doc, "edit");
1917        }
1918    }
1919
1920    fn effective_confirmation_reads_every_argument_form() {
1921        let resources = edit_by_value();
1922        let spec = resolve(&resources, &edit()).unwrap();
1923        let none = crate::ConfirmationPolicy::None;
1924        let confirm = crate::ConfirmationPolicy::Confirm;
1925        assert_eq!(spec.confirmation_for_json(&title("x")), none);
1926        assert_eq!(spec.confirmation_for_json(&title("")), confirm);
1927        assert_eq!(spec.confirmation_for_argument(Some("x")), none);
1928        assert_eq!(spec.confirmation_for_argument(Some("")), confirm);
1929        let typed = format!("{}{{\"title\":\"\"}}", crate::ARGUMENTS_JSON_PREFIX);
1930        assert_eq!(spec.confirmation_for_argument(Some(&typed)), confirm);
1931        // Arguments that cannot bind build nothing, so they get the declared policy.
1932        assert_eq!(spec.confirmation_for_json(&serde_json::Map::new()), none);
1933
1934        assert!(!spec.reaches_people() && !spec.contract.reaches_people());
1935        assert!(spec.contract.confirmation_depends_on_arguments());
1936        assert_eq!(spec.contract.confirmation, none);
1937        assert_eq!(spec.contract.advertised_confirmation(), confirm);
1938        assert!(spec.contract.validate_declaration().is_empty());
1939
1940        // A declared policy is never weakened by a classifier.
1941        let declared = spec.clone().destructive();
1942        assert_eq!(declared.confirmation_for_json(&title("x")), confirm);
1943    }
1944
1945    const OP: &str = "test.operation";
1946
1947    /// A session with a renamable name, a step it cannot take now, a disk erased only by its
1948    /// typed name and a power switch that asks to be confirmed.
1949    fn published_tree() -> Vec<ResourceSpec> {
1950        use crate::{ActionContract, ConfirmationPolicy, ParamType, RiskLevel};
1951        let encode =
1952            |value: serde_json::Value| EncodedAction::encode_operation(OP, &value).unwrap();
1953        vec![
1954            ResourceSpec::new("session", "test.session", "Session")
1955                .with_action(ActionSpec::typed_operation(
1956                    "rename",
1957                    "Rename",
1958                    "name",
1959                    OperationKind::Effect,
1960                    OP,
1961                    vec![crate::ActionParam::required(
1962                        "name",
1963                        ParamType::Text,
1964                        "New name",
1965                    )],
1966                    move |args| encode(serde_json::json!({"rename": args.text("name")})),
1967                ))
1968                .with_action(
1969                    ActionSpec::operation("reset", "Reset", OperationKind::Effect, OP, &"reset")
1970                        .unwrap()
1971                        .unavailable("not_now", "Finish the current step first"),
1972                )
1973                .with_child(
1974                    ResourceSpec::new("disk:/dev/vdb", "test.disk", "vdb").with_action(
1975                        ActionSpec::operation(
1976                            "erase",
1977                            "Erase",
1978                            OperationKind::Effect,
1979                            OP,
1980                            &"erase",
1981                        )
1982                        .unwrap()
1983                        .destructive()
1984                        .with_contract(ActionContract {
1985                            risk: RiskLevel::Destructive,
1986                            confirmation: ConfirmationPolicy::Phrase {
1987                                phrase: "/dev/vdb".into(),
1988                            },
1989                            ..ActionContract::default()
1990                        }),
1991                    ),
1992                )
1993                .with_child(
1994                    ResourceSpec::new("power", "test.power", "Power").with_action(
1995                        ActionSpec::operation(
1996                            "off",
1997                            "Power off",
1998                            OperationKind::Effect,
1999                            OP,
2000                            &"off",
2001                        )
2002                        .unwrap()
2003                        .privileged(),
2004                    ),
2005                ),
2006        ]
2007    }
2008
2009    #[test]
2010    fn a_published_tree_is_listed_and_admits_only_exact_confirmed_bindings() {
2011        use crate::remote::{CataloguePage, CatalogueQuery, Confirmation};
2012        let tree = published_tree();
2013        let page = CataloguePage::published("test", &tree, &CatalogueQuery::default());
2014        // A listing is one level: the session's own actions, then what it holds.
2015        assert_eq!(page.rows.len(), 2);
2016        assert!(page.rows.iter().all(|row| row.provider == "test"));
2017        let held = CatalogueQuery {
2018            parent_resource: Some("session".into()),
2019            ..CatalogueQuery::default()
2020        };
2021        let held = CataloguePage::published("test", &tree, &held);
2022        assert_eq!(held.rows.len(), 2);
2023        let erase = held
2024            .rows
2025            .iter()
2026            .find_map(|row| row.action.as_ref().filter(|a| a.address.action == "erase"))
2027            .unwrap();
2028        assert_eq!(erase.address.resource, "disk:/dev/vdb");
2029        let narrowed = CatalogueQuery {
2030            needle: "power".into(),
2031            parent_resource: Some("session".into()),
2032            ..CatalogueQuery::default()
2033        };
2034        assert_eq!(
2035            CataloguePage::published("test", &tree, &narrowed)
2036                .rows
2037                .len(),
2038            1
2039        );
2040
2041        let args = |value: serde_json::Value| value.as_object().unwrap().clone();
2042        let admitted = |resource: &str, action: &str, value, confirmation: Option<Confirmation>| {
2043            admit(
2044                &tree,
2045                &ActionAddress::new(resource, action),
2046                &args(value),
2047                confirmation.as_ref(),
2048            )
2049        };
2050        assert_eq!(
2051            admitted("session", "rename", serde_json::json!({"name": "x"}), None)
2052                .unwrap()
2053                .type_id,
2054            OP
2055        );
2056        for (resource, action, value, refusal) in [
2057            ("session", "nope", serde_json::json!({}), "unknown"),
2058            ("session", "rename", serde_json::json!({}), "argument"),
2059            (
2060                "session",
2061                "rename",
2062                serde_json::json!({"name": 3}),
2063                "argument",
2064            ),
2065            (
2066                "session",
2067                "rename",
2068                serde_json::json!({"name": "x", "extra": 1}),
2069                "argument",
2070            ),
2071            ("session", "reset", serde_json::json!({}), "unavailable"),
2072        ] {
2073            let error = admitted(resource, action, value, None).unwrap_err();
2074            let kind = match error {
2075                ApiError::Unknown(_) => "unknown",
2076                ApiError::Unavailable { .. } => "unavailable",
2077                ApiError::MissingArgument(_)
2078                | ApiError::UnexpectedArgument(_)
2079                | ApiError::InvalidArguments(_) => "argument",
2080                other => panic!("{other:?}"),
2081            };
2082            assert_eq!(kind, refusal, "{action}");
2083        }
2084        let erase = |confirmation| {
2085            admitted(
2086                "disk:/dev/vdb",
2087                "erase",
2088                serde_json::json!({}),
2089                confirmation,
2090            )
2091        };
2092        for wrong in [
2093            None,
2094            Some(Confirmation::Phrase("/dev/vda".into())),
2095            Some(Confirmation::Operated),
2096        ] {
2097            assert!(matches!(erase(wrong), Err(ApiError::ConfirmationRequired)));
2098        }
2099        assert!(erase(Some(Confirmation::Phrase("/dev/vdb".into()))).is_ok());
2100        // A yes only the person gives: nothing the caller writes answers it.
2101        let off = |confirmation| admitted("power", "off", serde_json::json!({}), confirmation);
2102        for claimed in [
2103            None,
2104            Some(Confirmation::Operated),
2105            Some(Confirmation::Phrase("off".into())),
2106        ] {
2107            assert!(matches!(off(claimed), Err(ApiError::ConfirmationRequired)));
2108        }
2109    }
2110}