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