tilo-resource 0.5.0

The Tilo resource layer: typed, hierarchical app resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
//! # The Tilo resource layer
//!
//! A Tilo app's state is a set of **resources**: typed, versioned, shared
//! values the system owns. This crate is the layer that turns a Rust type into
//! one. It has no rendering, windowing or widget dependency. The UI toolkit
//! uses only its document-generic parts (history, stamped commits, replay);
//! `tilo-app` binds resources to views.
//!
//! ## The golden path
//!
//! ```
//! use tilo_resource::{ActionCx, Collection, Id, Model, resource};
//!
//! #[derive(Model, Default)]
//! pub struct Todo {
//!     pub items: Collection<Item>,
//! }
//!
//! #[derive(Model, Default)]
//! pub struct Item {
//!     pub title: String,
//!     pub done: bool,
//! }
//!
//! #[resource(kind = "example.todo")]
//! impl Todo {
//!     /// Add an item.
//!     #[action]
//!     pub fn add(&mut self, cx: &mut ActionCx, title: String) {
//!         self.items.push(cx.id(), Item { title, done: false });
//!     }
//!
//!     /// Mark an item done or not done.
//!     #[action]
//!     pub fn set_done(&mut self, item: Id, done: bool) -> Result<(), &'static str> {
//!         self.items.get_mut(&item).ok_or("no such item")?.done = done;
//!         Ok(())
//!     }
//! }
//!
//! // Tests are replay: apply actions the way a control, the palette, an agent
//! // or a script would, and assert on state.
//! fn main() {
//!     // A replica names the app whose record it is before it applies anything: every device
//!     // decides its changes against that app's surface.
//!     let mut replica = tilo_resource::Replica::<Todo>::new().in_app("so.tilo.todo", "Todo");
//!     replica.apply(Todo::ADD.with("Buy milk")).unwrap();
//!     let id = replica.state().unwrap().items.ids().next().unwrap().clone();
//!     replica.apply(Todo::SET_DONE.with((id, true))).unwrap();
//!     assert!(replica.state().unwrap().items.values().all(|item| item.done));
//! }
//! ```
//!
//! That is the whole app-side state layer. From it the app gets, without
//! writing any of it:
//!
//! * **storage and sync** — the resource is an Automerge document; every field
//!   write is a minimal diff, text is spliced, collections are keyed and
//!   fractionally ordered, so members' concurrent edits merge;
//! * **replayable actions** — each `#[action]` method is a serializable
//!   operation with typed parameters, applied deterministically (ids and time
//!   come from [`ActionCx`]) and replayed byte-identically on every replica;
//! * **exposure** — the same declarations are what the palette, agents and
//!   scripts list and invoke ([`publish`]), with permissions per action, and
//!   the generic [`APPLY`] operation publishes a JSON Schema of the action
//!   vocabulary ([`Resource::action_schema`], [`JsonSchema`]);
//! * **history** — every action is a change attributed to its author with its
//!   label and time ([`history`]); any version can be read back
//!   ([`history::read_at`]) and restored, field by field and item by item,
//!   from the record's stored [`Shape`];
//! * **search** — text fields are indexed by default ([`Resource::search`]);
//! * **reading** — a record whose declaration names a document read answers
//!   the framework's `read` with what it holds, as typed data
//!   ([`read::fields`] for a record whose fields are all it holds), so an
//!   agent, a script or the SDK with no window open reads any record through
//!   the same action, permissions and audit as everything else;
//! * **lookup by kind** — a host that works with whatever a workspace holds
//!   reads, publishes and replays any registered type from the kind its
//!   record names ([`Kinds`], [`ResourceKind`]);
//! * **document machinery** — fractional [`order`] keys, stamped commits and
//!   positional replay ([`history`]), writing large content as a few changes
//!   ([`batch`]) and id-aligned structural [`diff`]s, shared by every
//!   resource type including the hand-written ones;
//! * **incremental reads** — after a change only what it touched is read
//!   again ([`Resource::refresh`], [`Delta`]); a record resource gets this
//!   field by field and item by item, and a resource too large to read whole
//!   reads what views look at ([`Resource::load`], [`Demand`]).
//!
//! ## Custom resource types
//!
//! A type with its own layout and merge semantics — a rich-text document, a
//! sheet — implements [`Resource`] by hand: [`read`](Resource::read) its
//! state from a document, name its replayable [`Action`](Resource::Action)
//! type, and optionally [`declarations`](Resource::declarations) for named,
//! typed palette entries. The SDK ships those types (`RichText`, plain text,
//! `Grid`); an app derives its record with `#[derive(Model)]` and
//! `#[resource]` and holds them as fields, never implementing `Resource`
//! itself (docs/architecture/resources.md §8). Such a type gets exactly the
//! same services. Edits without a named declaration travel as the generic
//! [`APPLY`] action, so nothing a custom surface does has to bypass
//! permissions, history or undo. `APPLY` is for surfaces, agents and
//! scripts, never a palette row; each value's own
//! [`risk`](tilo_actions::Action::risk) decides whether it needs
//! confirmation, so a destructive typed edit is treated exactly as a
//! declared destructive action is: what Undo takes back runs at once and
//! offers Undo, and only what it cannot is confirmed.

// The derives name this crate by its path, here as in an app.
extern crate self as tilo_resource;

mod absolute_path;
pub mod action;
mod apply_cache;
pub mod batch;
pub mod child;
pub mod children;
mod chunk_map;
mod clock;
pub mod collection;
#[cfg(test)]
mod concurrent_text_tests;
pub mod content;
mod cow;
mod dates;
mod search_preview;
pub use search_preview::SearchPreview;
pub mod delta;
pub mod derived;
mod describe;
pub mod diff;
pub mod effect;
pub mod evolution;
pub mod footprint;
pub mod genesis;
pub mod group;
pub mod history;
pub mod items;
mod kept;
pub mod keyed;
pub mod kind;
pub mod label;
mod map;
pub mod members;
pub mod model;
mod non_blank;
pub mod order;
pub mod ordered;
pub mod origin;
pub mod path;
pub mod reactions;
pub mod read;
pub mod reader;
mod recents;
pub mod recording;
pub mod replica;
pub mod resource;
pub mod row;
pub mod schema;
pub mod schema_check;
pub mod search_default;
pub use tilo_actions::search_index;
pub mod shape;
pub mod share;
pub mod sort;
pub mod status;
pub mod storage;
pub mod stored_items;
pub mod surface;
pub mod table;
pub mod text;
pub mod unreadable;
mod upsert;
mod value;
pub mod vocabulary;
pub mod words;

pub use __private::FlatFields;
pub use absolute_path::{AbsolutePath, RelativePath};
pub use action::{
    ActionCx, ActionKey, ActionKind, ActionRef, Binds, Invoke, Mapped, NoParams, Operation,
    Outcome, Params, Refusal, Reverting, Stamped, TryMapped, Undoing, fresh_uuid, invoking_member,
    invoking_name, minted_entry, minted_ids, minted_keys, restore_minted, reverting_type,
    take_minted,
};
/// A change a document reports, as an `answer` hook reads what its action did.
pub use automerge::Patch;
pub use child::{child_resource_id, publish_child};
pub use children::{ChildList, ChildRef, Children, Trashed};
pub use clock::HybridClock;
pub use collection::{
    Collection, Id, Membership, Quarantined, stored_entry, stored_ids, stored_item,
};
pub use delta::{Delta, ObjPath, Touch, Touched, Tracker};
pub use derived::{Bound, Derived};
pub use effect::{
    Answers, Effect, EffectDecl, EffectDecodeError, EffectOffload, EffectTarget, NoEffect, decode,
    offer,
};
pub use evolution::Unreadable;
pub use group::{ActionGroup, GROUP, GROUP_PARAM};
pub use keyed::{ById, Identified, ItemStorage, Items, Keyed};
pub use kind::{Kinds, ResourceKind};
pub use map::Map;
pub use model::{
    Atom, Doc, Fields, Fresh, LocatedAt, MapSlot, Model, ModelError, Slot, VARIANT_KEY, edit_whole,
    load_slot, read_key, read_slots, refresh_key, take_slot, write_key, write_key_changed,
};
pub use non_blank::{Blank, NonBlank};
pub use ordered::{Arranged, Ordered};
pub use origin::Origin;
pub use path::{
    At, Edit, EditOp, OP_ARGUMENTS, Operations, Path, Segment, Settable, op_argument_schema,
    op_arguments, op_usage, outbox_settle_arguments,
};
pub use reactions::{
    Reaction, ReactionGroup, Reactions, Reactor, custom_emoji_name, reaction_emoji,
    valid_custom_emoji_name,
};
pub use reader::{Demand, Reader, heads_of};
pub use recents::Recents;
pub use replica::{AppNamed, NoApp, Replica};
pub use resource::{
    APPLY, APPLY_PARAM, ActionDecl, BuildAction, EDIT_PARAM, FIELD_EDIT, HeadInputs, NamesItem,
    NoAction, Place, Resource, ScopeDecl, SearchBody, SearchEntry, SearchPiece, SearchRow,
    SearchRowShape, SearchText, SearchWeight, SharedResource, bind_declaration, build_action,
    by_app_refusal, child_by_id, declaration_spec, default_search, encode, head_inputs, need_of,
    origin_now_ms, publish, publish_head, publish_head_of, reset_type_schemas, scope_contains,
    spec_kind, state_from_reading, with_origin_clock,
};
pub use row::{Handle, LiveRow, RowBindings, typed_resource};
pub use schema::JsonSchema;
pub use shape::{FieldShape, Shape, StoredText, Trust, absent_scalar, stored_text};
pub use status::EffectStatus;
pub use storage::{Bytes, Counter, Grid, Outbox, OutboxEntry, Set, Settled};
pub use surface::Surface;
pub use text::{PlainText, TextEdit};
pub use tilo_action_policy::edits::Weaker;
pub use tilo_action_policy::{DIRECT_CONVERSATION_PREFIX, MemberId, PersonId};
pub use tilo_actions::surface::{FieldType, TypeSet};
pub use tilo_actions::{Acting, Availability};
pub use tilo_resource_macros::{Effect, JsonSchema, Model, Row, committed_surface, resource};
pub use tilo_sort::{Frecency, frecency};
pub use unreadable::withhold_document_actions;
pub use vocabulary::{Built, Declaration, Vocabulary, vocabulary};

/// A word of the catalogue beside the crate that names it,
/// `word!("files-rename-here")`: a [`label::Word`] read in the person's
/// language whenever what carries it is published. A key the crate's
/// `locales/en-US.ftl` does not hold does not build;
/// `word!("key", catalogue = "tests/locales")` reads another catalogue.
///
/// A word that names what a person is looking at carries it as an argument —
/// `word!("files-folder-rename-selected", name = file.0)` — which the
/// catalogue's message shows with its placeable (`Rename “{ $name }”`) in
/// every language the crate translates it into, and a count by its forms
/// (`{ $count -> [one] … }`). An argument the message has no placeable for,
/// or a placeable with no argument, does not build.
#[macro_export]
macro_rules! word {
    ($($input:tt)*) => {
        $crate::__private::word!($crate, $($input)*)
    };
}

/// Items the generated code refers to. Not part of the public API.
#[doc(hidden)]
pub mod __private {
    pub use automerge::{ObjId, ObjType, Patch, ROOT, ReadDoc, ScalarValue, Value};
    pub use serde;
    pub use serde_json;
    pub use tilo_actions::{
        ActionArgs, ActionKind, ActionParam, ActionRegistry, ActionSpec, Audience, ChangeKind,
        HOST_RENDER_TAG, OperationKind, PROMPTED_PARAM, ParamType, ResourceSpec, ResourceViewSpec,
        RiskLevel, SCREEN_PLACE_TAG, SCREEN_TAG, StepKind, picked_address_schema,
        picked_resource_schema,
    };
    pub use tilo_resource_macros::word;

    pub use crate::apply_cache::forget_all;

    /// Whether `record` holds an item where the nested item verb `action`
    /// acts: what its children would offer it bound on.
    #[must_use]
    pub fn holds_nested_items(
        record: &crate::table::ResourceDesc,
        state: &dyn std::any::Any,
        action: &crate::items::ItemAction,
    ) -> bool {
        let Some(field) = action.collection else {
            return false;
        };
        let mut path: Vec<&str> = action.within.to_vec();
        path.push(field);
        crate::table::holds_nested_items(record, state, &path)
    }

    /// A record to copy, if its type can be copied: `#[resource]` asks for
    /// `(&&Snapshot(record)).snapshot()`, which method resolution answers
    /// with [`SnapshotByClone`] for a `Clone` record and with
    /// [`SnapshotUnavailable`] otherwise.
    pub struct Snapshot<'a, T>(pub &'a T);

    /// A copy of a `Clone` record.
    pub trait SnapshotByClone<T> {
        fn snapshot(&self) -> Option<T>;
    }

    impl<T: Clone> SnapshotByClone<T> for &Snapshot<'_, T> {
        fn snapshot(&self) -> Option<T> {
            Some(self.0.clone())
        }
    }

    /// No copy of a record that cannot be cloned.
    pub trait SnapshotUnavailable<T> {
        fn snapshot(&self) -> Option<T>;
    }

    impl<T> SnapshotUnavailable<T> for Snapshot<'_, T> {
        fn snapshot(&self) -> Option<T> {
            None
        }
    }

    /// `T`'s value of a field `key` the document does not hold, located at
    /// it: one function per field type, not a closure per field.
    ///
    /// # Errors
    /// Why `T` has no such value.
    use crate::model::LocatedAt as _;

    /// The field edit `op` at `rest` inside the field `key` of `obj`,
    /// located at it.
    pub fn edit_at<T: crate::Model>(
        doc: &mut crate::Doc,
        obj: &ObjId,
        key: &str,
        rest: &[crate::Segment],
        op: &crate::EditOp,
        cx: &mut crate::ActionCx,
    ) -> Result<(), crate::ModelError> {
        T::edit(doc, crate::Slot::Key(obj, key), rest, op, cx).located(key)
    }

    /// How a verb's change is undone.
    #[derive(Clone, Copy, PartialEq, Eq)]
    pub enum VerbUndo {
        /// By reverting the document: the change is all there is.
        Revert,
        /// By its compensating verb (`#[action(undo = ...)]`): it also
        /// queued an outside consequence, which only that takes back.
        Compensation,
    }

    /// What a verb answers its caller.
    #[derive(Clone, Copy, PartialEq, Eq)]
    pub enum VerbAnswer {
        /// Only the items it created.
        Created,
        /// What it made (`#[action(answers)]`, [`crate::Resource::answer`]).
        Made,
        /// What the outside work it queued came back with, once a host
        /// performed it.
        Queued,
    }

    /// What `#[resource]` declares of one verb, besides how it is built.
    #[derive(Clone)]
    #[allow(
        clippy::struct_excessive_bools,
        reason = "one independent `#[action(...)]` flag each, as the macro reads them"
    )]
    pub struct VerbDecl {
        pub id: &'static str,
        pub label: crate::label::Word,
        /// The other words people use for it (`keywords = "…"`).
        pub keywords: &'static [&'static str],
        /// Its own picture (`icon = "…"`), by its Lucide name.
        pub icon: Option<&'static str>,
        /// What it did, in the app's own words (`did = "…"`), read after who
        /// did it.
        pub did: Option<&'static str>,
        pub description: &'static str,
        pub kind: ActionKind,
        /// Whether one invocation's kind is decided by its arguments
        /// (`#[action(local = path)]`); `kind` is then the least it is.
        pub by_arguments: bool,
        pub field: Option<&'static str>,
        pub destructive: bool,
        /// It also loses what Undo cannot bring back
        /// (`#[action(irreversible)]`).
        pub irreversible: bool,
        /// A change about the record rather than to it
        /// (`#[action(housekeeping)]`).
        pub housekeeping: bool,
        pub answer: VerbAnswer,
        /// It records a message someone received (`#[action(incoming_message)]`).
        pub incoming_message: bool,
        /// How its change is undone.
        pub undo: VerbUndo,
        /// Who listings offer it to (`#[action(audience = "agents")]`).
        pub audience: tilo_actions::Audience,
        pub collects: Option<&'static str>,
        /// The parameter the content it collects arrives as.
        pub content: Option<&'static str>,
        pub item_field: Option<&'static str>,
        /// The collection whose item it acts on, when it is offered on items
        /// (`#[action(item = field)]`, or an item id its first parameter).
        pub item: Option<&'static str>,
        pub writes: &'static [&'static str],
        /// The kind of step it takes (`#[action(step = "create")]`): what
        /// presence says of it
        /// ([`tilo_actions::StepKind`]). `None` for a verb whose declaration
        /// names none, whose step reads as the part of the record it acts on.
        pub step: Option<tilo_actions::StepKind>,
        pub shape: crate::Shape,
        pub params: &'static [ParamDecl],
    }

    /// What `#[resource]` declares of one parameter of a verb: static data,
    /// made into the published parameter by one function for every verb.
    #[derive(Clone, Copy)]
    pub struct ParamDecl {
        pub name: &'static str,
        pub ty: ParamTypeOf,
        pub description: &'static str,
        /// The schema of the parameter's type.
        pub schema: fn() -> serde_json::Value,
        pub optional: bool,
        pub place: PlaceIn,
        pub example: Option<fn() -> serde_json::Value>,
        /// Its type's fields are the verb's parameters, each its own.
        pub flat: bool,
        /// For a flattened parameter, its type's fields and their published
        /// types, by name: what names an enum or record a nested argument is.
        pub flat_types: Option<crate::surface::FlatTypes>,
        /// It takes content another action produced, by its hash, beside
        /// the verb's other parameters.
        pub content: bool,
        /// Its type in the surface's vocabulary.
        pub field_type: crate::vocabulary::ParamFieldType,
    }

    /// A declared parameter's type.
    #[derive(Clone, Copy)]
    pub enum ParamTypeOf {
        /// Known from the Rust type.
        Known(ParamType),
        /// Read off the schema of the (present) value's type.
        Schema(fn() -> serde_json::Value),
    }

    /// A record's fields as an action's own parameters, typed as the record
    /// declares them: what `#[param(flatten)]` publishes, so an argument that
    /// is an enum names that enum rather than "any".
    pub trait FlatFields {
        /// The record's fields, in declaration order, with the types the
        /// record declares them; the types it names are declared in `types`.
        fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)>;
    }

    impl<T: crate::JsonSchema> FlatFields for T {
        fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)> {
            let crate::FieldType::Named(name) = <T as crate::JsonSchema>::field_type(types) else {
                return Vec::new();
            };
            types
                .get(&name)
                .map(|record| {
                    record
                        .fields
                        .iter()
                        .map(|field| (field.name.clone(), field.ty.clone()))
                        .collect()
                })
                .unwrap_or_default()
        }
    }

    /// The published parameters of `params`.
    #[must_use]
    pub fn params_of(params: &[ParamDecl]) -> Vec<ActionParam> {
        let mut out = Vec::with_capacity(params.len());
        for param in params {
            if param.flat {
                out.extend(flat_params(&(param.schema)()));
                continue;
            }
            let ty = match param.ty {
                ParamTypeOf::Known(ty) => ty,
                ParamTypeOf::Schema(schema) => param_type_of(&schema()),
            };
            let declared = declared_param(
                param.name,
                ty,
                param.description,
                param.schema,
                param.optional,
                param.place,
                param.example,
            );
            out.push(if param.content {
                declared.as_content()
            } else {
                declared
            });
        }
        out
    }

    /// The declaration of the verb `verb`, built by `build`.
    pub fn declare<R: crate::Resource>(
        verb: VerbDecl,
        build: fn(&ActionArgs, i64) -> Result<R::Action, String>,
    ) -> crate::ActionDecl<R> {
        let builds: crate::vocabulary::Builds =
            std::sync::Arc::new(move |args, now_ms| match build(args, now_ms) {
                Ok(action) => Ok(crate::Built::of::<R>(action)),
                Err(reason) => Err(reason),
            });
        crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
    }

    /// The declaration of the verb `verb` of the record `R`, whose action
    /// is its operation `O` decoded from the arguments: one build for
    /// every verb of the record.
    pub fn declare_verb<R, O>(verb: VerbDecl) -> crate::ActionDecl<R>
    where
        R: crate::Resource<Action = crate::Stamped<O>>,
        O: serde::de::DeserializeOwned,
    {
        let (id, content) = (verb.id, verb.content);
        let builds: crate::vocabulary::Builds = std::sync::Arc::new(move |args, now_ms| {
            let arguments = verb_arguments(args, content);
            match build_stamped::<O>(id, &arguments, now_ms) {
                Ok(action) => Ok(crate::Built::of::<R>(action)),
                Err(reason) => Err(reason),
            }
        });
        crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
    }

    /// The arguments of a verb invoked with `args`, the content it collects
    /// (if any) under its parameter `content`.
    fn verb_arguments(
        args: &ActionArgs,
        content: Option<&'static str>,
    ) -> serde_json::Map<String, serde_json::Value> {
        let mut arguments = args.to_json();
        if let Some(content) = content
            && let Some(hash) = arguments.remove(PROMPTED_PARAM)
        {
            arguments.insert(String::from(content), hash);
        }
        arguments
    }

    /// The declaration of `verb` of the resource `vocabulary`, built by
    /// `build`.
    fn verb_declaration(
        vocabulary: &crate::Vocabulary,
        verb: VerbDecl,
        build: crate::vocabulary::Builds,
    ) -> crate::Declaration {
        let written = verb.label.source;
        let mut decl = crate::Declaration::new(
            vocabulary,
            verb.id,
            written.to_owned(),
            params_of(verb.params),
            build,
        );
        decl.word = Some(verb.label);
        decl.param_types = verb
            .params
            .iter()
            .filter(|param| !param.flat)
            .map(|param| (param.name, param.field_type))
            .collect();
        decl.flat_types = verb
            .params
            .iter()
            .find(|param| param.flat)
            .and_then(|param| param.flat_types);
        decl.kind = verb.kind;
        decl.keywords = verb
            .keywords
            .iter()
            .map(|word| (*word).to_owned())
            .collect();
        decl.icon = verb.icon.map(str::to_owned);
        decl.did = verb.did.map(str::to_owned);
        decl.by_arguments = verb.by_arguments;
        decl.writes = crate::footprint::declared(verb.shape, verb.item_field, verb.writes);
        decl.item = verb.item;
        // What the description says beyond its first line, the label.
        let description = verb
            .description
            .strip_prefix(written)
            .map_or(verb.description, |rest| {
                rest.trim_start_matches('.').trim_start()
            });
        if !description.is_empty() {
            decl.description = Some(description.to_owned());
        }
        decl.field = verb.field;
        decl.destructive = verb.destructive;
        decl.step = verb
            .step
            .or_else(|| verb.destructive.then_some(tilo_actions::StepKind::Delete));
        // A create that declares the collection it adds to makes one of them:
        // its step says that collection's noun ("an issue").
        decl.creates = (decl.step == Some(tilo_actions::StepKind::Create))
            .then(|| verb.writes.first().copied())
            .flatten();
        if verb.irreversible {
            decl.tags.push(tilo_actions::IRREVERSIBLE_TAG.to_owned());
        }
        if verb.housekeeping {
            decl.tags.push(tilo_actions::HOUSEKEEPING_TAG.to_owned());
        }
        if verb.incoming_message {
            decl.tags
                .push(tilo_actions::INCOMING_MESSAGE_TAG.to_owned());
        }
        if let Some(tag) = verb.audience.tag() {
            decl.tags.push(tag.to_owned());
        }
        if verb.undo == VerbUndo::Compensation {
            decl.tags
                .push(tilo_actions::COMPENSATED_UNDO_TAG.to_owned());
        }
        match verb.answer {
            VerbAnswer::Created => {}
            VerbAnswer::Made => {
                decl.result = Some(tilo_actions::ResultSpec::Json {
                    schema: serde_json::json!({"type": "object"}),
                });
            }
            // One result, or a list for several entries; nothing while the
            // work is still queued.
            VerbAnswer::Queued => {
                decl.result = Some(tilo_actions::ResultSpec::Json {
                    schema: serde_json::json!({"type": ["object", "array", "null"]}),
                });
            }
        }
        if let Some(prompt) = verb.collects {
            decl.content = Some(prompt.to_owned());
        }
        decl
    }

    /// Where a declared parameter names a place in the record.
    #[derive(Clone, Copy)]
    pub enum PlaceIn {
        /// It is no place.
        Nowhere,
        /// Anywhere in the record.
        Record,
        /// Among the items of this field.
        Field(&'static str),
    }

    /// A verb's declared parameter, built by one function for every verb:
    /// its schema is its type's, described, with the example when given. Its
    /// name and description are a verb's own words and, at an effect, its
    /// field's spelling and catalogue word, which is why it takes them the
    /// way the constructors beside it do.
    #[must_use]
    pub fn declared_param(
        name: impl Into<String>,
        ty: ParamType,
        description: impl Into<String>,
        schema: fn() -> serde_json::Value,
        optional: bool,
        place: PlaceIn,
        example: Option<fn() -> serde_json::Value>,
    ) -> ActionParam {
        let name = name.into();
        let description = description.into();
        let param = if optional {
            ActionParam::optional_owned(name, ty, description)
        } else {
            ActionParam::required_owned(name, ty, description)
        }
        // The parameter carries its description; its schema does not say
        // it again.
        .with_schema(param_schema(schema(), "", example.map(|example| example())));
        match place {
            PlaceIn::Nowhere => param,
            PlaceIn::Record => param.as_place(),
            PlaceIn::Field(field) => param.as_place_in(field),
        }
    }

    /// A parameter's schema: its type's, described, with an example.
    #[must_use]
    pub fn param_schema(
        schema: serde_json::Value,
        description: &str,
        example: Option<serde_json::Value>,
    ) -> serde_json::Value {
        let mut schema = crate::schema::describe(schema, description);
        if let (Some(example), serde_json::Value::Object(fields)) = (example, &mut schema) {
            fields.insert("examples".into(), serde_json::Value::Array(vec![example]));
        }
        schema
    }

    /// `Some(T::default())` when `T` is `Default`, else `None`, decided
    /// where `T` is concrete: `(&DefaultOf::<T>::new()).default_value()`
    /// with [`HasDefault`] and [`NoDefault`] in scope. A skipped field reads
    /// as its containing type's default this way.
    pub struct DefaultOf<T>(::core::marker::PhantomData<T>);

    impl<T> DefaultOf<T> {
        #[must_use]
        pub const fn new() -> Self {
            Self(::core::marker::PhantomData)
        }
    }

    impl<T> Default for DefaultOf<T> {
        fn default() -> Self {
            Self::new()
        }
    }

    /// See [`DefaultOf`].
    pub trait HasDefault<T> {
        fn default_value(&self) -> Option<T>;
    }

    impl<T: Default> HasDefault<T> for DefaultOf<T> {
        fn default_value(&self) -> Option<T> {
            Some(T::default())
        }
    }

    /// See [`DefaultOf`].
    pub trait NoDefault<T> {
        fn default_value(&self) -> Option<T>;
    }

    impl<T> NoDefault<T> for &DefaultOf<T> {
        fn default_value(&self) -> Option<T> {
            None
        }
    }

    /// A number a field's `#[model(range = ..)]` bounds: its value, `None`
    /// for an absent optional one.
    pub trait DeclaredNumber {
        fn declared_number(&self) -> Option<f64>;
    }

    macro_rules! declared_number {
        ($($ty:ty),*) => {$(
            impl DeclaredNumber for $ty {
                #[allow(clippy::cast_precision_loss, clippy::cast_lossless, reason = "a range bound is a numeric limit far below 2^53")]
                fn declared_number(&self) -> Option<f64> {
                    Some(*self as f64)
                }
            }
        )*};
    }
    declared_number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);

    impl<T: DeclaredNumber> DeclaredNumber for Option<T> {
        fn declared_number(&self) -> Option<f64> {
            self.as_ref().and_then(DeclaredNumber::declared_number)
        }
    }

    /// A text a field's `#[model(choices = ..)]` names: its value, `None` for
    /// an absent optional one.
    pub trait DeclaredChoice {
        fn declared_choice(&self) -> Option<&str>;
    }

    impl DeclaredChoice for String {
        fn declared_choice(&self) -> Option<&str> {
            Some(self)
        }
    }

    impl<T: DeclaredChoice> DeclaredChoice for Option<T> {
        fn declared_choice(&self) -> Option<&str> {
            self.as_ref().and_then(DeclaredChoice::declared_choice)
        }
    }

    /// A declared range's bound, as the number it is.
    #[must_use]
    pub fn declared_bound(bound: &impl DeclaredNumber) -> f64 {
        bound.declared_number().unwrap_or(f64::NAN)
    }

    /// Refused unless `value` lies within `low..=high`; `key` names the
    /// field as a field edit's path does.
    pub fn declared_range(
        value: &impl DeclaredNumber,
        low: f64,
        high: f64,
        key: &str,
    ) -> Result<(), crate::Refusal> {
        match value.declared_number() {
            Some(number) if !(number.is_finite() && (low..=high).contains(&number)) => Err(
                crate::Refusal::new(format!("`{key}` is between {low} and {high}")),
            ),
            _ => Ok(()),
        }
    }

    /// Refused unless `value` is one of `choices`.
    pub fn declared_choices(
        value: &impl DeclaredChoice,
        choices: &[&str],
        key: &str,
    ) -> Result<(), crate::Refusal> {
        match value.declared_choice() {
            Some(chosen) if !choices.contains(&chosen) => Err(crate::Refusal::new(format!(
                "`{key}` is one of {}",
                choices.join(", ")
            ))),
            _ => Ok(()),
        }
    }

    /// Run `change` on the item of type `T` at `path` of the record `R`,
    /// reading only that item, then write what changed where the item is
    /// kept, checked, or remove the item where `change` asked to
    /// ([`ActionCx::remove_item`](crate::ActionCx::remove_item)): an item
    /// method applied. `None` where nothing is at `path`: the caller decides
    /// on the whole resource then, where an item named by its label is
    /// found, or one that is not there is refused with the items there are.
    ///
    /// # Errors
    /// The item does not read as `T`, the method refused, or an edit did not
    /// apply.
    pub fn apply_item<R, T>(
        doc: &mut crate::Doc,
        cx: &mut crate::ActionCx,
        path: &[crate::Segment],
        change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
    ) -> Option<Result<(), crate::Refusal>>
    where
        R: crate::Fields,
        T: crate::Model,
    {
        let obj = crate::Path::<R, T>::from_segments(path.to_vec()).object(doc)?;
        Some(apply_item_at::<R, T>(doc, cx, path, &obj, change))
    }

    fn apply_item_at<R, T>(
        doc: &mut crate::Doc,
        cx: &mut crate::ActionCx,
        path: &[crate::Segment],
        obj: &automerge::ObjId,
        change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
    ) -> Result<(), crate::Refusal>
    where
        R: crate::Fields,
        T: crate::Model,
    {
        let refused = |error: crate::ModelError| crate::Refusal::new(error.to_string());
        let map = automerge::Value::Object(automerge::ObjType::Map);
        let before = T::load(doc, &map, obj).map_err(refused)?;
        let mut after = T::load(doc, &map, obj).map_err(refused)?;
        let _ = cx.take_item_removal();
        change(&mut after, cx)?;
        if cx.take_item_removal() {
            let (Some(crate::Segment::Item(id)), Some(collection)) = (
                path.last(),
                path.len().checked_sub(1).and_then(|at| path.get(..at)),
            ) else {
                return Err(crate::Refusal::new(
                    "only an item of a collection is removed",
                ));
            };
            let op = crate::EditOp::RemoveItem { id: id.clone() };
            return R::edit_fields(doc, &ROOT, collection, &op, cx).map_err(refused);
        }
        crate::Model::check(&after)?;
        if after.stores_as(&before) {
            return Ok(());
        }
        // Written where it is kept, as the resource's own write writes it:
        // only what changed, its read-only fields too (a verb sets those,
        // a field edit from outside never does).
        let Some(automerge::Parent {
            obj: parent,
            prop: automerge::Prop::Map(key),
            ..
        }) = doc.parents(obj).ok().and_then(|mut parents| parents.next())
        else {
            return Err(crate::Refusal::new("the item is not kept under a key"));
        };
        after
            .store(doc, crate::Slot::Key(&parent, &key))
            .map_err(refused)
    }

    /// The first non-empty line of the text `value` carries: one part of a
    /// label.
    pub fn first_line<T: crate::Model>(value: &T) -> Option<String> {
        let mut text = Vec::new();
        value.collect_text(&mut text);
        first_line_of(text)
    }

    pub use tilo_actions::params::param_type_of;

    /// The parameters a `#[param(flatten)]` struct's schema lists: each
    /// property by name, typed and described by its own schema, required as
    /// the schema says.
    #[must_use]
    pub fn flat_params(schema: &serde_json::Value) -> Vec<ActionParam> {
        let required: Vec<&str> = schema
            .get("required")
            .and_then(serde_json::Value::as_array)
            .map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
            .unwrap_or_default();
        let Some(properties) = schema
            .get("properties")
            .and_then(serde_json::Value::as_object)
        else {
            return Vec::new();
        };
        properties
            .iter()
            .map(|(name, property)| {
                let description = property
                    .get("description")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or(name)
                    .to_owned();
                let ty = param_type_of(property);
                let param = if required.contains(&name.as_str()) {
                    ActionParam::required_owned(name.clone(), ty, description)
                } else {
                    ActionParam::optional_owned(name.clone(), ty, description)
                };
                // The parameter carries the description; its schema does not
                // say it again.
                let mut schema = property.clone();
                if let Some(schema) = schema.as_object_mut() {
                    schema.remove("description");
                }
                param.with_schema(schema)
            })
            .collect()
    }

    /// `value` in its JSON form, written as bytes and read back: the
    /// byte serializer every recorded action already has serves, rather
    /// than one more per type for `serde_json::to_value`.
    ///
    /// # Errors
    /// Why `value` does not serialize.
    #[inline(never)]
    pub fn json_via_bytes<T: serde::Serialize + ?Sized>(
        value: &T,
    ) -> Result<serde_json::Value, serde_json::Error> {
        let bytes = serde_json::to_vec(value)?;
        value_of_bytes(&bytes)
    }

    /// The JSON value in `bytes`, parsed by code compiled once: a model
    /// type's reader that parses its stored text calls this and then reads
    /// itself out of the value, rather than compiling `serde_json`'s whole
    /// text parser again for every app it is instantiated in.
    #[inline(never)]
    pub(crate) fn value_of_bytes(bytes: &[u8]) -> Result<serde_json::Value, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// The action `id` with `arguments`, stamped `now_ms`, decoded as a
    /// recorded action is (`{"op": {"action", "args"}, "at"}` from bytes):
    /// one decoder per resource serves building and replaying.
    pub fn build_stamped<O: serde::de::DeserializeOwned>(
        id: &str,
        arguments: &serde_json::Map<String, serde_json::Value>,
        now_ms: i64,
    ) -> Result<crate::Stamped<O>, String> {
        let operation = serde_json::json!({ "action": id, "args": arguments });
        O::deserialize(operation)
            .map(|operation| crate::Stamped { operation, now_ms })
            .map_err(|error| error.to_string())
    }

    pub use crate::resource::{default_search, kept_of, listed_of};

    /// The arguments of a verb's JSON form: an object (`null` for none).
    ///
    /// # Errors
    /// Why `value` is no arguments object.
    #[inline(never)]
    pub fn args_object(
        value: serde_json::Value,
    ) -> Result<serde_json::Map<String, serde_json::Value>, serde_json::Error> {
        use serde::de::Error as _;
        match value {
            serde_json::Value::Object(args) => Ok(args),
            serde_json::Value::Null => Ok(serde_json::Map::new()),
            other => Err(serde_json::Error::invalid_type(
                serde::de::Unexpected::Other(&other.to_string()),
                &"the arguments as an object",
            )),
        }
    }

    /// The argument `name` taken from `args`, decoded as a `T`; an absent
    /// one is `None` when `optional`, else missing.
    ///
    /// # Errors
    /// Why the argument is missing or not a `T`.
    pub fn arg<T: serde::de::DeserializeOwned>(
        args: &mut serde_json::Map<String, serde_json::Value>,
        name: &'static str,
        optional: bool,
    ) -> Result<T, serde_json::Error> {
        // Only the decode is per type: taking the argument out is compiled
        // once for every parameter of every action.
        T::deserialize(take_arg(args, name, optional)?)
    }

    /// The argument `name` taken from `args`: `null` for an absent optional
    /// one, else missing.
    #[inline(never)]
    fn take_arg(
        args: &mut serde_json::Map<String, serde_json::Value>,
        name: &'static str,
        optional: bool,
    ) -> Result<serde_json::Value, serde_json::Error> {
        use serde::de::Error as _;
        match args.remove(name) {
            Some(value) => Ok(value),
            None if optional => Ok(serde_json::Value::Null),
            None => Err(serde_json::Error::missing_field(name)),
        }
    }

    /// The action name and arguments of an action's JSON form
    /// (`{"action": .., "args": ..}`, the arguments `null` when absent).
    ///
    /// # Errors
    /// Why `value` is not an action.
    #[inline(never)]
    pub fn tagged(
        value: serde_json::Value,
    ) -> Result<(String, serde_json::Value), serde_json::Error> {
        use serde::de::Error as _;
        let serde_json::Value::Object(mut fields) = value else {
            return Err(serde_json::Error::custom("an action is an object"));
        };
        let Some(serde_json::Value::String(action)) = fields.remove("action") else {
            return Err(serde_json::Error::missing_field("action"));
        };
        Ok((
            action,
            fields.remove("args").unwrap_or(serde_json::Value::Null),
        ))
    }

    /// The JSON form's schema of a record of `shape`: each field's under its
    /// key, read from the shape so it is built by one function for every
    /// record type.
    #[must_use]
    pub fn resource_value_schema(shape: crate::Shape) -> serde_json::Value {
        let properties: serde_json::Map<String, serde_json::Value> = shape
            .fields()
            .iter()
            .map(|field| (field.key.to_owned(), (field.schema)()))
            .collect();
        serde_json::json!({"type": "object", "properties": properties})
    }

    /// The first non-empty line among `text`.
    #[inline(never)]
    pub(crate) fn first_line_of(text: Vec<String>) -> Option<String> {
        text.into_iter()
            .map(|line| line.lines().next().unwrap_or_default().trim().to_owned())
            .find(|line| !line.is_empty())
    }

    /// A `#[model(check)]` function's result as a refusal.
    pub fn check_outcome<O: crate::Outcome>(outcome: O) -> Result<(), crate::Refusal> {
        outcome.into_result()
    }
}

pub use tilo_actions::profiling;