Skip to main content

tilo_resource/
resource.rs

1//! The resource contract: what any resource type provides so that it gets
2//! history, undo, collaboration, permissions, palette/agent/script exposure,
3//! search and replay without writing any of them.
4
5use std::any::TypeId;
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex, OnceLock};
8
9use serde::Serialize;
10use serde::de::DeserializeOwned;
11use tilo_actions::{
12    ActionArgs, ActionError, ActionNeed, ActionParam, ActionRegistry, ActionSpec, ActionType,
13    EncodedAction, ExecutionLocus, OperationKind, ParamType, Target,
14};
15
16use crate::action::ActionKind;
17use crate::delta::Delta;
18use crate::model::{Doc, ModelError};
19use crate::path::Edit;
20use crate::reader::Demand;
21use crate::vocabulary::{Builds, Built, Declaration, Vocabulary, vocabulary};
22use tilo_lock::MutexRecover as _;
23
24mod head;
25pub use head::{HeadInputs, head_inputs, publish_head, publish_head_of};
26
27mod search_entry;
28pub use search_entry::{SearchBody, SearchEntry, SearchPiece, SearchText, SearchWeight};
29
30/// A resource type. `#[resource]` implements it for a `#[derive(Model)]`
31/// record, which is how every app declares its own. The SDK implements it by
32/// hand for the shared types with a storage layout of their own (a rich-text
33/// document, plain text), which apps hold as fields; an app never does
34/// (docs/architecture/resources.md §8).
35///
36/// The contract is deliberately small:
37///
38/// * [`read`](Self::read) — materialise the state views render, from the live
39///   document *or* from any historical version (time travel is just `read` on
40///   an older document);
41/// * [`refresh`](Self::refresh) — optionally, bring a state up to date after a
42///   change by re-reading only what the change touched, so an edit costs as
43///   much as the edit rather than as much as the resource;
44/// * [`load`](Self::load) — optionally, read on demand the parts of a large
45///   resource that views are looking at (the pages of a long document on
46///   screen), so opening or refreshing it never reads all of it;
47/// * [`Action`](Self::Action) — the replayable mutation vocabulary: a
48///   serializable value whose `apply` is a pure function of the document;
49/// * [`declarations`](Self::declarations) — which mutations are offered by
50///   name to the palette, agents and scripts, with typed parameters.
51///
52/// Everything else has a default.
53pub trait Resource: Sized + 'static {
54    /// Stable kind of record this resource lives in, e.g. `"notes.notebook"`.
55    const KIND: &'static str;
56    /// Human name of one resource of this kind, e.g. `"Notebook"`, in the
57    /// language the declaration is written in. What a person reads is
58    /// [`label`](Self::label), which a host's catalogue translates.
59    const LABEL: &'static str;
60    /// The catalogue beside the crate that declares it, whose entry under
61    /// the kind's [`message_key`](crate::label::message_key) names it in
62    /// each language: `None` reads only the catalogues the host loaded.
63    const CATALOGUE: Option<&'static crate::label::Catalogue> = None;
64    /// The app that publishes records of this kind, e.g. `"so.tilo.notes"`:
65    /// the framework app's id, or for a resource that names its app in its
66    /// `#[resource(app = "…")]` declaration, that. It is part of the
67    /// [`ActionKey`](tilo_actions::ActionKey) every typed reference of the
68    /// resource names its actions by.
69    const APP_ID: &'static str = crate::kind::DEFAULT_APP;
70    /// The registry type id every action of this resource is replayed under.
71    const ACTION_TYPE: &'static str = Self::KIND;
72
73    /// The name a person reads this kind by, in their language: what
74    /// [`LABEL`](Self::LABEL) declares, resolved through the catalogue a
75    /// host installed ([`crate::label`]), so every kind is named in the
76    /// language of the desktop it is published on.
77    fn label() -> String {
78        crate::label::localized(Self::KIND, Self::LABEL, Self::CATALOGUE)
79    }
80
81    /// What views render. For a record resource this is the record itself.
82    type State: 'static;
83    /// The replayable mutation. Must be deterministic: no clock, no RNG, no
84    /// local state — use [`ActionCx`](crate::ActionCx) for ids and time.
85    type Action: tilo_actions::Action + Serialize + DeserializeOwned + Clone + 'static;
86
87    /// Read the state from a document.
88    ///
89    /// # Errors
90    /// Returns [`ModelError`] when the document does not hold this resource.
91    fn read(doc: &Doc) -> Result<Self::State, ModelError>;
92
93    /// Bring `state`, read earlier from this document, up to date after the
94    /// changes in `delta`. Re-read only what they touched: this runs on every
95    /// keystroke, local or a member's. The default reads everything
96    /// again, which is right for small resources.
97    ///
98    /// # Errors
99    /// Returns [`ModelError`] when the document does not hold this resource.
100    fn refresh(state: &mut Self::State, doc: &Doc, delta: &Delta) -> Result<(), ModelError> {
101        if !delta.is_empty() {
102            *state = Self::read(doc)?;
103        }
104        Ok(())
105    }
106
107    /// A copy of `state` for [`refresh`](Self::refresh) to bring up to date
108    /// while the state the reader holds is shared (a view still holds the
109    /// last one): refreshing a copy reads only what a change touched, where
110    /// without one the state is read whole. `#[resource]` copies a `Clone`
111    /// record; the default has none.
112    fn copy_state(_state: &Self::State) -> Option<Self::State> {
113        None
114    }
115
116    /// Opt in to reusing the document-owned publication between changes.
117    ///
118    /// Return an epoch for every non-document input used by declarations,
119    /// children, views or local operations (for example the local date of a
120    /// daily-note action). The framework also invalidates on state and locale
121    /// revisions; surface bindings and effect availability remain live.
122    /// `None` preserves publication on every request for dynamic resources.
123    fn publication_cache_epoch(_state: &Self::State) -> Option<String> {
124        None
125    }
126
127    /// Where `obj` sits in the document, when the state already knows: the
128    /// path from the root to it. A change to an object the state has read
129    /// (the paragraph being typed in) is then placed without asking the
130    /// document, which for a large document is the costly part of reading a
131    /// change. The default knows nothing, and the document is asked.
132    fn locate(state: &Self::State, obj: &automerge::ObjId) -> Option<crate::delta::ObjPath> {
133        let _ = (state, obj);
134        None
135    }
136
137    /// Make sure the parts of the state views asked for are read, and drop
138    /// parts nobody asks for any more. For a resource too large to read
139    /// whole, [`read`](Self::read) reads a spine (the order of a document's
140    /// paragraphs, the rows of a sheet) and this reads the parts on screen.
141    /// Called after every read and refresh and whenever the demand changes,
142    /// so it must be cheap when everything demanded is already there. The
143    /// default reads nothing: the state is read whole.
144    ///
145    /// # Errors
146    /// Returns [`ModelError`] when the document does not hold this resource.
147    fn load(state: &mut Self::State, doc: &Doc, demand: &Demand) -> Result<(), ModelError> {
148        let _ = (state, doc, demand);
149        Ok(())
150    }
151
152    /// Write the initial content of a brand-new record: its genesis.
153    ///
154    /// The genesis is made under an actor derived from the record's identity,
155    /// at time zero, so it is the same change byte for byte on every device:
156    /// two people who each create the same record before they sync (a
157    /// workspace's default record, the record of one file) converge on one
158    /// record rather than two competing roots. It must therefore depend on
159    /// nothing but the resource type — not on who creates it, the device, the
160    /// clock or a file. Content that does depend on those (the creator as
161    /// owner, a first-run import of settings that already exist) is the app's
162    /// seed, applied as actions right after the genesis (`ResourceApp::seed`
163    /// in `tilo-app`).
164    fn initialize(_doc: &mut Doc) -> Result<(), ModelError> {
165        Ok(())
166    }
167
168    /// Whether `next`, applied right after `previous` by the same person,
169    /// continues it as one undo step — the characters of a word typed one
170    /// keystroke at a time, the values a slider passes through in one drag.
171    /// The default keeps every action its own step.
172    ///
173    /// Immediate edits (`Dispatcher::apply_now` in `tilo-app`) and native
174    /// keyboard/IME edits from action-bound text fields may continue one
175    /// another. Programmatic/agent invocations remain separate steps.
176    /// A surface ends an immediate pointer gesture
177    /// (`Dispatcher::settle`) when the pointer is let go, so the next drag
178    /// of the same slider is a step of its own.
179    fn coalesces(previous: &Self::Action, next: &Self::Action) -> bool {
180        let _ = (previous, next);
181        false
182    }
183
184    /// Whether a later action may continue `action` ([`coalesces`](Self::coalesces)),
185    /// so its undo step stays open for it. One that never continues — a
186    /// paragraph split after a typed word, a block moved — is a step of its
187    /// own, recorded at once. The default keeps every step open for what may
188    /// follow.
189    fn continuable(action: &Self::Action) -> bool {
190        let _ = action;
191        true
192    }
193
194    /// Where `action`, just applied, leaves the member who took it, read
195    /// off the state after it: the paragraph an append wrote and the caret
196    /// at its end. Every member's view draws that member there,
197    /// so one with no pointer or caret of its own (an agent) shows where it
198    /// works. The default places it nowhere in particular.
199    fn lands(state: &Self::State, action: &Self::Action) -> Option<Place> {
200        let _ = (state, action);
201        None
202    }
203
204    /// Whether [`Self::lands`] reads the state to place whoever took
205    /// `action`: `false` where it places them nowhere whatever the state
206    /// holds, so a host placing them after each action need not read a
207    /// record of thousands of items to learn that. The default reads it.
208    fn lands_on_state(action: &Self::Action) -> bool {
209        let _ = action;
210        true
211    }
212
213    /// The field `action` sets when it is the edit of one field (`set-<field>`): what the person
214    /// chose there, kept as their choice even where it is what the record already reads. `None`
215    /// by default, and for every other action.
216    fn set_field(action: &Self::Action) -> Option<String> {
217        let _ = action;
218        None
219    }
220
221    /// The one field of the record `action` writes, when it writes only one:
222    /// a reply or a note writes the `comments`, so a grant on that field
223    /// (what someone who may only comment holds) reaches it. `None` by
224    /// default. A declared action that builds it names the same field with
225    /// [`ActionDecl::below_field`].
226    fn field_of(action: &Self::Action) -> Option<&'static str> {
227        let _ = action;
228        None
229    }
230
231    /// The least any of the resource's actions is ([`kind_of`](Self::kind_of),
232    /// [`field_of`](Self::field_of)): what the generic [`APPLY`] and group
233    /// actions are offered under, each invocation then decided by what its
234    /// value is. An undoable change of the record by default; an undoable
235    /// change of its `comments` for a resource someone who may only comment
236    /// can still reply in.
237    fn least_need() -> ActionNeed {
238        least_need_declared(&vocabulary::<Self>().declarations())
239    }
240
241    /// Mutations offered by name. The generic [`APPLY`] action is always
242    /// offered in addition, so any typed value can reach the host.
243    fn declarations() -> Vec<ActionDecl<Self>> {
244        Vec::new()
245    }
246
247    /// The JSON Schema of [`Action`](Self::Action)'s serde form, published as
248    /// the schema of the generic [`APPLY`] operation's argument, so agents
249    /// and scripts can read the edit vocabulary from the descriptor and
250    /// binding refuses a malformed edit by name. A variant that only
251    /// restates a declaration is published as a reference to it. Return `Some(<Self::Action as
252    /// JsonSchema>::json_schema())` for an action type deriving
253    /// [`JsonSchema`](crate::JsonSchema); `#[resource]` describes its
254    /// operations from their declarations. The default publishes no schema.
255    fn action_schema() -> Option<serde_json::Value> {
256        None
257    }
258
259    /// Resources nested inside this one (a track's clips, a list's items,
260    /// a page's rich-text body), each exporting actions with their arguments
261    /// already bound. Published beneath the root resource for the palette,
262    /// agents and scripts — the same API as the root, not a second tree.
263    fn children(_state: &Self::State) -> Vec<tilo_actions::ResourceSpec> {
264        Vec::new()
265    }
266
267    /// The effects offered on the item `item` of the collection `field`,
268    /// bound to it (`#[resource(effects = E)]` with `#[effect(item = field)]`
269    /// variants): published on the item resource beside its item verbs.
270    fn item_effects(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ActionSpec> {
271        Vec::new()
272    }
273
274    /// The views the item `item` of the collection `field` offers
275    /// (`#[resource(item_views = path)]`): published on the item resource,
276    /// so a link to the item opens it in one, each opened by one of the
277    /// item's own actions ([`item_effects`](Self::item_effects)).
278    fn item_views(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ResourceViewSpec> {
279        Vec::new()
280    }
281
282    /// [`children`](Self::children) split into the children that are not
283    /// items and the items of the record's collections, so a publisher can
284    /// keep the item children it built for an earlier version and build
285    /// only those whose label changed. `others` followed by
286    /// [`item_children`](crate::items::item_children) of the rest must be
287    /// exactly `children`. The default puts every child in `others`;
288    /// `#[resource]` splits off its item collections.
289    fn children_parts(state: &Self::State) -> crate::items::ChildrenParts {
290        crate::items::ChildrenParts {
291            others: Self::children(state),
292            kept: std::rc::Rc::default(),
293            items: Vec::new(),
294            item_actions: Vec::new(),
295        }
296    }
297
298    /// The ids of the [`declarations`](Self::declarations) that
299    /// [`children`](Self::children) offer on some child with arguments
300    /// already bound (an item action on each item of a list), which the
301    /// resource then publishes for scripts rather than the palette.
302    ///
303    /// [`publish_head`] asks this to publish the resource's own actions
304    /// without building its children, so a resource with many children
305    /// answers from what it knows about them: `#[resource]` from how many
306    /// items each collection holds. The default builds the children and
307    /// looks.
308    fn children_offer_bound(state: &Self::State) -> Vec<&'static str> {
309        offered_bound_ids(&Self::children(state), &vocabulary::<Self>().declarations())
310    }
311
312    /// The nested resource `id`, when [`children`](Self::children) leaves it
313    /// out. A resource with more children than a published tree should carry
314    /// (a book of contacts, a long history) publishes a bounded page from
315    /// `children` and resolves the rest here, so an action addressed to any
316    /// of them still reaches it through the same API. The default resolves
317    /// nothing beyond `children`.
318    fn child(_state: &Self::State, _id: &str) -> Option<tilo_actions::ResourceSpec> {
319        None
320    }
321
322    /// View and effect operations on this resource: local presentation and
323    /// jobs that have no document delta (show a week, start a sync drain,
324    /// open a system file picker). They are published on the same tree as
325    /// [`declarations`](Self::declarations). A document mutation does not
326    /// belong here — it is a [`declarations`](Self::declarations) entry or
327    /// [`APPLY`]. `publish` drops a `Document` spec so it cannot become a
328    /// second write path.
329    fn local_operations() -> Vec<tilo_actions::ActionSpec> {
330        Vec::new()
331    }
332
333    /// Named presentations of this resource (editor, reader) with stable ids.
334    /// Not an action called `open`: ordinary presentation toggles never become
335    /// composable views by accident. Defaults to none.
336    fn views(_state: &Self::State) -> Vec<tilo_actions::ResourceViewSpec> {
337        Vec::new()
338    }
339
340    /// Entries for the system search index.
341    fn search_scopes(_state: &Self::State) -> Vec<ScopeDecl> {
342        Vec::new()
343    }
344
345    fn search(_state: &Self::State) -> Vec<SearchEntry> {
346        Vec::new()
347    }
348
349    /// Whether [`read_content`](Self::read_content) answers. A resource that
350    /// does is published with the framework's `read` operation, so a script,
351    /// an agent or an assistive tool reads what it holds as typed data through
352    /// the same API, permissions and audit as every other action — never
353    /// from a screenshot.
354    const READABLE: bool = false;
355
356    /// Whether this exact child is part of the public document projection
357    /// answered by `read_content`. Defaults to false even for readable parents.
358    /// This is a structural declaration, not a permission check: it must not
359    /// perform IO, inspect private view state, or probe by executing a read.
360    /// Eligibility must remain stable while the child's identity exists.
361    fn document_child(_state: &Self::State, _id: &str) -> bool {
362        false
363    }
364
365    /// What the resource holds, as JSON a caller can act on: with no `item`,
366    /// the resource itself (a notebook's pages); with `item`, the nested
367    /// resource of that id from [`children`](Self::children) (one page's
368    /// title and blocks). Read from `doc`, the committed document, so the
369    /// answer is never older than the action that preceded it. Called only
370    /// when [`READABLE`](Self::READABLE) is set.
371    fn read_content(
372        state: &Self::State,
373        doc: &Doc,
374        item: Option<&str>,
375    ) -> Result<serde_json::Value, String> {
376        let _ = (state, doc, item);
377        Err(format!("a {} does not answer reads", Self::LABEL))
378    }
379
380    /// Whether [`facts`](Self::facts) answers. A resource that does is
381    /// published with the framework's `facts` read, which an agent's host
382    /// shows when it checks work done on the resource.
383    const HAS_FACTS: bool = false;
384
385    /// The record's own table, for a resource that is a record: what
386    /// generic code reads a field's value through without the record's type
387    /// (the framework, a window's [`Reactions`](crate::Reactions) with
388    /// [`record_reactions`](crate::reactions::record_reactions)).
389    /// `#[resource]` names the record's; none otherwise.
390    const RESOURCE_TABLE: Option<&'static crate::table::ModelTable> = None;
391
392    /// What the resource holds as a compact summary of plain values, meant
393    /// for checking it against a request: names, times, counts and text as
394    /// a person would state them (a cut's shots with their source, in and
395    /// out points; a deck's slide titles), not ids or storage. Two answers
396    /// compare field by field, so keep a list's order meaningful and its
397    /// items' keys stable. Called only when [`HAS_FACTS`](Self::HAS_FACTS)
398    /// is set.
399    fn facts(state: &Self::State, doc: &Doc) -> Result<serde_json::Value, String> {
400        let _ = (state, doc);
401        Err(format!("a {} states no facts", Self::LABEL))
402    }
403
404    /// Whether [`Self::answer`] answers anything. Working out the changes it
405    /// reads costs as much as the change is large, so a resource whose
406    /// answer is the default's nothing is not asked. `#[resource]` sets it
407    /// with `answer = path`.
408    const ANSWERS: bool = false;
409
410    /// What declared action `action` (one [`ActionDecl::answering`]) made,
411    /// answered to its caller once it applied to `doc` as `changes`: the
412    /// ids it minted, the area it selected, a warning that what it drew is
413    /// hidden. A compact summary, so the caller needs no second read to
414    /// see what happened. The default answers nothing.
415    fn answer(
416        _doc: &Doc,
417        _action: &str,
418        _changes: &[automerge::Patch],
419    ) -> Option<serde_json::Value> {
420        None
421    }
422
423    /// The stored layout of this resource's content, for services that act
424    /// on it generically: History restores a past version through it, field
425    /// by field and item by item. `#[resource]` returns the record's
426    /// [`Model::SHAPE`](crate::Model::SHAPE); the default opts out.
427    fn shape() -> Option<crate::Shape> {
428        None
429    }
430
431    /// The state as its record's JSON ([`Model::to_json`](crate::Model::to_json)):
432    /// what a field that weakens one way holds now. `#[resource]` returns
433    /// the record's; the default knows none, so any change of such a field
434    /// counts as weakening.
435    fn state_json(state: &Self::State) -> Option<serde_json::Value> {
436        let _ = state;
437        None
438    }
439
440    /// The storage version documents of this resource are written at;
441    /// `#[resource(version = N)]` raises it with each incompatible change
442    /// and [`Self::migrate`] brings older documents up to it.
443    const VERSION: u32 = 1;
444
445    /// Who reads a record of this kind, when not every member of the
446    /// workspace: `"author"`, `"author until <field>"` or a `Set<Actor>`
447    /// field's name, as `#[resource(readers = "...")]` writes it
448    /// ([`tilo_actions::surface::ReaderRule`]); empty for every member.
449    const READERS: &'static str = "";
450
451    /// Bring a document stored at version `from` up to [`Self::VERSION`],
452    /// reading its old shape with the model helpers. Called once per
453    /// document by [`crate::evolution::rewrite`], after its derived steps.
454    fn migrate(doc: &mut Doc, from: u32) -> Result<(), ModelError> {
455        let _ = doc;
456        Err(ModelError::invalid(format!(
457            "{} has no migration from storage version {from}",
458            Self::LABEL
459        )))
460    }
461
462    /// The public surface: verbs, their parameters and kinds, and the
463    /// stored fields ([`crate::surface`]).
464    #[must_use]
465    fn surface() -> crate::surface::Surface {
466        crate::surface::surface_of::<Self>()
467    }
468
469    /// Whether the resource's actions include field edits ([`Edit`]),
470    /// published as [`FIELD_EDIT`]. `#[resource]` records have them.
471    const EDITS: bool = false;
472
473    /// The action a field edit of this resource is, when it has field edits
474    /// ([`Self::EDITS`]).
475    fn edit_action(edit: Edit<Self>) -> Option<Self::Action> {
476        let _ = edit;
477        None
478    }
479
480    /// Stamp the origin's clock on an action as the API admits it. A caller
481    /// never supplies the time an action carries.
482    fn stamp(action: &mut Self::Action, now_ms: i64) {
483        let _ = (action, now_ms);
484    }
485
486    /// The schemas of the own vocabularies of the record's fields
487    /// ([`Operations`](crate::Operations)), by field path pattern (`*` for
488    /// every item): what a field edit in that vocabulary carries.
489    fn op_schemas() -> Vec<(String, serde_json::Value)> {
490        Vec::new()
491    }
492
493    /// Whether the declared action `action` can be taken in `state`, and why
494    /// not when it cannot. `#[resource(available = path)]` answers it.
495    fn availability(state: &Self::State, action: &str) -> tilo_actions::Availability {
496        let _ = (state, action);
497        tilo_actions::Availability::Available
498    }
499
500    /// The first content of a new record, written by its creator once it is
501    /// created: nobody's undo step. `#[resource(seed = path)]` provides it.
502    fn seed() -> Option<Self::Action> {
503        None
504    }
505
506    /// What kind of action `action` is: whether it only reads, changes only
507    /// the document, or reaches outside it. Derived by `#[resource]` from
508    /// what each verb is able to do, never declared.
509    fn kind_of(action: &Self::Action) -> ActionKind {
510        let _ = action;
511        ActionKind::Undoable
512    }
513
514    /// Whether `action` is one only the app's own code applies
515    /// (`#[action(by_app)]`): the app's bookkeeping of the record, such as
516    /// what its engine listed. It has no declaration, so it is not
517    /// published, nothing builds it by its id, and the generic [`APPLY`] and
518    /// every API that decodes an action refuse it ([`by_app_refusal`]).
519    /// The app applies it to a record it holds.
520    fn by_app(action: &Self::Action) -> bool {
521        let _ = action;
522        false
523    }
524
525    /// The action `id` only the app's own code applies, built from
526    /// `arguments` where the app invokes it
527    /// ([`Invoke::build`](crate::Invoke::build)); `None` for any other id.
528    /// `#[resource]` generates it.
529    fn build_by_app(
530        id: &str,
531        arguments: &serde_json::Map<String, serde_json::Value>,
532        now_ms: i64,
533    ) -> Option<Result<Self::Action, String>> {
534        let _ = (id, arguments, now_ms);
535        None
536    }
537
538    /// The item of the resource's collections `action` acts on: an item verb's
539    /// (its first parameter), or the one a field edit's path passes through.
540    /// What a store keeping a collection's items in several resources routes
541    /// the action by. `#[resource]` generates it; `None` by default.
542    fn action_item(action: &Self::Action) -> Option<crate::Id> {
543        let _ = action;
544        None
545    }
546
547    /// The entries `action` lists that each name an item, in order: the
548    /// item an entry names, or `None` for an entry that makes a new one
549    /// (a message arriving). A verb declares the parameter it lists them in
550    /// with `#[action(items = param)]`; `None` for any other action.
551    fn listed_items(action: &Self::Action) -> Option<Vec<Option<crate::Id>>> {
552        let _ = action;
553        None
554    }
555
556    /// `action`, a verb listing items ([`listed_items`](Self::listed_items)),
557    /// over only its entries at the positions `keep`: the share of it a
558    /// resource holding those items carries out.
559    fn keep_listed(action: &Self::Action, keep: &[usize]) -> Option<Self::Action> {
560        let _ = (action, keep);
561        None
562    }
563
564    /// Register this resource's replay decoder. Override to register an
565    /// existing vocabulary under additional type ids.
566    fn register(registry: &mut ActionRegistry) {
567        registry.register::<Self::Action>(Self::ACTION_TYPE);
568    }
569}
570
571/// An entry of a verb's list of items (`#[action(items = param)]`): the item
572/// it names, or `None` when it makes a new one.
573pub trait NamesItem: Clone {
574    fn named_item(&self) -> Option<crate::Id>;
575}
576
577impl NamesItem for crate::Id {
578    fn named_item(&self) -> Option<crate::Id> {
579        Some(self.clone())
580    }
581}
582
583impl NamesItem for String {
584    fn named_item(&self) -> Option<crate::Id> {
585        Some(crate::Id::from_raw(self.clone()))
586    }
587}
588
589/// [`Resource::listed_items`] of the list `entries`.
590#[doc(hidden)]
591pub fn listed_of<E: NamesItem>(entries: &[E]) -> Vec<Option<crate::Id>> {
592    entries.iter().map(NamesItem::named_item).collect()
593}
594
595/// The entries of `entries` at the positions `keep`, in order.
596#[doc(hidden)]
597#[must_use]
598pub fn kept_of<E: NamesItem>(entries: &[E], keep: &[usize]) -> Vec<E> {
599    keep.iter()
600        .filter_map(|at| entries.get(*at).cloned())
601        .collect()
602}
603
604/// The id of the action every resource publishes that applies one typed
605/// [`Resource::Action`] given as JSON. It is how a custom surface, an agent or
606/// a script submits an edit that has no named declaration (a drag with its
607/// final geometry) through the same permission-checked, undoable path.
608///
609/// It is for agents ([`tilo_actions::Audience::Agents`]): never offered in
610/// the palette or a menu, where a
611/// person picks named actions. Its risk is the value's own
612/// ([`tilo_actions::Action::risk`]), so a destructive value — deleting a clip —
613/// needs the same confirmation a declared destructive action does, while an
614/// ordinary edit applies directly.
615pub const APPLY: &str = "apply";
616/// The parameter of [`APPLY`] carrying the JSON-encoded action.
617pub const APPLY_PARAM: &str = "action";
618
619/// The id of the action a resource with field edits ([`Resource::EDITS`])
620/// publishes for them: one [`Edit`] given as JSON, a path and an operation.
621pub const FIELD_EDIT: &str = "field-edit";
622/// The parameter of [`FIELD_EDIT`] carrying the edit.
623pub const EDIT_PARAM: &str = "edit";
624
625/// Read a field edit given as JSON into the action it is.
626fn read_edit(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
627    let edit = vocabulary.rooted_edit(Edit::<()>::from_json(value)?)?;
628    match (vocabulary.edit)(edit) {
629        Some(action) => Ok(action),
630        None => Err(format!("{} has no field edits", vocabulary.label)),
631    }
632}
633
634/// The schema of a field edit of `R`: one alternative per editable path of
635/// its stored shape — the path's steps, the operations its type takes, the
636/// value it holds, its title and flags — so an agent builds a valid edit
637/// from the published descriptor alone. A resource without a shape gets
638/// the generic one, with its fields' own operations named for `rich`.
639pub(crate) fn edit_schema(vocabulary: &Vocabulary) -> serde_json::Value {
640    let ops = (vocabulary.op_schemas)();
641    if let Some(shape) = (vocabulary.shape)()
642        && !shape.fields().is_empty()
643    {
644        let mut alternatives = Vec::new();
645        edit_paths(shape, &[], "", &ops, &mut alternatives);
646        if !alternatives.is_empty() {
647            return described_edit(&alternatives, &ops);
648        }
649    }
650    generic_edit_schema(&ops, |_| true)
651}
652
653/// The schema a field edit is checked against, with every editable path
654/// described: its template, the operations it takes, the value's schema,
655/// its title and flags (the description), and one example edit per path
656/// (the examples) — what an agent builds a field edit from.
657fn described_edit(
658    alternatives: &[serde_json::Value],
659    ops: &[(String, serde_json::Value)],
660) -> serde_json::Value {
661    // The operations some path of the record takes: the schema names only
662    // those, and only their arguments.
663    let taken: Vec<String> = alternatives
664        .iter()
665        .filter_map(|alternative| alternative.pointer("/properties/op/enum")?.as_array())
666        .flatten()
667        .filter_map(serde_json::Value::as_str)
668        .map(str::to_owned)
669        .collect();
670    let mut schema = generic_edit_schema(ops, |op| taken.iter().any(|taken| taken == op));
671    let mut lines = vec![
672        "A field edit: `path` from the record (fields by name, items by id, map entries by key) and `op` with its arguments. Editable paths:".to_owned(),
673    ];
674    let mut examples = Vec::new();
675    let mut shapes: Vec<Vec<String>> = Vec::new();
676    // Each listed path, its line, and the fields named on that line when it
677    // is a record stored field by field.
678    let mut listed: Vec<(String, String, Vec<String>)> = Vec::new();
679    let nexts = alternatives.iter().skip(1).map(Some).chain([None]);
680    for (alternative, next) in alternatives.iter().zip(nexts) {
681        let at = |pointer: &str| alternative.pointer(pointer).cloned().unwrap_or_default();
682        let template = at("/properties/path/examples/0");
683        let ops: Vec<String> = at("/properties/op/enum")
684            .as_array()
685            .map(|ops| {
686                ops.iter()
687                    .filter_map(serde_json::Value::as_str)
688                    .map(str::to_owned)
689                    .collect()
690            })
691            .unwrap_or_default();
692        let value = at("/properties/value");
693        let text = |key: &str| at(key).as_str().unwrap_or_default().to_owned();
694        let title = text("/title");
695        // One example per shape of path (a field, an item's field, an
696        // entry): the listing names every path of each shape.
697        let shape: Vec<String> = template
698            .as_array()
699            .map(|steps| {
700                steps
701                    .iter()
702                    .filter_map(|step| step.as_object()?.keys().next().cloned())
703                    .collect()
704            })
705            .unwrap_or_default();
706        // A field of a record stored field by field, only ever set and with
707        // no paths inside it, is named on its record's line: its meaning is
708        // the record's, and a line of its own would repeat the record's
709        // path for every field.
710        let leaf = next.is_none_or(|next| {
711            next.get("title")
712                .and_then(serde_json::Value::as_str)
713                .is_none_or(|next| !next.starts_with(&format!("{title}.")))
714        });
715        let in_resource = shape
716            .iter()
717            .rev()
718            .take(2)
719            .filter(|kind| *kind == "field")
720            .count()
721            == 2;
722        let record = title
723            .rsplit_once('.')
724            .and_then(|(parent, key)| {
725                listed
726                    .iter_mut()
727                    .find(|(path, ..)| path == parent)
728                    .map(|(_, _, fields)| (fields, key))
729            })
730            .filter(|_| in_resource && leaf && ops == ["set"]);
731        if let Some((fields, key)) = record {
732            fields.push(format!("`{key}`"));
733        } else {
734            let kind = value_kind(&value);
735            let usage: Vec<String> = ops.iter().map(|op| crate::path::op_usage(op)).collect();
736            let line = format!(
737                "- `{title}`: {} — {}{}",
738                usage.join(", "),
739                text("/description"),
740                kind.map_or_else(String::new, |kind| format!(" ({kind})")),
741            );
742            listed.push((title.clone(), line, Vec::new()));
743        }
744        if shapes.contains(&shape) {
745            continue;
746        }
747        shapes.push(shape);
748        let mut example = serde_json::Map::new();
749        example.insert("path".into(), template);
750        if let Some(op) = ops.first() {
751            example.insert("op".into(), op.clone().into());
752        }
753        examples.push(serde_json::Value::Object(example));
754    }
755    lines.extend(listed.into_iter().map(|(_, line, fields)| {
756        if fields.is_empty() {
757            line
758        } else {
759            format!("{line}; set one field of it: {}", fields.join(", "))
760        }
761    }));
762    if let Some(object) = schema.as_object_mut() {
763        object.insert("description".into(), lines.join("\n").into());
764        object.insert("examples".into(), examples.into());
765    }
766    schema
767}
768
769/// The kind of value a schema describes, in a word or two, when it says one
770/// (`string`, `number`, `one of a, b`): what a path's line in the field-edit
771/// listing tells beside its operations. Objects are described by their own
772/// paths.
773fn value_kind(schema: &serde_json::Value) -> Option<String> {
774    if let Some(options) = schema.get("enum").and_then(serde_json::Value::as_array) {
775        let options: Vec<String> = options
776            .iter()
777            .map(|option| {
778                option
779                    .as_str()
780                    .map_or_else(|| option.to_string(), str::to_owned)
781            })
782            .collect();
783        return Some(format!("one of {}", options.join(", ")));
784    }
785    match schema.get("type")? {
786        serde_json::Value::String(kind) if kind != "object" => Some(kind.clone()),
787        serde_json::Value::Array(kinds) => Some(
788            kinds
789                .iter()
790                .filter_map(serde_json::Value::as_str)
791                .collect::<Vec<_>>()
792                .join(" or "),
793        ),
794        _ => None,
795    }
796}
797
798/// The generic field-edit schema, with the vocabularies of the record's
799/// fields' own operations named for `rich`.
800fn generic_edit_schema(
801    ops: &[(String, serde_json::Value)],
802    takes: impl Fn(&str) -> bool,
803) -> serde_json::Value {
804    let ops = ops.to_vec();
805    let mut schema = crate::path::edit_schema_taking(&takes);
806    if !ops.is_empty()
807        && takes("rich")
808        && let Some(properties) = schema
809            .get_mut("properties")
810            .and_then(serde_json::Value::as_object_mut)
811    {
812        // A field type's own vocabulary (rich text's) can outweigh the
813        // whole listing: it is summarised by its operations and their
814        // arguments, and checked when the edit applies. The summaries only
815        // describe, so they are one alternative: several describing
816        // alternatives (two drafts' bodies) would each match any edit.
817        let description = ops
818            .into_iter()
819            .map(|(path, schema)| {
820                format!(
821                    "An edit of `{path}` in its own vocabulary, one of: {}",
822                    crate::schema::summary(&schema)
823                )
824            })
825            .collect::<Vec<_>>()
826            .join("\n");
827        properties.insert(
828            "rich".into(),
829            crate::schema::one_of(vec![serde_json::json!({ "description": description })]),
830        );
831    }
832    schema
833}
834
835fn step_schema(kind: &str, value: serde_json::Value) -> serde_json::Value {
836    let mut properties = serde_json::Map::new();
837    properties.insert(kind.to_owned(), value);
838    serde_json::json!({
839        "type": "object",
840        "properties": properties,
841        "required": [kind],
842    })
843}
844
845/// The operations a field of `field`'s type takes, by its stored shape and
846/// type: a text stored whole (`#[model(atom)]`) is only ever set.
847fn field_ops(field: &crate::FieldShape, rich: bool) -> Vec<&'static str> {
848    let ty = field.ty;
849    // Who reacted with what: each invoker adds and takes back their own.
850    if ty.rsplit("::").next() == Some("Reactions") {
851        return vec!["react", "unreact"];
852    }
853    match field.shape {
854        crate::Shape::Collection(_) | crate::Shape::Keyed(_) => {
855            vec![
856                "upsert-item",
857                "insert-item",
858                "remove-item",
859                "move-to",
860                "set",
861            ]
862        }
863        // Rich text is written whole as markdown, or edited in its own
864        // vocabulary.
865        _ if rich => vec!["replace", "rich"],
866        _ if ty.starts_with("Counter") => vec!["add", "set"],
867        _ if ty.starts_with("Set<") => vec!["insert", "remove", "set"],
868        _ if ty.starts_with("Grid<") => vec![
869            "set-cell",
870            "insert-row",
871            "insert-column",
872            "remove-row",
873            "remove-column",
874        ],
875        _ if ty.starts_with("Outbox") => vec!["settle", "forget"],
876        crate::Shape::Map(_) => vec!["set", "remove-key"],
877        _ if ty == "String" && !field.atom => vec!["set", "splice", "replace"],
878        _ => vec!["set"],
879    }
880}
881
882/// Whether a field's type takes edits of its own that a read-only field still
883/// accepts: each invoker's own reaction, or the outside settling its outbox
884/// entry, as the record's table allows them.
885fn takes_own_verbs(field: &crate::FieldShape) -> bool {
886    let ops = field_ops(field, false);
887    ops.iter()
888        .any(|op| matches!(*op, "react" | "unreact" | "settle" | "forget"))
889}
890
891/// The vocabulary the value at `at` has of its own (a rich text's), when it
892/// has one.
893fn rich_schema_at<'a>(
894    rich: &'a [(String, serde_json::Value)],
895    at: &str,
896) -> Option<&'a serde_json::Value> {
897    rich.iter()
898        .find(|(path, _)| path == at)
899        .map(|(_, schema)| schema)
900}
901
902#[allow(
903    clippy::too_many_lines,
904    reason = "one walk over the stored shape, an alternative per kind of path"
905)]
906fn edit_paths(
907    shape: crate::Shape,
908    steps: &[serde_json::Value],
909    dotted: &str,
910    rich: &[(String, serde_json::Value)],
911    out: &mut Vec<serde_json::Value>,
912) {
913    let alternative = |steps: &[serde_json::Value],
914                       open: bool,
915                       ops: &[&str],
916                       value: serde_json::Value,
917                       rich: Option<&serde_json::Value>,
918                       title: &str,
919                       description: String| {
920        // The path as an agent writes it, items by a placeholder id.
921        let template: Vec<serde_json::Value> = steps
922            .iter()
923            .map(|step| {
924                let properties = step.get("properties").and_then(serde_json::Value::as_object);
925                match properties.and_then(|properties| properties.iter().next()) {
926                    Some((kind, value)) if kind == "field" => {
927                        serde_json::json!({ "field": value.get("const").cloned().unwrap_or_default() })
928                    }
929                    Some((kind, _)) => serde_json::json!({ kind.clone(): format!("<{kind}>") }),
930                    None => serde_json::Value::Null,
931                }
932            })
933            .collect();
934        let dotted: Vec<String> = template
935            .iter()
936            .map(
937                |step| match step.get("field").and_then(serde_json::Value::as_str) {
938                    Some(field) => field.to_owned(),
939                    None => "*".to_owned(),
940                },
941            )
942            .collect();
943        let mut path = serde_json::json!({
944            "type": "array",
945            "prefixItems": steps,
946            "minItems": steps.len(),
947            "examples": [template],
948        });
949        if let Some(path) = path.as_object_mut() {
950            if open {
951                // What is inside the entry or cell, by any steps.
952                path.insert("items".into(), serde_json::json!({ "type": "object" }));
953            } else {
954                path.insert("maxItems".into(), steps.len().into());
955            }
956        }
957        let mut properties = serde_json::Map::new();
958        properties.insert("path".into(), path);
959        properties.insert("op".into(), serde_json::json!({ "enum": ops }));
960        properties.insert("value".into(), value);
961        if ops.contains(&"upsert-item") {
962            properties.insert(
963                "match".into(),
964                serde_json::json!({
965                    "type": "object",
966                    "description": "upsert-item: the fields that identify the item, e.g. {\"name\": \"Ana\"}; it updates the one item holding them with `value`'s fields, else appends `value` as a new item"
967                }),
968            );
969            properties.insert(
970                "at".into(),
971                serde_json::json!({
972                    "description": "insert-item, move-to: \"end\" (the default), {\"after\": id} or {\"before\": id}",
973                    "anyOf": [
974                        { "const": "end" },
975                        { "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
976                        { "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
977                        { "type": "integer", "minimum": 0 }
978                    ]
979                }),
980            );
981        }
982        if let Some(rich) = rich {
983            properties.insert("rich".into(), rich.clone());
984        }
985        serde_json::json!({
986            "title": dotted.join("."),
987            "description": if description.is_empty() {
988                title.to_owned()
989            } else {
990                format!("{title}; {description}")
991            },
992            "type": "object",
993            "properties": properties,
994            "required": ["path", "op"],
995        })
996    };
997    let item = step_schema("item", serde_json::json!({ "type": "string" }));
998    // A read-only field is changed only by the record's verbs: no path an
999    // edit could take, save the verbs its own type keeps that a field edit
1000    // still applies (a reaction, a settled outbox entry).
1001    for field in shape
1002        .fields()
1003        .iter()
1004        .filter(|field| !field.readonly || takes_own_verbs(field))
1005    {
1006        let mut here = steps.to_vec();
1007        here.push(step_schema(
1008            "field",
1009            serde_json::json!({ "const": field.key }),
1010        ));
1011        let path = format!("{dotted}{}", field.key);
1012        let rich_schema = rich_schema_at(rich, &path);
1013        let ops = field_ops(field, rich_schema.is_some());
1014        let collection = matches!(
1015            field.shape,
1016            crate::Shape::Collection(_) | crate::Shape::Keyed(_)
1017        );
1018        // A value field's `set` takes its value; containers' operations
1019        // carry items, elements or keys of their own.
1020        let simple = ops.first() == Some(&"set") && !collection;
1021        let value = if simple {
1022            (field.schema)()
1023        } else {
1024            serde_json::json!({})
1025        };
1026        let mut flags = Vec::new();
1027        if field.unit {
1028            flags.push("its own storage unit".to_owned());
1029        }
1030        match field.trust {
1031            crate::Trust::Ordinary => {}
1032            crate::Trust::Sensitive => flags.push("changing it asks for confirmation".to_owned()),
1033            crate::Trust::Weakens(_) => flags.push(
1034                "making it weaker can weaken security: such a change asks for confirmation and needs the person's own grant; making it stricter does not"
1035                    .to_owned(),
1036            ),
1037            crate::Trust::Weakening => flags.push(
1038                "changing it can weaken security: it asks for confirmation and needs the person's own grant"
1039                    .to_owned(),
1040            ),
1041        }
1042        if collection {
1043            // A field edit changes only the record, so Undo takes a removed
1044            // item back and nobody is asked first.
1045            flags.push(if field.quiet_remove {
1046                "removing an item asks nothing".to_owned()
1047            } else {
1048                "removing an item asks nothing; Undo takes it back".to_owned()
1049            });
1050        }
1051        let description = flags.join("; ");
1052        out.push(alternative(
1053            &here,
1054            false,
1055            &ops,
1056            value,
1057            rich_schema,
1058            field.title,
1059            description,
1060        ));
1061        match field.shape {
1062            crate::Shape::Record(_) => {
1063                edit_paths(field.shape, &here, &format!("{path}."), rich, out);
1064            }
1065            crate::Shape::Collection(inner) | crate::Shape::Keyed(inner) => {
1066                let mut items = here.clone();
1067                items.push(item.clone());
1068                let item_value = (field.schema)().get("items").map_or_else(
1069                    || serde_json::json!({}),
1070                    |items| {
1071                        // A collection's JSON lists `{id, value}` entries.
1072                        items
1073                            .get("properties")
1074                            .and_then(|properties| properties.get("value"))
1075                            .cloned()
1076                            .unwrap_or_else(|| items.clone())
1077                    },
1078                );
1079                // A collection of text items takes the text operations at each item, not only
1080                // the whole-value `set` a record item takes.
1081                let item_ops: &[&str] = match *inner {
1082                    crate::Shape::Value => &["set", "splice", "replace", "rich"],
1083                    _ => &["set"],
1084                };
1085                out.push(alternative(
1086                    &items,
1087                    false,
1088                    item_ops,
1089                    item_value,
1090                    None,
1091                    field.title,
1092                    "one item, by its id".to_owned(),
1093                ));
1094                edit_paths(*inner, &items, &format!("{path}.*."), rich, out);
1095            }
1096            crate::Shape::Value if field.ty.starts_with("Grid<") => {
1097                let mut cells = here.clone();
1098                cells.push(step_schema(
1099                    "cell",
1100                    serde_json::json!({
1101                        "type": "object",
1102                        "properties": {
1103                            "row": { "type": "string" },
1104                            "column": { "type": "string" },
1105                        },
1106                        "required": ["row", "column"],
1107                    }),
1108                ));
1109                out.push(alternative(
1110                    &cells,
1111                    true,
1112                    &[
1113                        "set", "splice", "replace", "add", "insert", "remove", "rich",
1114                    ],
1115                    serde_json::json!({}),
1116                    None,
1117                    field.title,
1118                    "a cell, by its row and column ids, and what is inside it".to_owned(),
1119                ));
1120            }
1121            crate::Shape::Map(_) => {
1122                let mut entries = here.clone();
1123                entries.push(step_schema("key", serde_json::json!({ "type": "string" })));
1124                // An entry whose type has its own vocabulary (a text) is edited in it.
1125                let entry_rich = rich_schema_at(rich, &format!("{path}.*"));
1126                let mut ops = vec!["set", "splice", "replace", "add", "insert", "remove"];
1127                if entry_rich.is_some() {
1128                    ops.push("rich");
1129                }
1130                out.push(alternative(
1131                    &entries,
1132                    true,
1133                    &ops,
1134                    serde_json::json!({}),
1135                    entry_rich,
1136                    field.title,
1137                    "an entry, by its key, and what is inside it".to_owned(),
1138                ));
1139            }
1140            crate::Shape::Value => {}
1141        }
1142    }
1143}
1144
1145mod field_edit;
1146use field_edit::rooted_edit_spec;
1147
1148/// The published spec of [`FIELD_EDIT`], where `now` holds the values of
1149/// the fields that weaken one way ([`weakening_now`]).
1150pub(crate) fn field_edit_spec(
1151    vocabulary: &'static Vocabulary,
1152    now: Vec<(String, String)>,
1153) -> ActionSpec {
1154    // Built once per type: it describes every editable path, which only
1155    // the type decides.
1156    let schema = per_type(vocabulary, TypeSchema::Edit, &|| {
1157        Some(edit_schema(vocabulary))
1158    })
1159    .unwrap_or_else(|| Arc::new(edit_schema(vocabulary)));
1160    rooted_edit_spec(
1161        vocabulary,
1162        (vocabulary.shape)(),
1163        schema,
1164        format!("Edit a {} field", vocabulary.label),
1165        "The path of the field from the record's root, and the operation",
1166        now,
1167    )
1168}
1169
1170/// The values now, as JSON text by dotted path, of `R`'s fields that weaken
1171/// one way ([`Trust::Weakens`](crate::Trust::Weakens)) outside any item:
1172/// whether a change of one weakens depends on them.
1173fn weakening_now<R: Resource>(state: &R::State) -> Vec<(String, String)> {
1174    weakening_in(R::shape(), &|| R::state_json(state))
1175}
1176
1177/// [`weakening_now`] of the resource whose stored layout is `shape` and
1178/// whose state's JSON `json` reads. Not generic, so it is compiled once
1179/// rather than for every resource type.
1180#[inline(never)]
1181fn weakening_in(
1182    shape: Option<crate::Shape>,
1183    json: &dyn Fn() -> Option<serde_json::Value>,
1184) -> Vec<(String, String)> {
1185    let Some(shape) = shape else {
1186        return Vec::new();
1187    };
1188    let fields: Vec<String> = shape
1189        .guarded_fields()
1190        .into_iter()
1191        .filter(|(path, trust)| {
1192            matches!(trust, crate::Trust::Weakens(_)) && !path.split('.').any(|key| key == "*")
1193        })
1194        .map(|(path, _)| path)
1195        .collect();
1196    if fields.is_empty() {
1197        return Vec::new();
1198    }
1199    let Some(json) = json() else {
1200        return Vec::new();
1201    };
1202    fields
1203        .into_iter()
1204        .filter_map(|path| {
1205            let value = path
1206                .split('.')
1207                .try_fold(&json, |value, key| value.get(key))?
1208                .to_string();
1209            Some((path, value))
1210        })
1211        .collect()
1212}
1213
1214/// The field edit offered on the item `item` of the collection `field`:
1215/// paths from the item, its editable paths described as the record's are.
1216#[must_use]
1217pub fn item_field_edit_spec<R: Resource>(field: &str, item: &crate::Id) -> Option<ActionSpec> {
1218    item_field_edit_spec_of(vocabulary::<R>(), field, item)
1219}
1220
1221/// [`item_field_edit_spec`] of the resource `vocabulary`.
1222pub(crate) fn item_field_edit_spec_of(
1223    vocabulary: &'static Vocabulary,
1224    field: &str,
1225    item: &crate::Id,
1226) -> Option<ActionSpec> {
1227    field_edit_spec_at_of(
1228        vocabulary,
1229        vec![
1230            crate::Segment::Field(field.to_owned()),
1231            crate::Segment::Item(item.clone()),
1232        ],
1233    )
1234}
1235
1236/// The field edit offered on the item at `prefix` (fields and item ids from
1237/// the record, ending at an item): paths from the item, its editable paths
1238/// described as the record's are.
1239#[must_use]
1240pub fn field_edit_spec_at<R: Resource>(prefix: Vec<crate::Segment>) -> Option<ActionSpec> {
1241    field_edit_spec_at_of(vocabulary::<R>(), prefix)
1242}
1243
1244/// [`field_edit_spec_at`] of the resource `vocabulary`.
1245pub(crate) fn field_edit_spec_at_of(
1246    vocabulary: &'static Vocabulary,
1247    prefix: Vec<crate::Segment>,
1248) -> Option<ActionSpec> {
1249    let mut shape = (vocabulary.shape)()?;
1250    let mut dotted = String::new();
1251    let mut readonly = false;
1252    for segment in &prefix {
1253        match (shape, segment) {
1254            (crate::Shape::Record(fields), crate::Segment::Field(key)) => {
1255                let field = fields.iter().find(|candidate| candidate.key == key)?;
1256                readonly |= field.readonly;
1257                shape = field.shape;
1258                dotted.push_str(key);
1259                dotted.push('.');
1260            }
1261            (
1262                crate::Shape::Collection(inner) | crate::Shape::Keyed(inner),
1263                crate::Segment::Item(_),
1264            ) => {
1265                shape = *inner;
1266                dotted.push_str("*.");
1267            }
1268            _ => return None,
1269        }
1270    }
1271    if shape.fields().is_empty() || readonly {
1272        return None;
1273    }
1274    // The same for every item: kept once per type and path, bound to the
1275    // item's.
1276    thread_local! {
1277        static KEPT: std::cell::RefCell<crate::kept::KeptByPath> = std::cell::RefCell::default();
1278    }
1279    let key = ((vocabulary.type_id)(), dotted.clone());
1280    crate::kept::kept_type(&KEPT, key, || item_edit_type(vocabulary, shape, &dotted))
1281        .map(|ty| ty.bind(Target::new(prefix)))
1282}
1283
1284/// The type of the field edit of the items at the dotted path `dotted`, of
1285/// shape `shape`, or `None` when nothing there is editable.
1286fn item_edit_type(
1287    vocabulary: &'static Vocabulary,
1288    shape: crate::Shape,
1289    dotted: &str,
1290) -> Option<Arc<ActionType>> {
1291    let schema = per_type_at(vocabulary, TypeSchema::Edit, dotted, &|| {
1292        let ops: Vec<(String, serde_json::Value)> = (vocabulary.op_schemas)()
1293            .into_iter()
1294            .filter_map(|(path, schema)| {
1295                path.strip_prefix(dotted)
1296                    .map(|rest| (rest.to_owned(), schema))
1297            })
1298            .collect();
1299        let mut alternatives = Vec::new();
1300        edit_paths(shape, &[], "", &ops, &mut alternatives);
1301        (!alternatives.is_empty()).then(|| described_edit(&alternatives, &ops))
1302    })?;
1303    let spec = rooted_edit_spec(
1304        vocabulary,
1305        Some(shape),
1306        schema,
1307        "Edit a field of this item".to_owned(),
1308        "The path of the field from the item, and the operation",
1309        Vec::new(),
1310    );
1311    Some(Arc::clone(spec.action_type()))
1312}
1313
1314/// The edits of a resource whose document holds nothing. An app whose data
1315/// lives entirely outside any document — credentials in this device's
1316/// encrypted vault, a device's hardware — publishes that data as live rows
1317/// and effects, and its resource is only the API they are published on.
1318/// No value exists, so nothing is ever applied, undone or synced.
1319#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
1320pub enum NoAction {}
1321
1322impl tilo_actions::Action for NoAction {
1323    // No value exists to apply.
1324    fn apply(&self, _doc: &mut tilo_actions::Doc) -> Result<(), tilo_actions::ActionError> {
1325        Ok(())
1326    }
1327}
1328
1329/// Where a member is inside a resource, in the resource's own terms:
1330/// the same on every member's screen whatever its layout.
1331///
1332/// Also what an action is told to act at (`#[param(place)] at:
1333/// Option<Place>`): it travels as `{"item": id}`, `{"item": id, "at": n}` or
1334/// `{"item": id, "start": n, "end": n}`.
1335#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
1336#[serde(into = "tilo_actions::SelectionPlace")]
1337pub enum Place {
1338    /// An item (a paragraph, a clip, a row).
1339    Item(String),
1340    /// A caret at a character position inside an item.
1341    Caret { item: String, at: usize },
1342    /// Characters `start..end` of an item.
1343    Range {
1344        item: String,
1345        start: usize,
1346        end: usize,
1347    },
1348}
1349
1350impl Place {
1351    /// The item the place is in.
1352    #[must_use]
1353    pub fn item(&self) -> &str {
1354        match self {
1355            Self::Item(item) | Self::Caret { item, .. } | Self::Range { item, .. } => item,
1356        }
1357    }
1358}
1359
1360// Decoded through a JSON value whatever the deserializer, by one function.
1361//
1362// Validating on every read is safe while every stored place names a generated
1363// id (today only code-editor's recorded `replace-range` action stores a
1364// `Place`, its item is always a UUID, and it declares no undo). A later action
1365// that has an undo and takes items from outside data would fail to decode on
1366// undo.
1367impl<'de> serde::Deserialize<'de> for Place {
1368    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1369        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
1370        match place_from_json(value) {
1371            Ok(place) => Ok(place),
1372            Err(error) => Err(serde::de::Error::custom(error)),
1373        }
1374    }
1375}
1376
1377/// The place in `value`, its JSON form.
1378fn place_from_json(value: serde_json::Value) -> Result<Place, String> {
1379    match serde_json::from_value::<tilo_actions::SelectionPlace>(value) {
1380        Ok(wire) => Place::try_from(wire),
1381        Err(error) => Err(error.to_string()),
1382    }
1383}
1384
1385impl crate::JsonSchema for Place {
1386    fn json_schema() -> serde_json::Value {
1387        tilo_actions::place_schema()
1388    }
1389}
1390
1391// A selection carried to an agent is the place an action takes, in the
1392// same wire form, so the agent can hand it back unchanged.
1393impl From<Place> for tilo_actions::SelectionPlace {
1394    fn from(place: Place) -> Self {
1395        match place {
1396            Place::Item(item) => Self::item(item),
1397            Place::Caret { item, at } => Self::caret(item, at),
1398            Place::Range { item, start, end } => Self::range(item, start, end),
1399        }
1400    }
1401}
1402
1403impl TryFrom<tilo_actions::SelectionPlace> for Place {
1404    type Error = String;
1405
1406    fn try_from(place: tilo_actions::SelectionPlace) -> Result<Self, String> {
1407        match place.validated_span()? {
1408            tilo_actions::selection::SelectionSpan::Item => Ok(Self::Item(place.item)),
1409            tilo_actions::selection::SelectionSpan::Caret(at) => Ok(Self::Caret {
1410                item: place.item,
1411                at,
1412            }),
1413            tilo_actions::selection::SelectionSpan::Range { start, end } => Ok(Self::Range {
1414                item: place.item,
1415                start,
1416                end,
1417            }),
1418        }
1419    }
1420}
1421
1422/// Builds a resource's action from arguments already bound against the
1423/// declaration's parameters. `now_ms` is the origin's clock, captured once so
1424/// replay is deterministic.
1425pub type BuildAction<R> =
1426    Arc<dyn Fn(&ActionArgs, i64) -> Result<<R as Resource>::Action, String> + Send + Sync>;
1427
1428/// One mutation offered by name: a [`Declaration`] of the resource `R`,
1429/// whose fields it derefs to.
1430pub struct ActionDecl<R: Resource> {
1431    decl: Declaration,
1432    marker: std::marker::PhantomData<fn() -> R>,
1433}
1434
1435impl<R: Resource> Clone for ActionDecl<R> {
1436    fn clone(&self) -> Self {
1437        Self {
1438            decl: self.decl.clone(),
1439            marker: std::marker::PhantomData,
1440        }
1441    }
1442}
1443
1444impl<R: Resource> std::ops::Deref for ActionDecl<R> {
1445    type Target = Declaration;
1446
1447    fn deref(&self) -> &Declaration {
1448        &self.decl
1449    }
1450}
1451
1452impl<R: Resource> AsRef<Declaration> for ActionDecl<R> {
1453    fn as_ref(&self) -> &Declaration {
1454        &self.decl
1455    }
1456}
1457
1458impl<R: Resource> std::ops::DerefMut for ActionDecl<R> {
1459    fn deref_mut(&mut self) -> &mut Declaration {
1460        &mut self.decl
1461    }
1462}
1463
1464impl<R: Resource> ActionDecl<R> {
1465    /// A field edit whose one value its caller supplies, offered as the
1466    /// action `id` labelled `label`: the parameter `param` (described by
1467    /// `description`, typed by `V`'s schema) becomes the edit `make(value)`.
1468    /// What a row offers when the edit is bound to it but its value is not
1469    /// ("Rename playlist", "Add a song to this playlist").
1470    pub fn edit_asking<V>(
1471        id: &'static str,
1472        label: impl Into<String>,
1473        param: &'static str,
1474        description: &'static str,
1475        make: impl Fn(V) -> crate::Edit<R> + Send + Sync + 'static,
1476    ) -> Self
1477    where
1478        V: DeserializeOwned + crate::JsonSchema,
1479    {
1480        let schema = V::json_schema();
1481        let declared = ActionParam::required_owned(
1482            param,
1483            crate::__private::param_type_of(&schema),
1484            description,
1485        )
1486        .with_schema(schema);
1487        let vocabulary = vocabulary::<R>();
1488        let build: Builds = Arc::new(move |args, now_ms| {
1489            let value = taken_arg(args, param)?;
1490            let value: V = match serde_json::from_value(value) {
1491                Ok(value) => value,
1492                Err(error) => return Err(format!("`{param}`: {error}")),
1493            };
1494            stamped_edit(vocabulary, make(value).retyped(), now_ms)
1495        });
1496        Self::declared(Declaration::new(
1497            vocabulary,
1498            id,
1499            label.into(),
1500            vec![declared],
1501            build,
1502        ))
1503    }
1504
1505    /// The field edit `edit` offered as the action `id` labelled `label`,
1506    /// its value bound: what a place or a live row offers ("Use Proton for
1507    /// Adobe Reader"), checked and recorded as the edit itself.
1508    pub fn edit(id: &'static str, label: impl Into<String>, edit: crate::Edit<R>) -> Self
1509    where
1510        crate::Edit<R>: Send + Sync,
1511    {
1512        Self::declared(edit_declaration(
1513            vocabulary::<R>(),
1514            id,
1515            label.into(),
1516            edit.retyped(),
1517        ))
1518    }
1519
1520    pub fn new(
1521        id: &'static str,
1522        label: impl Into<String>,
1523        params: Vec<ActionParam>,
1524        build: impl Fn(&ActionArgs, i64) -> Result<R::Action, String> + Send + Sync + 'static,
1525    ) -> Self {
1526        let build: Builds = Arc::new(move |args, now_ms| match build(args, now_ms) {
1527            Ok(action) => Ok(Built::of::<R>(action)),
1528            Err(reason) => Err(reason),
1529        });
1530        Self::declared(Declaration::new(
1531            vocabulary::<R>(),
1532            id,
1533            label.into(),
1534            params,
1535            build,
1536        ))
1537    }
1538
1539    pub(crate) fn declared(decl: Declaration) -> Self {
1540        Self {
1541            decl,
1542            marker: std::marker::PhantomData,
1543        }
1544    }
1545
1546    /// This action with `arguments` as a caller sent them over a call that names the action by
1547    /// its id: what a dispatch hands the record, which binds them as it binds any.
1548    #[must_use]
1549    pub fn with_arguments(
1550        &self,
1551        arguments: serde_json::Map<String, serde_json::Value>,
1552    ) -> crate::Invoke<R> {
1553        crate::Invoke::bound(self.decl.id, Ok(arguments))
1554    }
1555
1556    /// The declaration, of whichever resource.
1557    #[must_use]
1558    pub fn into_declaration(self) -> Declaration {
1559        self.decl
1560    }
1561
1562    /// The action it builds from `args` at `now_ms`.
1563    pub fn build_action(&self, args: &ActionArgs, now_ms: i64) -> Result<R::Action, String> {
1564        typed::<R>(crate::content::invoking(|| {
1565            (self.decl.build)(args, now_ms)
1566        })?)
1567    }
1568
1569    /// Mark a bound edit as refining the resource's declared action of the
1570    /// same id ([`bind_declaration`]).
1571    #[must_use]
1572    pub fn refining(mut self) -> Self {
1573        self.decl.refines = true;
1574        self
1575    }
1576
1577    /// Declare who listings offer it to ([`tilo_actions::Audience`]), as
1578    /// `#[action(audience = ..)]` declares it for a verb: a bound edit that
1579    /// names entries by path is for agents and scripts, not a row a person
1580    /// picks.
1581    #[must_use]
1582    pub fn for_audience(mut self, audience: tilo_actions::Audience) -> Self {
1583        self.decl.tags.retain(|tag| {
1584            tag != tilo_actions::AGENTS_AUDIENCE_TAG && tag != tilo_actions::PEOPLE_AUDIENCE_TAG
1585        });
1586        if let Some(tag) = audience.tag() {
1587            self.decl.tags.push(tag.to_owned());
1588        }
1589        self
1590    }
1591
1592    /// Tag the action's contract (`ContextRequirement::Caret.tag()`, an
1593    /// incremental-text declaration) for the callers that read it.
1594    #[must_use]
1595    pub fn tagged(mut self, tag: impl Into<String>) -> Self {
1596        self.decl.tag(tag.into());
1597        self
1598    }
1599
1600    #[must_use]
1601    pub fn describe(mut self, description: impl Into<String>) -> Self {
1602        self.decl.description = Some(description.into());
1603        self
1604    }
1605
1606    /// Declare what the action answers its caller with (an outline of the
1607    /// state it left), which the hosting surface supplies after it applies.
1608    #[must_use]
1609    pub fn returns(mut self, result: tilo_actions::ResultSpec) -> Self {
1610        self.decl.result = Some(result);
1611        self
1612    }
1613
1614    /// Set what the action is able to do.
1615    #[must_use]
1616    pub fn of_kind(mut self, kind: ActionKind) -> Self {
1617        self.decl.kind = kind;
1618        self
1619    }
1620
1621    /// Place the action below the one field it writes.
1622    #[must_use]
1623    pub fn below_field(mut self, field: &'static str) -> Self {
1624        self.decl.field = Some(field);
1625        self
1626    }
1627
1628    #[must_use]
1629    pub fn destructive(mut self) -> Self {
1630        self.decl.destructive = true;
1631        self
1632    }
1633
1634    /// The units the action writes, as the surface lists them
1635    /// ([`crate::footprint`]).
1636    #[must_use]
1637    pub fn writing(mut self, units: Vec<String>) -> Self {
1638        self.decl.writes = units;
1639        self
1640    }
1641
1642    /// Answer the caller with what the action made, from
1643    /// [`Resource::answer`].
1644    #[must_use]
1645    pub fn answering(mut self) -> Self {
1646        self.decl.answer();
1647        self
1648    }
1649}
1650
1651impl Declaration {
1652    fn tag(&mut self, tag: String) {
1653        if !self.tags.contains(&tag) {
1654            self.tags.push(tag);
1655        }
1656    }
1657
1658    fn answer(&mut self) {
1659        self.result = Some(tilo_actions::ResultSpec::Json {
1660            schema: serde_json::json!({"type": "object"}),
1661        });
1662    }
1663}
1664
1665/// The action of `R` that `built` is.
1666fn typed<R: Resource>(built: Built) -> Result<R::Action, String> {
1667    built
1668        .into_action::<R>()
1669        .ok_or_else(|| format!("not an action of a {}", R::LABEL))
1670}
1671
1672/// The argument `param` of `args`, taken out.
1673fn taken_arg(args: &ActionArgs, param: &str) -> Result<serde_json::Value, String> {
1674    match args.to_json().remove(param) {
1675        Some(value) => Ok(value),
1676        None => Err(format!("`{param}` is missing")),
1677    }
1678}
1679
1680/// The action the field edit `edit` of the resource `vocabulary` is,
1681/// stamped at `now_ms`.
1682pub(crate) fn stamped_edit(
1683    vocabulary: &Vocabulary,
1684    edit: Edit<()>,
1685    now_ms: i64,
1686) -> Result<Built, String> {
1687    let Some(mut action) = (vocabulary.edit)(edit) else {
1688        return Err(format!("{} has no field edits", vocabulary.label));
1689    };
1690    action.stamp(now_ms);
1691    Ok(action)
1692}
1693
1694/// [`ActionDecl::edit`] of the resource `vocabulary`.
1695fn edit_declaration(
1696    vocabulary: &'static Vocabulary,
1697    id: &'static str,
1698    label: String,
1699    edit: Edit<()>,
1700) -> Declaration {
1701    let destructive = (vocabulary.edit)(edit.clone())
1702        .is_some_and(|action| action.risk() == tilo_actions::RiskLevel::Destructive);
1703    let invokes = serde_json::to_value(&edit).ok().map(|edit| {
1704        (
1705            FIELD_EDIT.to_owned(),
1706            serde_json::Map::from_iter([(EDIT_PARAM.to_owned(), edit)]),
1707        )
1708    });
1709    let build: Builds = Arc::new(move |_, now_ms| stamped_edit(vocabulary, edit.clone(), now_ms));
1710    let mut decl = Declaration::new(vocabulary, id, label, Vec::new(), build);
1711    decl.destructive = destructive;
1712    decl.invokes = invokes;
1713    decl
1714}
1715
1716thread_local! {
1717    /// The origin clock of a [`Replica`](crate::Replica) applying an action
1718    /// on this thread, in place of the machine's.
1719    static ORIGIN_CLOCK: std::cell::Cell<Option<i64>> = const { std::cell::Cell::new(None) };
1720}
1721
1722/// Milliseconds since the Unix epoch on this machine (or the clock of the
1723/// replica applying an action here). Only ever read on the origin, when an
1724/// action is built; never inside `apply`.
1725#[must_use]
1726pub fn origin_now_ms() -> i64 {
1727    ORIGIN_CLOCK
1728        .with(std::cell::Cell::get)
1729        .unwrap_or_else(tilo_clock::unix_now_ms_i64)
1730}
1731
1732/// Run `f` with the origin clock reading `now_ms`: every action built
1733/// inside it is stamped with that time, so encoding the same invocation
1734/// twice (once to ask for confirmation, once to check it) gives the same
1735/// action.
1736pub fn with_origin_clock<T>(now_ms: i64, f: impl FnOnce() -> T) -> T {
1737    struct Restore(Option<i64>);
1738    impl Drop for Restore {
1739        fn drop(&mut self) {
1740            ORIGIN_CLOCK.with(|clock| clock.set(self.0));
1741        }
1742    }
1743    let _restore = Restore(ORIGIN_CLOCK.with(|clock| clock.replace(Some(now_ms))));
1744    f()
1745}
1746
1747/// Encode a resource action under its registry type id.
1748///
1749/// # Errors
1750/// Returns [`ActionError::Encode`] when the action does not serialize.
1751pub fn encode<R: Resource>(action: &R::Action) -> Result<EncodedAction, ActionError> {
1752    EncodedAction::encode(R::ACTION_TYPE, action)
1753}
1754
1755/// The encoded form of a built action, or a refusal carrying why it does
1756/// not encode.
1757pub(crate) fn encoded(action: &Built) -> EncodedAction {
1758    match action.encode() {
1759        Ok(encoded) => encoded,
1760        Err(error) => refused(&error.to_string()),
1761    }
1762}
1763
1764/// The encoded form of a builder's result: the action, or a refusal that
1765/// carries the builder's reason.
1766pub(crate) fn encode_built(built: Result<Built, String>) -> EncodedAction {
1767    match built {
1768        Ok(action) => encoded(&action),
1769        Err(reason) => refused(&reason),
1770    }
1771}
1772
1773/// The nested resource `id` of `state`, read from `doc` with `id` demanded
1774/// when `state` has not loaded it: an item past what a view shows or a
1775/// tree pages still resolves by id ([`Resource::child`], [`Resource::load`]).
1776pub fn child_by_id<R: Resource>(
1777    state: &R::State,
1778    doc: &Doc,
1779    id: &str,
1780) -> Option<tilo_actions::ResourceSpec> {
1781    if let Some(child) = R::child(state, id) {
1782        return Some(child);
1783    }
1784    let mut fresh = R::read(doc).ok()?;
1785    R::load(&mut fresh, doc, &child_demand(id)).ok()?;
1786    R::child(&fresh, id)
1787}
1788
1789/// What reading the child published at `id` demands: compiled once rather
1790/// than for every resource.
1791#[inline(never)]
1792fn child_demand(id: &str) -> Demand {
1793    // A child is published as `<kind>/<field>/<key>`; its record knows
1794    // it by the key.
1795    let key = id.rsplit('/').next().unwrap_or(id);
1796    Demand::none().with_keys([id, key])
1797}
1798
1799/// An action whose payload cannot be decoded, so the host refuses it with
1800/// the builder's reason instead of applying anything.
1801pub(crate) fn refused(reason: &str) -> EncodedAction {
1802    EncodedAction {
1803        type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
1804        payload: reason.as_bytes().to_vec(),
1805    }
1806}
1807
1808/// The ids of `declarations` some child among `children` offers bound.
1809fn offered_bound_ids(
1810    children: &[tilo_actions::ResourceSpec],
1811    declarations: &[Declaration],
1812) -> Vec<&'static str> {
1813    let mut ids = Vec::new();
1814    for decl in declarations {
1815        if crate::items::offered_bound(children, decl) {
1816            ids.push(decl.id);
1817        }
1818    }
1819    ids
1820}
1821
1822/// The least a caller needs to take any of `declarations`.
1823fn least_need_declared(declarations: &[Declaration]) -> ActionNeed {
1824    least_need_of(declarations.iter().map(|decl| decl.kind))
1825}
1826
1827/// The least a caller needs to take any of the actions of the kinds `needs`:
1828/// the least kind, at no field.
1829///
1830/// A group and a typed edit are offered to whoever may take the resource's
1831/// least demanding kind, and each invocation is what its own arguments say it
1832/// is ([`ActionSpec::with_need_of`]). One declaration's field is not that
1833/// offer's: it is that declaration's, and a chat whose `remove-message` writes
1834/// its `moderation` field would offer every `group` and `apply` only to
1835/// whoever may moderate, though the members of a group write their own
1836/// fields.
1837#[must_use]
1838pub fn least_need_of(needs: impl IntoIterator<Item = ActionKind>) -> ActionNeed {
1839    needs.into_iter().min().map_or_else(
1840        || tilo_actions::ActionContract::default().need(),
1841        |kind| ActionNeed {
1842            kind,
1843            field: None,
1844            privileged: false,
1845        },
1846    )
1847}
1848
1849/// The published spec of one declared or bound mutation: what the palette,
1850/// agents and scripts invoke, building the resource's action from their
1851/// arguments.
1852///
1853/// The action is built when it is invoked, never when it is published: one
1854/// that takes no arguments still mints its ids and reads the clock at the
1855/// moment it is taken, so two invocations make two distinct actions.
1856#[must_use]
1857pub fn declaration_spec<D: AsRef<Declaration> + ?Sized>(decl: &D) -> ActionSpec {
1858    spec_of_declaration(decl.as_ref())
1859}
1860
1861/// [`declaration_spec`] of a declaration of whichever resource.
1862fn spec_of_declaration(decl: &Declaration) -> ActionSpec {
1863    let build = Arc::clone(&decl.build);
1864    spec_of_declaration_on(decl, move |_, args, now_ms| build(args, now_ms))
1865}
1866
1867/// The spec of `decl` as a type whose target `build` reads: what every item
1868/// offering the declared action shares ([`Target`]).
1869pub(crate) fn spec_of_declaration_on(
1870    decl: &Declaration,
1871    build: impl Fn(&Target, &ActionArgs, i64) -> Result<Built, String> + Send + Sync + 'static,
1872) -> ActionSpec {
1873    let build = Arc::new(build);
1874    let label = decl.shown_label();
1875    let encoded = move |target: &Target, args: &tilo_actions::ActionArgs| {
1876        encode_built(crate::content::invoking(|| {
1877            build(target, args, origin_now_ms())
1878        }))
1879    };
1880    let spec = if let Some(prompt) = &decl.content {
1881        let param = ActionParam::required_owned(
1882            tilo_actions::PROMPTED_PARAM,
1883            ParamType::Text,
1884            prompt.clone(),
1885        );
1886        ActionSpec::prompted_content_on(
1887            decl.id,
1888            label,
1889            prompt.clone(),
1890            "content hash",
1891            ExecutionLocus::ClientLocal,
1892            move |target, hash| {
1893                let supplied = [(
1894                    tilo_actions::PROMPTED_PARAM.to_owned(),
1895                    tilo_actions::ArgValue::Text(hash.to_owned()),
1896                )];
1897                match ActionArgs::bind(std::slice::from_ref(&param), supplied) {
1898                    Ok(args) => encoded(target, &args),
1899                    Err(error) => refused(&error.to_string()),
1900                }
1901            },
1902        )
1903    } else if decl.params.is_empty() {
1904        // Built when taken, so it reads the clock and mints its ids then; a
1905        // destructive one is held for confirmation as the same verb of the
1906        // same kind of record.
1907        let domain = format!("{}#{}", decl.resource, decl.id);
1908        let action_type = decl.action_type;
1909        ActionSpec::deferred_on(
1910            decl.id,
1911            label,
1912            ExecutionLocus::ClientLocal,
1913            action_type,
1914            move |target| encoded(target, &tilo_actions::ActionArgs::none()),
1915        )
1916        .with_continuation_identity(move |query| match query {
1917            tilo_actions::ContinuationQuery::Draft => {
1918                Some(tilo_actions::ContinuationEvidence::Draft {
1919                    resolution_domain: tilo_actions::ContinuationKey::new(
1920                        "verb",
1921                        [domain.as_bytes()],
1922                    ),
1923                    handler: tilo_actions::ContinuationKey::new(
1924                        "action-type",
1925                        [action_type.as_bytes()],
1926                    ),
1927                })
1928            }
1929            tilo_actions::ContinuationQuery::Exact(_) => None,
1930        })
1931    } else {
1932        ActionSpec::typed_on(
1933            decl.id,
1934            label.clone(),
1935            label,
1936            ExecutionLocus::ClientLocal,
1937            decl.shown_params(),
1938            encoded,
1939        )
1940    };
1941    let mut spec = spec.of_kind(decl.kind);
1942    // One whose arguments decide whether it reaches outside is what the
1943    // action built from them is; arguments that build none are taken as
1944    // reaching outside.
1945    if decl.by_arguments {
1946        let classify = Arc::clone(&decl.build);
1947        spec = spec.with_need_of(move |args| match classify(args, 0) {
1948            Ok(action) => action.need(),
1949            Err(_) => tilo_actions::ActionNeed::of(ActionKind::Outside),
1950        });
1951    }
1952    if let Some(field) = decl.field {
1953        spec = spec.below_field(field);
1954    }
1955    if let Some(description) = &decl.description {
1956        spec = spec.with_description(description.clone());
1957    }
1958    if !decl.keywords.is_empty() {
1959        spec = spec.with_keywords(decl.keywords.iter().cloned());
1960    }
1961    spec = with_declared_words(spec, decl);
1962    if decl.destructive {
1963        spec = spec.destructive();
1964    }
1965    let contract = &mut spec.type_mut().contract;
1966    (contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
1967    if let Some(result) = &decl.result {
1968        contract.result = result.clone();
1969    }
1970    for tag in &decl.tags {
1971        if !contract.tags.contains(tag) {
1972            contract.tags.push(tag.clone());
1973        }
1974    }
1975    // A compensated undo arrives as a tag: once it is there, a deletion it
1976    // takes back is no longer asked about.
1977    contract.settle_confirmation();
1978    spec
1979}
1980
1981/// `spec` carrying the declared action's own picture and the past-tense words
1982/// its app says it did, where it declares them.
1983pub(crate) fn with_declared_words(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
1984    spec.type_mut().icon.clone_from(&decl.icon);
1985    spec.type_mut().did = decl.did.clone().filter(|did| !did.trim().is_empty());
1986    spec
1987}
1988
1989/// Each declared action's arguments object, as serde reads it.
1990fn declared_args(
1991    declarations: &[Declaration],
1992) -> std::collections::BTreeMap<&'static str, serde_json::Value> {
1993    let mut args = std::collections::BTreeMap::new();
1994    for decl in declarations {
1995        args.insert(decl.id, crate::schema::args_schema(&decl.params));
1996    }
1997    args
1998}
1999
2000/// The parameter of [`APPLY`]: one action value, described by
2001/// [`Resource::action_schema`] when the resource has one, with what only
2002/// restates a named action folded into a reference to it.
2003pub(crate) fn apply_param(vocabulary: &Vocabulary) -> ActionParam {
2004    let param = ActionParam::required_owned(
2005        APPLY_PARAM,
2006        ParamType::Object,
2007        format!("A {} action, as JSON", vocabulary.label),
2008    );
2009    let schema = per_type(vocabulary, TypeSchema::Apply, &|| {
2010        let schema = (vocabulary.action_schema)()?;
2011        Some(crate::schema::fold_declared(
2012            &schema,
2013            &declared_args(&vocabulary.declarations()),
2014        ))
2015    });
2016    match schema {
2017        Some(schema) => param.with_shared_schema(schema),
2018        None => param,
2019    }
2020}
2021
2022/// The schemas a publication derives from the resource type alone.
2023#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2024enum TypeSchema {
2025    Apply,
2026    Group,
2027    /// The field edit's, at the paths under a dotted prefix (`""` for the
2028    /// record's root, `notes.*.` for an item of `notes`).
2029    Edit,
2030}
2031
2032#[derive(Default)]
2033struct CompiledSchemas {
2034    epoch: u64,
2035    entries: HashMap<(TypeId, TypeSchema, String), Option<Arc<serde_json::Value>>>,
2036}
2037
2038static SCHEMAS: OnceLock<Mutex<CompiledSchemas>> = OnceLock::new();
2039
2040/// Forget schemas derived by the previous app code before an in-place reload.
2041/// Hosts also call this when a reload is rejected, so the retained app rebuilds
2042/// its own definitions. Document and view changes do not invalidate type schemas.
2043#[doc(hidden)]
2044pub fn reset_type_schemas() {
2045    if let Some(cache) = SCHEMAS.get() {
2046        let mut store = cache.lock_recover();
2047        store.epoch = store.epoch.wrapping_add(1);
2048        store.entries.clear();
2049    }
2050}
2051
2052/// Which generation of app code built what is cached from the resource
2053/// types: it changes when [`reset_type_schemas`] forgets them.
2054pub(crate) fn type_epoch() -> u64 {
2055    SCHEMAS.get().map_or(0, |cache| cache.lock_recover().epoch)
2056}
2057
2058/// [`type_epoch`] and the language the words resolve in on this thread: what
2059/// a cache of published actions, whose labels are read in that language, is
2060/// kept for.
2061pub(crate) fn words_epoch() -> u64 {
2062    type_epoch() ^ crate::label::revision().rotate_left(32)
2063}
2064
2065/// `build`'s schema for the resource `vocabulary`, retained for this
2066/// generation of app code.
2067fn per_type(
2068    vocabulary: &Vocabulary,
2069    schema: TypeSchema,
2070    build: &dyn Fn() -> Option<serde_json::Value>,
2071) -> Option<Arc<serde_json::Value>> {
2072    per_type_at(vocabulary, schema, "", build)
2073}
2074
2075/// [`per_type`] for the paths under the dotted prefix `at`.
2076fn per_type_at(
2077    vocabulary: &Vocabulary,
2078    schema: TypeSchema,
2079    at: &str,
2080    build: &dyn Fn() -> Option<serde_json::Value>,
2081) -> Option<Arc<serde_json::Value>> {
2082    let cache = SCHEMAS.get_or_init(Mutex::default);
2083    cached_schema(
2084        cache,
2085        ((vocabulary.type_id)(), schema, at.to_owned()),
2086        build,
2087    )
2088}
2089
2090fn cached_schema(
2091    cache: &Mutex<CompiledSchemas>,
2092    key: (TypeId, TypeSchema, String),
2093    build: &dyn Fn() -> Option<serde_json::Value>,
2094) -> Option<Arc<serde_json::Value>> {
2095    let epoch = {
2096        let store = cache.lock_recover();
2097        if let Some(found) = store.entries.get(&key) {
2098            let _phase = crate::profiling::Phase::start("schema.cached_clone");
2099            return found.clone();
2100        }
2101        store.epoch
2102    };
2103    // Build outside the lock: a schema may publish another resource's.
2104    let value = build().map(Arc::new);
2105    let mut store = cache.lock_recover();
2106    // A build started before a code reload cannot repopulate the new cache.
2107    if store.epoch == epoch {
2108        store.entries.insert(key, value.clone());
2109    }
2110    value
2111}
2112
2113/// Why an action only the app's own code applies ([`Resource::by_app`]) is
2114/// refused where a caller sent it: one sentence for every API.
2115#[must_use]
2116pub fn by_app_refusal(label: &str) -> String {
2117    format!("{label} keeps this itself: it is not an action to invoke")
2118}
2119
2120/// A JSON action value as [`APPLY`] reads it. A value naming a declared
2121/// action is checked against that declaration first, so it is refused with
2122/// the reason the named action would give. A value of an action only the
2123/// app's own code applies is refused: it is no caller's to send.
2124fn read_apply(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
2125    let declarations = vocabulary.declarations();
2126    let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2127    for decl in declarations.iter() {
2128        ids.push(decl.id);
2129    }
2130    if let Some((id, fields)) = crate::schema::declared_invocation(&value, &ids)
2131        && let Some(decl) = declarations.iter().find(|decl| decl.id == id)
2132        && let Err(error) = ActionArgs::bind_json(&decl.params, &fields)
2133    {
2134        return Err(format!("{id}: {error}"));
2135    }
2136    // Group members refer to this schema instead of copying it into the
2137    // group's parameter. Validate here as well as at the direct apply API,
2138    // including constraints stricter than the action's serde representation.
2139    if let Some(schema) = apply_param(vocabulary).schema {
2140        tilo_actions::validate_json_schema(&value, &schema)?;
2141    }
2142    let action = (vocabulary.read)(value)?;
2143    if action.by_app() {
2144        return Err(by_app_refusal(vocabulary.label));
2145    }
2146    Ok(action)
2147}
2148
2149/// The parameter of [`GROUP`](crate::GROUP): invocations of the resource's
2150/// declared actions and of [`APPLY`]. A declared member's arguments are
2151/// checked against its own action's schema when the group is built, so this
2152/// names those actions rather than repeating their schemas. An `apply`
2153/// member is read exactly as [`APPLY`] reads its value when the group is
2154/// built, so it refers to `apply`'s schema rather than copying it: a
2155/// resource with a large action vocabulary (rich text's) published that
2156/// schema twice in every surface.
2157pub(crate) fn group_param(vocabulary: &Vocabulary) -> ActionParam {
2158    let schema = per_type(vocabulary, TypeSchema::Group, &|| {
2159        let declarations = vocabulary.declarations();
2160        let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2161        for decl in declarations.iter() {
2162            ids.push(decl.id);
2163        }
2164        Some(group_schema(&ids, vocabulary.edits))
2165    })
2166    .unwrap_or_else(|| Arc::new(serde_json::json!({"type": "array"})));
2167    ActionParam::required_owned(
2168        crate::GROUP_PARAM,
2169        ParamType::Array,
2170        format!(
2171            "{} actions to apply in order as one step, each {{\"action\": id, \"args\": {{..}}}}. \
2172             A member names an item an earlier member of the same group makes by its place, \
2173             {{\"$made\": {{\"member\": 0, \"item\": 0}}}}: the member counted from 0, then which \
2174             of the ids it made, which the group fills in as it applies",
2175            vocabulary.label
2176        ),
2177    )
2178    .with_shared_schema(schema)
2179}
2180
2181/// What the value of an `apply` member of a group is: the schema it is
2182/// checked against is published once, on `apply` itself.
2183pub const APPLY_MEMBER: &str =
2184    "One action value, as the `apply` action's `apply` parameter describes it";
2185
2186/// What the value of a `field-edit` member of a group is: the schema it is
2187/// checked against is published once, on `field-edit` itself.
2188pub const FIELD_EDIT_MEMBER: &str =
2189    "A field edit, as the `field-edit` action's `edit` parameter describes it";
2190
2191/// The schema of a group of the actions `ids`, `apply`, and field edits when
2192/// `edits`: one function for every resource.
2193fn group_schema(ids: &[&str], edits: bool) -> serde_json::Value {
2194    use crate::schema::{array, constant, describe, nullable, object, one_of, string_enum};
2195    let mut members = Vec::new();
2196    if !ids.is_empty() {
2197        members.push(describe(
2198            object(vec![
2199                ("action", string_enum(ids), true),
2200                (
2201                    "args",
2202                    nullable(serde_json::json!({"type": "object"})),
2203                    false,
2204                ),
2205            ]),
2206            "A named action, args as it takes them",
2207        ));
2208    }
2209    let action = describe(serde_json::json!({"type": "object"}), APPLY_MEMBER);
2210    if edits {
2211        members.push(describe(
2212            object(vec![
2213                ("action", constant(FIELD_EDIT), true),
2214                (
2215                    "args",
2216                    object(vec![(
2217                        EDIT_PARAM,
2218                        describe(serde_json::json!({"type": "object"}), FIELD_EDIT_MEMBER),
2219                        true,
2220                    )]),
2221                    true,
2222                ),
2223            ]),
2224            "A field edit",
2225        ));
2226    }
2227    members.push(object(vec![
2228        ("action", constant(APPLY), true),
2229        ("args", object(vec![(APPLY_PARAM, action, true)]), true),
2230    ]));
2231    array(one_of(members))
2232}
2233
2234/// The JSON object of the argument `param` of `args`.
2235fn object_arg(
2236    args: &tilo_actions::ActionArgs,
2237    param: &str,
2238) -> Option<serde_json::Map<String, serde_json::Value>> {
2239    match args.get(param) {
2240        Some(tilo_actions::ArgValue::Object(value)) => Some(value.clone()),
2241        _ => None,
2242    }
2243}
2244
2245pub(crate) fn apply_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
2246    #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
2247    let _phase = crate::profiling::Phase::start("resource.apply_spec");
2248    let read = move |args: &tilo_actions::ActionArgs| match object_arg(args, APPLY_PARAM) {
2249        Some(value) => read_apply(vocabulary, serde_json::Value::Object(value)),
2250        None => Err("missing action".to_owned()),
2251    };
2252    ActionSpec::typed(
2253        APPLY,
2254        format!("Apply {} edit", vocabulary.label),
2255        "Action as JSON",
2256        ExecutionLocus::ClientLocal,
2257        vec![apply_param(vocabulary)],
2258        move |args| match crate::content::invoking(|| read(args)) {
2259            Ok(mut action) => {
2260                action.stamp(origin_now_ms());
2261                encoded(&action)
2262            }
2263            Err(reason) => refused(&reason),
2264        },
2265    )
2266    .with_description(
2267        "One edit as a typed JSON value: {action: id, ...its params}. The named action does the same and says more.",
2268    )
2269    // A typed edit is how a surface, an agent or a script says what should
2270    // happen without a named declaration; a person picks named actions.
2271    .for_audience(tilo_actions::Audience::Agents)
2272    // History records the edit it carried, not `apply`.
2273    .carrying()
2274    // Offered to whoever may take the least of its edits; each value is
2275    // what that edit is.
2276    .with_need((vocabulary.least_need)())
2277    .of_kind((vocabulary.least_need)().kind)
2278    .with_need_of(move |args| match read(args) {
2279        Ok(action) => action.need(),
2280        Err(_) => tilo_actions::ActionContract::default().need(),
2281    })
2282    // Each value is classified: deleting is destructive, trimming is not, so
2283    // a destructive value gets the confirmation a declared one would.
2284    .with_risk(move |args| {
2285        let value = object_arg(args, APPLY_PARAM).map(serde_json::Value::Object);
2286        match value.map(vocabulary.read) {
2287            Some(Ok(action)) => action.risk(),
2288            _ => tilo_actions::RiskLevel::Low,
2289        }
2290    })
2291    // Undo takes a value back when it takes back the edit it carries, so a
2292    // deleting value Undo does take back applies without asking, and one its
2293    // declaration says Undo cannot bring back asks first, exactly as its
2294    // named declaration does. The declaration says which its edits are, so
2295    // nothing is built to ask.
2296    .with_undo_of(move |args| {
2297        let Some(value) = object_arg(args, APPLY_PARAM) else {
2298            return false;
2299        };
2300        let value = serde_json::Value::Object(value);
2301        let declarations = vocabulary.declarations();
2302        let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2303        for decl in declarations.iter() {
2304            ids.push(decl.id);
2305        }
2306        let carried = crate::schema::declared_invocation(&value, &ids)
2307            .and_then(|(id, _)| declarations.iter().find(|decl| decl.id == id));
2308        tilo_actions::undo_takes_back(
2309            carried.map_or(tilo_actions::ActionKind::Outside, |decl| decl.kind),
2310            tilo_actions::ChangeKind::Content,
2311            carried.is_some_and(|decl| {
2312                decl.tags
2313                    .iter()
2314                    .any(|tag| tag == tilo_actions::IRREVERSIBLE_TAG)
2315            }),
2316        )
2317    })
2318}
2319
2320/// What kind of action a published spec is: the kind its contract carries,
2321/// which the code that built it derived (a view only reads, a document
2322/// action changes only the document when the host's undo reverts it, else it
2323/// reaches outside).
2324#[must_use]
2325pub fn spec_kind(spec: &ActionSpec) -> ActionKind {
2326    spec.contract.kind
2327}
2328
2329/// What `action` is, for the grants deciding it.
2330pub fn need_of<R: Resource>(action: &R::Action) -> ActionNeed {
2331    ActionNeed {
2332        kind: R::kind_of(action),
2333        field: R::field_of(action).map(str::to_owned),
2334        privileged: false,
2335    }
2336}
2337
2338/// What several actions applied as one are: the strongest kind among them,
2339/// below a field only when every one writes that same field. Nothing to
2340/// apply is an undoable change of the record.
2341pub(crate) fn group_need(needs: impl IntoIterator<Item = ActionNeed>) -> ActionNeed {
2342    let mut needs = needs.into_iter();
2343    let Some(mut group) = needs.next() else {
2344        return tilo_actions::ActionContract::default().need();
2345    };
2346    for need in needs {
2347        group = ActionNeed {
2348            kind: group.kind.max(need.kind),
2349            field: group
2350                .field
2351                .filter(|field| need.field.as_ref() == Some(field)),
2352            privileged: group.privileged || need.privileged,
2353        };
2354    }
2355    group
2356}
2357
2358/// The encoded group of the built `members`, of the resource `vocabulary`:
2359/// what [`ActionGroup`](crate::ActionGroup) of them encodes as. A group of
2360/// one action is that action, as `Dispatcher::group` submits it: a control
2361/// whose gesture is sometimes several actions (create a draft, then edit
2362/// it) and usually one edit records that edit, which continues the undo
2363/// step of the edit before it as the edit alone would.
2364pub(crate) fn encode_group(vocabulary: &Vocabulary, members: &[Built]) -> EncodedAction {
2365    if let [only] = members {
2366        return encoded(only);
2367    }
2368    let mut payload = Vec::with_capacity(128);
2369    payload.push(b'[');
2370    for (index, member) in members.iter().enumerate() {
2371        if index > 0 {
2372            payload.push(b',');
2373        }
2374        if let Err(error) = member.write_json(&mut payload) {
2375            return refused(&error.to_string());
2376        }
2377    }
2378    payload.push(b']');
2379    EncodedAction::written(crate::group::group_type_of(vocabulary.action_type), payload)
2380}
2381
2382pub(crate) fn group_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
2383    #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
2384    let _phase = crate::profiling::Phase::start("resource.group_spec");
2385    let build = move |args: &tilo_actions::ActionArgs, now_ms: i64| {
2386        crate::group::build_members(vocabulary, &args.to_json(), now_ms)
2387    };
2388    ActionSpec::typed(
2389        crate::GROUP,
2390        format!("Apply several {} edits as one", vocabulary.label),
2391        "Invocations as JSON",
2392        ExecutionLocus::ClientLocal,
2393        vec![group_param(vocabulary)],
2394        move |args| match build(args, origin_now_ms()) {
2395            Ok(members) => encode_group(vocabulary, &members),
2396            Err(reason) => refused(&reason),
2397        },
2398    )
2399    .with_description(
2400        "Several actions as one all-or-nothing step: one undo, and if any member refuses nothing is applied. actions: [{action: id, args: {..}}].",
2401    )
2402    // A gesture's edits, from a surface, a script or an agent; a person picks
2403    // the named actions it is made of.
2404    .for_audience(tilo_actions::Audience::Agents)
2405    // History records the members, not the group.
2406    .carrying()
2407    // Is what its most demanding member is.
2408    .with_need((vocabulary.least_need)())
2409    .with_need_of(move |args| match build(args, 0) {
2410        Ok(members) => group_need(members.iter().map(Built::need)),
2411        Err(_) => tilo_actions::ActionContract::default().need(),
2412    })
2413    // As consequential as its most consequential member.
2414    .with_risk(move |args| match build(args, 0) {
2415        Ok(members) => crate::group::group_risk(members.iter().map(Built::risk)),
2416        Err(_) => tilo_actions::RiskLevel::Low,
2417    })
2418    // Undo takes it back only when it takes back every member: one that
2419    // reaches outside the document makes a deleting group ask.
2420    .with_undo_of(move |args| match build(args, 0) {
2421        Ok(members) => members.iter().all(Built::undoable),
2422        Err(_) => false,
2423    })
2424}
2425
2426/// The default search entries of a record ([`crate::search_default`]).
2427pub use crate::search_default::default_search;
2428
2429/// The resource tree published for one open resource: every declared and
2430/// state-bound action, the generic [`APPLY`] and [`GROUP`](crate::GROUP)
2431/// actions, the named [`Resource::views`], and the nested resources.
2432///
2433/// This is the only bridge from a [`Resource`] type to the
2434/// [`tilo_actions::ResourceSpec`] tree the palette, agents, scripts and the shell
2435/// API see. Apps do not construct a second tree for the same state.
2436///
2437/// An action offered on the items of a collection (see [`crate::items`])
2438/// stays published on the record, with its id parameter, for scripts and
2439/// agents; a person picks it on the item, so it is not a palette row here.
2440pub fn publish<R: Resource>(id: &str, label: &str, state: &R::State) -> tilo_actions::ResourceSpec {
2441    publish_parts::<R>(id, label, Some(state))
2442}
2443
2444/// The resource tree built from `R`'s declarations alone, reading no state of the record: what
2445/// a write is dispatched against. An action is declared by its type, never by what the record
2446/// holds, so a write costs the change it makes, not a read of the whole record.
2447#[must_use]
2448pub(crate) fn publish_actions<R: Resource>(id: &str, label: &str) -> tilo_actions::ResourceSpec {
2449    publish_parts::<R>(id, label, None)
2450}
2451
2452/// A record's state from the reading a document host publishes for it
2453/// ([`Resource::state_json`](Resource::state_json), [`crate::Model::to_json`]):
2454/// what an app's process reads when the record lives in the session's
2455/// document host and it holds no document of its own (`docs/architecture/apps.md`
2456/// §2–§3).
2457///
2458/// The host answers the reading, and the app's own view reads its fields
2459/// through its own model types: the state a reading names is the state the
2460/// host read from its document, so what the view shows is what the host
2461/// holds.
2462///
2463/// # Errors
2464/// Returns [`ModelError`] when the type keeps no JSON form
2465/// ([`Resource::RESOURCE_TABLE`](Resource::RESOURCE_TABLE) is `None`) or
2466/// `reading` is not one of it.
2467pub fn state_from_reading<R: Resource>(
2468    reading: &serde_json::Value,
2469) -> Result<R::State, ModelError> {
2470    let table = R::RESOURCE_TABLE.ok_or_else(|| {
2471        ModelError::invalid(format!("{} keeps no reading a host answers", R::LABEL))
2472    })?;
2473    crate::table::Run(table).from_json(reading)
2474}
2475
2476/// [`publish`], or without a state only what does not depend on one: the
2477/// declared actions, [`APPLY`], [`GROUP`](crate::GROUP) and the local
2478/// operations.
2479pub(crate) fn publish_parts<R: Resource>(
2480    id: &str,
2481    label: &str,
2482    state: Option<&R::State>,
2483) -> tilo_actions::ResourceSpec {
2484    let vocabulary = vocabulary::<R>();
2485    let Some(state) = state else {
2486        let own = Own {
2487            availability: None,
2488            views: Vec::new(),
2489            local_operations: R::local_operations(),
2490            now: Vec::new(),
2491        };
2492        return publish_own(vocabulary, id, label, own, &|_| false);
2493    };
2494    let children = R::children(state);
2495    let own = Own {
2496        availability: Some(&|action| R::availability(state, action)),
2497        views: R::views(state),
2498        local_operations: R::local_operations(),
2499        now: weakening_now::<R>(state),
2500    };
2501    publish_own(vocabulary, id, label, own, &|decl| {
2502        crate::items::offered_bound(&children, decl)
2503    })
2504    .with_children(children)
2505}
2506
2507/// The resource tree published for one open document ([`publish`]) whose
2508/// state its holder could not read: its declared actions, [`APPLY`],
2509/// [`GROUP`](crate::GROUP) and the field edit, each unavailable for
2510/// `reason`, so a caller learns why they do not apply instead of finding a
2511/// hole in the surface. What a state would offer — its children, its views,
2512/// which actions can be taken now — is not published: there is no state to
2513/// read it from.
2514pub fn unreadable_parts<R: Resource>(
2515    id: &str,
2516    label: &str,
2517    reason: &str,
2518) -> tilo_actions::ResourceSpec {
2519    let label = crate::label::published(R::KIND, label, R::LABEL, R::CATALOGUE);
2520    crate::unreadable::parts::<R>(id, &label, reason)
2521}
2522
2523/// What a resource's own publication reads of its state.
2524struct Own<'a> {
2525    /// Whether each declared action can be taken now; without a state,
2526    /// none is decided.
2527    availability: Option<&'a dyn Fn(&str) -> tilo_actions::Availability>,
2528    views: Vec<tilo_actions::ResourceViewSpec>,
2529    local_operations: Vec<ActionSpec>,
2530    /// The values now of the fields that weaken one way ([`weakening_now`]).
2531    now: Vec<(String, String)>,
2532}
2533
2534/// The resource's own part of [`publish_parts`]: everything but its
2535/// children, with `offered_bound` saying which declarations a child offers
2536/// with arguments bound.
2537fn publish_own(
2538    vocabulary: &'static Vocabulary,
2539    id: &str,
2540    label: &str,
2541    own: Own<'_>,
2542    offered_bound: &dyn Fn(&Declaration) -> bool,
2543) -> tilo_actions::ResourceSpec {
2544    let _phase = crate::profiling::Phase::start("resource.published");
2545    // The name the person reads, in their language: the kind's catalogue
2546    // entry while the publisher kept the name the declaration gave it.
2547    let label = crate::label::published(
2548        vocabulary.kind,
2549        label,
2550        vocabulary.label,
2551        vocabulary.catalogue,
2552    );
2553    let mut resource = tilo_actions::ResourceSpec::new(id, vocabulary.kind, &label);
2554    // Describe the declared domain ID before any host dispatch alias projection.
2555    resource.semantic_identity = tilo_actions::ResourceSemanticIdentity::new(vocabulary.kind, id);
2556    // The app it publishes under: what an action's `ActionKey` names, and
2557    // what a control bound by key is checked against.
2558    resource.app_id = Some(vocabulary.app.to_owned());
2559    // What it is, as people name it: its type's noun, its app's name and
2560    // whether it is that app's root. Exactly a tilolang type's, so the one
2561    // search matches a Rust and a tilolang type alike. Its noun is the
2562    // *type's* (`vocabulary.label`), never the record's own title: a channel
2563    // called "MKBHD" is a `channel`, not an `m k b h d`.
2564    resource = resource.with_type(crate::words::type_words(vocabulary.kind, vocabulary.label));
2565    let kept = own_specs(vocabulary);
2566    for (decl, declared) in vocabulary.declarations().iter().zip(kept.declared.iter()) {
2567        let _phase = crate::profiling::Phase::start("resource.declaration_spec");
2568        // Another declaration a child offers with some of its arguments
2569        // bound ([`items::bound`](crate::items::bound)) needs nothing in
2570        // hand, and stays here for scripts, out of the palette's way.
2571        let mut spec = if decl.item.is_none() && offered_bound(decl) {
2572            declared.for_agents.clone()
2573        } else {
2574            declared.offered.clone()
2575        };
2576        // Whether it can be taken now is the resource's own: its type is
2577        // copied only where that differs from what the kept one says.
2578        if let Some(availability) = own.availability {
2579            let now = availability(decl.id);
2580            if spec.contract.availability != now {
2581                spec.type_mut().contract.availability = now;
2582            }
2583        }
2584        resource = resource.with_action(spec);
2585    }
2586    for view in own.views {
2587        resource = resource.with_view(view);
2588    }
2589    crate::share::offer(&mut resource);
2590    for spec in own.local_operations {
2591        if spec.kind == OperationKind::Document {
2592            continue;
2593        }
2594        resource = resource.with_action(spec);
2595    }
2596    resource = resource
2597        .with_action(kept.apply.clone())
2598        .with_action(kept.group.clone());
2599    if vocabulary.edits {
2600        resource = resource.with_action(field_edit_spec(vocabulary, own.now));
2601    }
2602    resource
2603}
2604
2605/// The actions every resource of a vocabulary offers as its own, the same
2606/// on each: its declarations, its typed edit and its group.
2607struct OwnSpecs {
2608    /// Each declaration's spec, in [`Vocabulary::declarations`]' order.
2609    declared: Box<[DeclaredSpec]>,
2610    apply: ActionSpec,
2611    group: ActionSpec,
2612}
2613
2614/// One declaration's spec as a resource offers it, and as it offers it to
2615/// agents alone where a child offers the declaration bound.
2616struct DeclaredSpec {
2617    offered: ActionSpec,
2618    for_agents: ActionSpec,
2619}
2620
2621/// [`OwnSpecs`] of `vocabulary`, kept like every type the items of a kind
2622/// share ([`crate::kept`]): building a declaration's spec builds its
2623/// parameters and schema, and publishing each of a tracker's thousands of
2624/// issues built every one of them again for each issue.
2625fn own_specs(vocabulary: &'static Vocabulary) -> std::rc::Rc<OwnSpecs> {
2626    thread_local! {
2627        static KEPT: std::cell::RefCell<crate::kept::KeptTypes<TypeId, std::rc::Rc<OwnSpecs>>> =
2628            std::cell::RefCell::default();
2629    }
2630    crate::kept::kept_type(&KEPT, (vocabulary.type_id)(), || {
2631        let declared = vocabulary
2632            .declarations()
2633            .iter()
2634            .map(|decl| {
2635                let mut offered = spec_of_declaration(decl);
2636                // An item verb stays published here for a caller that names
2637                // the item, saying it needs one: a listing holding no item
2638                // leaves it to the items, which offer it bound.
2639                if let Some(item) = decl.item {
2640                    offered.type_mut().contract.item = Some(item.to_owned());
2641                }
2642                let for_agents = offered.clone().for_audience(tilo_actions::Audience::Agents);
2643                DeclaredSpec {
2644                    offered,
2645                    for_agents,
2646                }
2647            })
2648            .collect();
2649        std::rc::Rc::new(OwnSpecs {
2650            declared,
2651            apply: apply_spec(vocabulary),
2652            group: group_spec(vocabulary),
2653        })
2654    })
2655}
2656
2657/// Build the action a declaration produces for JSON arguments, validating them
2658/// against its parameters exactly as the host does.
2659pub fn build_action<R: Resource>(
2660    id: &str,
2661    arguments: &serde_json::Map<String, serde_json::Value>,
2662    now_ms: i64,
2663) -> Result<R::Action, String> {
2664    typed::<R>(build_action_of(vocabulary::<R>(), id, arguments, now_ms)?)
2665}
2666
2667/// [`build_action`] of the resource `vocabulary`, on the side invoking it
2668/// ([`crate::content::invoking`]).
2669pub(crate) fn build_action_of(
2670    vocabulary: &Vocabulary,
2671    id: &str,
2672    arguments: &serde_json::Map<String, serde_json::Value>,
2673    now_ms: i64,
2674) -> Result<Built, String> {
2675    crate::content::invoking(|| build_invoked(vocabulary, id, arguments, now_ms))
2676}
2677
2678fn build_invoked(
2679    vocabulary: &Vocabulary,
2680    id: &str,
2681    arguments: &serde_json::Map<String, serde_json::Value>,
2682    now_ms: i64,
2683) -> Result<Built, String> {
2684    if id == crate::GROUP {
2685        return Err("a group is several actions; build it with `group::build_group`".into());
2686    }
2687    let read = if id == APPLY {
2688        Some((APPLY_PARAM, "missing action"))
2689    } else if id == FIELD_EDIT && vocabulary.edits {
2690        Some((EDIT_PARAM, "missing edit"))
2691    } else {
2692        None
2693    };
2694    if let Some((param, missing)) = read {
2695        let Some(value) = arguments.get(param).cloned() else {
2696            return Err(missing.to_owned());
2697        };
2698        let mut action = if id == APPLY {
2699            read_apply(vocabulary, value)?
2700        } else {
2701            read_edit(vocabulary, value)?
2702        };
2703        action.stamp(now_ms);
2704        return Ok(action);
2705    }
2706    let declarations = vocabulary.declarations();
2707    let Some(decl) = declarations.iter().find(|decl| decl.id == id) else {
2708        return Err(format!("{} has no action `{id}`", vocabulary.label));
2709    };
2710    let args = match ActionArgs::bind_json(&decl.params, arguments) {
2711        Ok(args) => args,
2712        Err(error) => return Err(error.to_string()),
2713    };
2714    (decl.build)(&args, now_ms)
2715}
2716
2717/// `resource` with the bound edit `decl` published on it.
2718///
2719/// An id the resource does not declare is added. One it declares is kept,
2720/// unless `decl` says it refines it ([`ActionDecl::refining`]) and takes the
2721/// same parameters with the same permission and risk: then it builds the
2722/// same edit from the same arguments and only adds where it was invoked from
2723/// (an append that leaves its writer's caret after the text), and replaces
2724/// the declared spec while the binding lasts.
2725#[must_use]
2726pub fn bind_declaration(
2727    resource: tilo_actions::ResourceSpec,
2728    decl: &Declaration,
2729) -> tilo_actions::ResourceSpec {
2730    let spec = spec_of_declaration(decl);
2731    let mut resource = resource;
2732    match resource
2733        .actions
2734        .iter_mut()
2735        .find(|existing| existing.id == decl.id)
2736    {
2737        Some(declared) => {
2738            if decl.refines && same_shape(&spec, declared) {
2739                *declared = spec;
2740            }
2741            resource
2742        }
2743        None => resource.with_action(spec),
2744    }
2745}
2746
2747fn same_shape(bound: &ActionSpec, declared: &ActionSpec) -> bool {
2748    let shape = |spec: &ActionSpec| {
2749        spec.params()
2750            .iter()
2751            .map(|param| (param.name.to_string(), param.ty, param.required))
2752            .collect::<Vec<_>>()
2753    };
2754    bound.kind == declared.kind
2755        && shape(bound) == shape(declared)
2756        && bound.contract.kind == declared.contract.kind
2757        && bound.contract.field == declared.contract.field
2758        && bound.contract.risk == declared.contract.risk
2759}
2760
2761/// A resource that one app keeps for every app of the workspace: its
2762/// accounts, which Settings keeps and Mail signs in to; the people it knows,
2763/// which Contacts keeps and Mail, Calendar and Messages address. Opened as
2764/// the workspace's record, at the keeper's route (`ViewCx::shared_workspace`
2765/// in `tilo-app`): one record for every member, its changes decided by the
2766/// workspace's grants on the keeper's resource.
2767pub trait SharedResource: Resource {
2768    /// The app that keeps the record: whose route holds it, and whose surface
2769    /// its changes are decided against.
2770    const OWNER: &'static str;
2771}
2772
2773#[derive(Clone, Debug, Default, PartialEq, Eq)]
2774pub struct SearchRow {
2775    /// The dimmer line under the title (an address, a path, a date).
2776    pub subtitle: Option<String>,
2777    /// A named icon from the icon set (`"mail"`, `"calendar"`); `None` draws
2778    /// the app's own.
2779    pub icon: Option<String>,
2780    /// What the hit is, for the row's shape.
2781    pub shape: SearchRowShape,
2782}
2783
2784impl SearchRow {
2785    /// A generic row with `subtitle` under the title.
2786    pub fn subtitle(subtitle: impl Into<String>) -> Self {
2787        Self {
2788            subtitle: Some(subtitle.into()),
2789            ..Self::default()
2790        }
2791    }
2792
2793    /// A row of `shape`.
2794    #[must_use]
2795    pub fn shaped(shape: SearchRowShape) -> Self {
2796        Self {
2797            shape,
2798            ..Self::default()
2799        }
2800    }
2801
2802    /// The row's named icon.
2803    #[must_use]
2804    pub fn icon(mut self, name: impl Into<String>) -> Self {
2805        self.icon = Some(name.into());
2806        self
2807    }
2808}
2809
2810#[derive(Clone, Debug, Default, PartialEq, Eq)]
2811pub enum SearchRowShape {
2812    /// Icon, title and subtitle.
2813    #[default]
2814    Plain,
2815    /// A message: who sent it, a snippet, when, and whether it is unread.
2816    Message {
2817        sender: String,
2818        snippet: Option<String>,
2819        date: Option<String>,
2820        unread: bool,
2821    },
2822    /// A video, track or other media item: who made it and how long it
2823    /// runs. (A provider with artwork answers its own rows, with
2824    /// `AppImage::from_image_store` thumbnails.)
2825    Media {
2826        byline: Option<String>,
2827        duration: Option<String>,
2828    },
2829    /// A match inside a file: the path, the line and the matched line.
2830    FileHit {
2831        path: String,
2832        line: Option<u32>,
2833        snippet: String,
2834    },
2835}
2836
2837pub use tilo_actions::{ScopeDecl, scope_contains};
2838
2839#[cfg(test)]
2840mod schema_sharing_tests;
2841
2842#[cfg(test)]
2843mod selection_place_tests {
2844    use super::Place;
2845    use tilo_actions::SelectionPlace;
2846    use tilo_actions::selection::MAX_PLACE_ITEM_BYTES;
2847
2848    #[test]
2849    fn a_selection_place_is_the_place_an_action_takes() {
2850        for (place, expected_json) in [
2851            (Place::Item("p1".into()), r#"{"item":"p1"}"#),
2852            (
2853                Place::Caret {
2854                    item: "p1".into(),
2855                    at: 3,
2856                },
2857                r#"{"item":"p1","at":3}"#,
2858            ),
2859            (
2860                Place::Range {
2861                    item: "p1".into(),
2862                    start: 2,
2863                    end: 7,
2864                },
2865                r#"{"item":"p1","start":2,"end":7}"#,
2866            ),
2867            (
2868                Place::Item("a".repeat(MAX_PLACE_ITEM_BYTES)),
2869                &format!(r#"{{"item":"{}"}}"#, "a".repeat(MAX_PLACE_ITEM_BYTES)),
2870            ),
2871        ] {
2872            let wire = serde_json::to_string(&place).unwrap();
2873            assert_eq!(wire, expected_json, "valid places serialise as before");
2874            let selection = SelectionPlace::from(place.clone());
2875            assert_eq!(
2876                serde_json::to_string(&selection).unwrap(),
2877                wire,
2878                "both travel in one wire form"
2879            );
2880            assert_eq!(serde_json::from_str::<Place>(&wire).unwrap(), place);
2881            assert_eq!(Place::try_from(selection).unwrap(), place);
2882        }
2883
2884        let overlong_ascii = "a".repeat(MAX_PLACE_ITEM_BYTES + 1);
2885        let overlong_utf8 = "界".repeat(MAX_PLACE_ITEM_BYTES / 3 + 1);
2886        assert!(overlong_utf8.len() > MAX_PLACE_ITEM_BYTES);
2887
2888        for bad_item in [
2889            String::new(),
2890            overlong_ascii,
2891            overlong_utf8,
2892            "p\n1".to_owned(),
2893            "p\u{0}1".to_owned(),
2894            "p\x1b1".to_owned(),
2895            "p\t1".to_owned(),
2896        ] {
2897            for selection in [
2898                SelectionPlace::item(bad_item.clone()),
2899                SelectionPlace::caret(bad_item.clone(), 0),
2900                SelectionPlace::range(bad_item.clone(), 0, 1),
2901            ] {
2902                assert!(
2903                    Place::try_from(selection.clone()).is_err(),
2904                    "Place::try_from accepted invalid SelectionPlace: {selection:?}"
2905                );
2906                let json = serde_json::to_value(&selection).unwrap();
2907                assert!(
2908                    serde_json::from_value::<Place>(json.clone()).is_err(),
2909                    "Place::deserialize accepted invalid JSON: {json}"
2910                );
2911            }
2912        }
2913
2914        for malformed in [
2915            serde_json::json!({"item": "p1", "at": 1, "start": 0, "end": 2}),
2916            serde_json::json!({"item": "p1", "start": 2}),
2917            serde_json::json!({"item": "p1", "end": 2}),
2918            serde_json::json!({"item": "p1", "start": 5, "end": 2}),
2919        ] {
2920            let wire: SelectionPlace = serde_json::from_value(malformed.clone()).unwrap();
2921            let from_selection = Place::try_from(wire).unwrap_err();
2922            let from_json = serde_json::from_value::<Place>(malformed)
2923                .unwrap_err()
2924                .to_string();
2925            for error in [&from_selection, &from_json] {
2926                assert!(
2927                    error.contains("at") && error.contains("start") && error.contains("end"),
2928                    "malformed-shape error should name `at` and `start`/`end`: {error}"
2929                );
2930            }
2931        }
2932        assert!(
2933            serde_json::from_value::<Place>(serde_json::json!({"item": "p1", "extra": true}))
2934                .is_err()
2935        );
2936    }
2937}