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