tilo-actions 0.5.2

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store.
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
//! # Tilo ACTION model
//!
//! The state layer behind Ctrl+K and cross-peer collaboration: a
//! serializable, **replayable** unit of CRDT mutation.
//!
//! ## Play locally, replay anywhere
//!
//! An [`Action`] is a *value* that deterministically mutates a CRDT
//! [`Doc`]. Applied to the local replica, its
//! [`ActionEnvelope`] is replicated; a peer starting from the same state
//! [`replay`]s it and lands on the **identical**
//! document — the [executor] pins the Automerge actor id (from
//! the action's [`ActionId`]) and commit timestamp on every apply, so
//! the resulting change is content-addressed identical everywhere.
//!
//! Replayable [`Action`] values are strictly **not presentation** and mutate
//! only shared CRDT state. The wider resource/action protocol also describes
//! client-local [`OperationKind::View`] and external
//! [`OperationKind::Effect`] operations. Those use the same typed descriptors,
//! permission checks and invocation receipts, but are dispatched through the
//! toolkit's operation handler instead of being replayed as document history.
//!
//! ## Resources
//!
//! An app publishes the tree of [`ResourceSpec`]s it currently has open (a
//! video → its comments; a book → its annotations) through the toolkit's
//! `PublishesResources`. Each resource exports [`ActionSpec`]s; the
//! palette lists them, and choosing one
//! [`dispatch`]es the underlying action.
//!
//! ## The action API
//!
//! A resource tree is only useful to the app that built it until someone
//! else can reach it. [`api`] is that reach: [`api::survey`] turns a
//! live tree into inert, stably-addressed descriptors, and
//! [`api::invoke`] performs one attributed to the caller — so another
//! session acts on an app without the app growing a remote-control
//! surface of its own.
//!
//! ## Remote use
//!
//! [`remote`] carries the action API across machines: a versioned, transport-neutral
//! vocabulary for listing, invoking, observing and cancelling another peer's
//! actions, and the [`remote::ActionProvider`] trait a peer implements to answer
//! it. The caller is always the actor the transport authenticated, and
//! invocations are idempotent per [`InvocationId`].
//!
//! ## Execution locus
//!
//! Each action declares an [`ExecutionLocus`]: `ClientLocal` (this
//! client applies + replicates; peers replay) or `ServerPreferred`
//! (route to an authoritative host). [`dispatch`] honours
//! it against an [`ActionTransport`] and refuses
//! the operation when no host answers.
//!
//! ## Sharing this vocabulary with the compositor
//!
//! [`params`] is the *same* vocabulary the compositor's headless
//! action API speaks — [`ParamType`], [`ActionParam`], [`ArgValue`], and the
//! strict [`ActionArgs::bind`] — lifted into one definition rather than left to
//! converge by accident. The wire spellings of `text` / `integer` / `boolean`
//! and the bind semantics (unknown argument refused, first failure wins,
//! nothing partial reaches an action) are unchanged from that surface, and the
//! `const` constructors keep a `const PARAMS: &[ActionParam] = &[…]` compiling
//! as written.
//!
//! Two additive extensions: [`ParamType::Number`], because the
//! app-side arguments this replaces are overwhelmingly fractional and rounding
//! them would discard the values they exist to carry; and
//! [`ActionParam::choices`], which turns a prose list into something a caller
//! can read and binding can enforce. The string fields are
//! [`Cow<'static, str>`](std::borrow::Cow) rather than `&'static str` because an
//! app builds its parameters per frame out of live document state — a `const`
//! declaration is `Cow::Borrowed` and costs nothing.
//!
//! ## Plain vocabulary
//!
//! The parts of Tilo's resource vocabulary that need no store, document or
//! CRDT live here too: the smallest splice between two texts ([`splice_between`]),
//! the scope a search looks within ([`ScopeDecl`]), the kind an item's address
//! names ([`item_kind`]), the name a workspace emoji is written by
//! ([`custom_emoji_name`]), the catalogue key a kind is named under
//! ([`message_key`]), the id of a history entry ([`HistoryEntryId`]), the named
//! scopes the app framework is profiled by ([`profiling`]).
//! `tilo-resource` publishes them where they have always been; the toolkit reads
//! them here, with or without that model.

#![cfg_attr(
    test,
    allow(
        clippy::string_slice,
        clippy::unreachable,
        reason = "in a test these are the assertion, not a hazard"
    )
)]

/// Serde for a JSON-only type whose reading goes through one
/// `serde_json::Value`.
///
/// The type derives with `#[serde(remote = "Self")]`, which makes its
/// derived code inherent functions. Writing runs them as derived. Reading
/// runs them once, against a `Value`, in the crate that declares the type:
/// every format and every crate that reads the type then shares that one
/// copy instead of compiling the type's whole deserializer (and, for an
/// internally tagged enum, its buffered copy) again for each deserializer it
/// meets. Only for types every encoding of which is JSON: a `Value` needs a
/// self-describing format. `custom` leaves `from_json_value` to the type.
/// `write` also writes through one `Value`, built by a function compiled in
/// the declaring crate, so a crate that writes the type compiles none of its
/// serializer either; the JSON is the same.
#[macro_export]
macro_rules! read_through_json_value {
    ($ty:ty) => {
        $crate::read_through_json_value!($ty, custom);

        impl $ty {
            #[inline(never)]
            fn from_json_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
                Self::deserialize(value)
            }
        }
    };
    ($ty:ty, custom) => {
        impl serde::Serialize for $ty {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                Self::serialize(self, serializer)
            }
        }

        $crate::read_through_json_value!($ty, read);
    };
    ($ty:ty, write) => {
        impl serde::Serialize for $ty {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                match self.to_json_value() {
                    Ok(value) => serde::Serialize::serialize(&value, serializer),
                    Err(error) => Err(serde::ser::Error::custom(error)),
                }
            }
        }

        $crate::read_through_json_value!($ty, read);

        impl $ty {
            #[inline(never)]
            fn from_json_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
                Self::deserialize(value)
            }

            #[inline(never)]
            fn to_json_value(&self) -> Result<serde_json::Value, serde_json::Error> {
                Self::serialize(self, serde_json::value::Serializer)
            }
        }
    };
    ($ty:ty, read) => {
        impl<'de> serde::Deserialize<'de> for $ty {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
                Self::from_json_value(value).map_err(serde::de::Error::custom)
            }
        }
    };
}

/// Serde for a type kept as JSON and in a binary format: in a human-readable
/// format (JSON, a `serde_json::Value`, serde's buffered content) it is read
/// and written through one `Value`, by functions compiled once in the crate
/// that declares it; in any other (postcard) by its derived code, unchanged.
///
/// The type derives with `#[serde(remote = "Self")]`, as for
/// [`read_through_json_value!`]. A crate that reads or writes the type as JSON
/// then compiles only the `Value` step, not the type's whole serializer and
/// deserializer (and, for an internally tagged or flattened type, its buffered
/// copy) once per format it meets. The JSON is the same: a `Value`'s map keeps
/// the order its fields were written in. `read` routes only reading, for a
/// type whose `Serialize` is its own.
#[macro_export]
macro_rules! readable_through_json_value {
    ($ty:ty) => {
        impl serde::Serialize for $ty {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                if !serializer.is_human_readable() {
                    return Self::serialize(self, serializer);
                }
                match self.to_readable_json() {
                    Ok(value) => serde::Serialize::serialize(&value, serializer),
                    Err(error) => Err(serde::ser::Error::custom(error)),
                }
            }
        }

        impl $ty {
            #[inline(never)]
            fn to_readable_json(&self) -> Result<serde_json::Value, serde_json::Error> {
                Self::serialize(self, serde_json::value::Serializer)
            }
        }

        $crate::readable_through_json_value!($ty, read);
    };
    ($ty:ty, read) => {
        impl<'de> serde::Deserialize<'de> for $ty {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                if !deserializer.is_human_readable() {
                    return Self::deserialize(deserializer);
                }
                let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
                Self::from_readable_json(value).map_err(serde::de::Error::custom)
            }
        }

        impl $ty {
            #[inline(never)]
            fn from_readable_json(value: serde_json::Value) -> Result<Self, serde_json::Error> {
                Self::deserialize(value)
            }
        }
    };
}

/// Serde for an enum written as one object whose `$tag` field names the
/// variant, beside the variant's own fields: the form of
/// `#[serde(tag = "...")]`, the same JSON field for field and in order.
///
/// The enum derives with `#[serde(remote = "Self")]` in place of `tag`, so
/// the derive writes a variant as an object's only key, and this moves the
/// name between the two places through one `serde_json::Value`, by code
/// compiled once here. serde reads a `tag` enum by buffering the object in
/// its private `Content` form and gives every struct inside two more readers
/// for that, in every crate that reads the enum; read through a `Value`, each
/// struct keeps the one reader a `Value` has. A unit variant reads from its
/// name alone, any other fields beside it ignored, as with `tag`. `read`
/// routes only reading, for an enum that derives only `Deserialize`.
#[macro_export]
macro_rules! tagged_through_json_value {
    ($ty:ty, $tag:literal) => {
        $crate::tagged_through_json_value!($ty, $tag, read);

        impl serde::Serialize for $ty {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                let named = Self::serialize(self, serde_json::value::Serializer)
                    .map_err(serde::ser::Error::custom)?;
                let tagged = $crate::tagged_json::tag_inside(named, $tag)
                    .map_err(serde::ser::Error::custom)?;
                serde::Serialize::serialize(&tagged, serializer)
            }
        }
    };
    ($ty:ty, $tag:literal, read) => {
        impl<'de> serde::Deserialize<'de> for $ty {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let object = <serde_json::Map<String, serde_json::Value> as serde::Deserialize>::deserialize(
                    deserializer,
                )?;
                let (named, unit) = $crate::tagged_json::tag_outside(object, $tag)
                    .map_err(serde::de::Error::custom)?;
                Self::deserialize(named)
                    .or_else(|error| Self::deserialize(unit).map_err(|_| error))
                    .map_err(serde::de::Error::custom)
            }
        }
    };
}

/// The two halves of [`tagged_through_json_value!`], compiled once.
#[doc(hidden)]
pub mod tagged_json {
    use serde_json::{Map, Value};

    /// `{"variant": {fields}}`, or a unit variant's `"variant"`, as
    /// `{"<tag>": "variant", fields}`.
    #[inline(never)]
    pub fn tag_inside(named: Value, tag: &str) -> Result<Value, String> {
        let (variant, fields) = match named {
            Value::String(variant) => (variant, Map::new()),
            Value::Object(named) if named.len() == 1 => match named.into_iter().next() {
                Some((variant, Value::Object(fields))) => (variant, fields),
                Some((variant, _)) => {
                    return Err(format!(
                        "the variant `{variant}` holds no fields, so it has no place for `{tag}`"
                    ));
                }
                None => return Err("an empty object is not a variant".to_owned()),
            },
            other => return Err(format!("{other} is not a variant")),
        };
        let mut object = Map::with_capacity(fields.len().saturating_add(1));
        object.insert(tag.to_owned(), Value::String(variant));
        object.extend(fields);
        Ok(Value::Object(object))
    }

    /// `{"<tag>": "variant", fields}` as `{"variant": {fields}}`, and as the
    /// unit variant `"variant"` to read when that is what it names.
    #[inline(never)]
    pub fn tag_outside(
        mut object: Map<String, Value>,
        tag: &str,
    ) -> Result<(Value, Value), String> {
        let variant = match object.remove(tag) {
            Some(Value::String(variant)) => variant,
            Some(other) => return Err(format!("`{tag}` is {other}, not a variant name")),
            None => return Err(format!("missing field `{tag}`")),
        };
        let unit = Value::String(variant.clone());
        let mut named = Map::with_capacity(1);
        named.insert(variant, Value::Object(object));
        Ok((Value::Object(named), unit))
    }
}

pub mod action;
pub mod agent_disclosure;
pub mod api;
pub mod appearance;
#[cfg(feature = "asks")]
pub mod asks;
pub mod compact;
pub mod content;
pub mod context;
pub mod contract;
pub mod document_sync;
pub mod draft;
mod emoji;
pub mod entry;
pub mod envelope;
pub mod executor;
pub mod field_type;
pub mod framework;
pub mod group_form;
mod history;
pub mod interaction;
mod item;
pub mod key;
mod label;
pub mod noun;
pub mod offload;
pub mod opened_by;
pub mod outcome;
pub mod outside_document;
pub mod params;
pub mod prefill;
pub mod profiling;
pub mod protocol;
pub mod published;
pub mod reaction;
pub mod receipt;
mod refusal;
pub mod registry;
pub mod remote;
pub mod resource;
pub mod row_status;
pub mod run;
pub mod schema;
mod scope;
pub mod selection;
pub mod selectors;
pub mod send_to;
pub mod stamp;
pub mod step;
pub mod surface;
pub mod task_step;
pub mod terminal_text;
mod text;
pub mod tree;

pub use action::{
    Action, ActionError, ActionId, ActionStep, Declined, Doc, EncodedAction, ExecutionLocus,
    MAX_TEXT_BYTES, OperationKind, RECALL_SUMMARY_BYTES, asks_first, codes, undo_takes_back,
};
pub use agent_disclosure::hidden_from_agents;
pub use api::{
    ActionAddress, ActionDescriptor, ActionEffect, ApiError, InputSpec, NOT_THE_ASKED_PERSON,
    ResourceViewDescriptor,
};
pub use appearance::{Appearance, AppearanceError, Persona};
pub use content::{
    CONTENT_PART_THRESHOLD, CONTENT_REFERENCE_KEY, ContentParts, MissingContent, current, register,
};
pub use context::{
    ActionApp, ActionContext, ActionFacet, ActionInvoker, ActionResource, CHANGE_MESSAGE_PREFIX,
    CONTINUATION_PREFIX, Cause, ChangeKind, InvokerDevice, MAX_PRESENCE_ID_BYTES, PLACE_FACET,
    PresenceId, RISK_FACET, WorkGroup,
};
pub use contract::{
    AGENTS_AUDIENCE_TAG, ARGUMENT_RISK_TAG, ATTENDED_TAG, ActionContract, ActionKind, ActionNeed,
    Audience, Availability, CARRIER_TAG, COMPENSATED_UNDO_TAG, ConfirmationPolicy,
    DOCUMENT_READ_TAG, ExecutionMode, HOST_RENDER_TAG, HOST_UNSUPPORTED_CODE, HOUSEKEEPING_TAG,
    INCOMING_MESSAGE_FACET, INCOMING_MESSAGE_TAG, IRREVERSIBLE_TAG, MAX_OFFLOAD_CPU_TIME_MS,
    MAX_OFFLOAD_MEMORY_BYTES, MAX_OFFLOAD_OUTPUT_BYTES, MEMBER_OWN_TAG, MIN_OFFLOAD_MEMORY_BYTES,
    OPENS_HIT_TAG, OPENS_PATH_EXTENSION_PREFIX, OPENS_PATH_TAG, ORIGIN_FACET,
    OUTSIDE_CAPABILITY_PREFIX, OWN_DEVICE_SCOPE, Offload, PEOPLE_AUDIENCE_TAG, READERS_FACET,
    REQUIRES_HOST_PREFIX, REQUIRES_NATIVE_PATHS_TAG, RESOURCE_READ_TAG, ROOT_ONLY_TAG,
    ROUTED_CHANGE_TAG, ResultSpec, RetryPolicy, RiskLevel, SCREEN_PLACE_TAG, SCREEN_TAG,
    SEARCH_KIND_PREFIX, SEARCH_TAG, SECRET_ANSWER_TAG, UNTRUSTED_CONTENT_TAG, action_node,
    phrase_is_meaningful, resource_node,
};
pub use draft::{Draft, DraftEdit, DraftField, DraftLayout, DraftValue, MessageRole};
pub use emoji::{MAX_CUSTOM_NAME, custom_emoji_name, valid_custom_emoji_name};
pub use entry::{
    ActionItem, Described, Did, EditOp, FieldEdit, GroupOf, HistoryOp, HistoryStep, PathStep,
    Scalar, VerbCall,
};
pub use envelope::ActionEnvelope;
pub use executor::{
    ActionTransport, CompensatingScope, Dispatched, EntryReader, HostDecision, LocalTransport,
    UNDONE_KEY, Verified, apply_local, apply_local_by, apply_local_with_context,
    await_compensation, await_settlement, commit_written, current_step, dispatch, dispatch_by,
    dispatch_by_with_context, dispatch_with_context, entry_message, entry_of, envelope_at,
    invoking_context, open_step, reading_invoking_context, replay, replay_decoded, replaying_as,
    settle_compensation, verify_change, with_invoking_context,
};
pub use framework::FrameworkChange;
pub use history::{HistoryEntryId, change_hex, entry_hex, entry_id};
pub use interaction::{
    INTERACTION_VERSION, InteractionAction, InteractionAnchor, InteractionGridRange,
    InteractionPhase, InteractionTextRange, InteractionUpdate, InteractionViolation,
    MAX_ANCHOR_ITEMS, MAX_DETAIL_BYTES, MAX_ID_BYTES, MAX_INTERACTION_BYTES, MAX_LABEL_BYTES,
    SemanticInteraction,
};
pub use item::item_kind;
pub use key::{ActionKey, CREATE_ACTION};
pub use label::{message_key, noun_key};
pub use outcome::{
    ActionFailure, ActionOutput, CONTENT_RESOURCE_KIND, EffectReceiptStatus, InvocationId,
    InvocationUpdate, content_hash, content_resource, named_reference,
};
pub use params::{
    ARGUMENTS_JSON_PREFIX, ActionArgs, ActionParam, ArgError, ArgValue, ArgViolation,
    CHOICE_LABELS_ANNOTATION, CONTENT_ANNOTATION, PEOPLE_ANNOTATION, PICK_ANNOTATION,
    PLACE_ANNOTATION, ParamType, Pick, RESOURCE_KINDS_ANNOTATION, SHAPED_BY_ANNOTATION,
    picked_address_schema, picked_resource_schema, place_schema, resource_reference_schema,
    shaped_by_schema, validate_json_schema,
};
pub use protocol::{ContractViolation, validate_surface, validate_surface_contracts};
pub use refusal::Refusal;
pub use registry::{ActionRegistry, DecodePayload, decode_json, decode_payload};
pub use resource::{
    ActionBinding, ActionBindingError, ActionInput, ActionSpec, ActionState, ActionType,
    ArgsBuilder, Collects, ContinuationArguments, ContinuationEvidence, ContinuationKey,
    ContinuationQuery, ControlInvocation, Exports, FlatAction, KEY_SEP, ListedRow,
    NESTED_RESOURCE_FACET, Noun, PROMPTED_PARAM, ReadingRow, ResourceId, ResourcePresentation,
    ResourceSemanticIdentity, ResourceSpec, ResourceType, ResourceViewMountSpec,
    ResourceViewRangeSpec, ResourceViewSpec, RunBy, SEMANTIC_OPERATION_TYPE, Target, action_label,
    app_label, flatten, in_words, kind_is_a_drawn_control, kind_mirrors_a_control,
    listed_for_people, listed_row, listed_row_problems, plural, singular, sole_text_argument,
};
pub use row_status::{RowStatus, apply_row_statuses};
pub use schema::{
    CatalogueSchemaEntry, ContextRequirement, PRESENCE_VIEW_TAG, REQUIRES_TAG_PREFIX,
    catalogue_schema, catalogue_schema_bytes,
};
pub use scope::{ScopeDecl, scope_contains};
pub use selection::{
    BOUND_RESOURCE_PREFIX, MAX_EXCERPT_BYTES, MAX_EXCERPT_CHARS, MAX_SELECTED_ITEMS,
    SelectionAnchor, SelectionPlace, SelectionSubject, excerpt_of, logical_resource_id,
};
pub use send_to::{Recipient, RecipientKind, recipients_matching};
pub use step::{Step, StepKind};
pub use text::{Splice, common_ends, common_text_ends, splice_between};
/// Grants and the decisions over them, as apps read and show them.
pub use tilo_action_policy as policy;
/// The field a resource's comments live in: an action that only comments
/// is placed below it ([`ActionContract::field`]), where someone who may only
/// comment is granted changes.
pub use tilo_action_policy::roles::{COMMENTS_FIELD, MODERATION_FIELD};
pub use tilo_action_policy::{Acting, Actor, MemberId, PersonId};

/// The stable address (`kind:id`) of the item an item resource id names: `<kind>.<field>:<item>`
/// for `<kind>/<field>/<item>` — the address an action's resource parameter takes. An app that
/// publishes an item under its stable address resolves a link written in the older item form
/// through this; `None` for an id naming no item of a top-level collection.
#[must_use]
pub fn stable_item_address(resource_id: &str) -> Option<String> {
    let (collection, item) = resource_id.rsplit_once('/')?;
    let (kind, field) = collection.split_once('/')?;
    (!kind.is_empty()
        && !field.is_empty()
        && !field.contains('/')
        && !item.is_empty()
        && !resource_id.contains(':'))
    .then(|| format!("{kind}.{field}:{item}"))
}

/// The item form (`<kind>/<field>/<item>`) of an item's stable address (`<kind>.<field>:<item>`):
/// what an app that publishes its items in the item form publishes the item a stable link names
/// under. `None` for an address that names no item of a collection (`tl:app:root-x`).
#[must_use]
pub fn item_form_of(address: &str) -> Option<String> {
    let (kind_field, item) = address.split_once(':')?;
    let (kind, field) = kind_field.rsplit_once('.')?;
    (!kind.is_empty()
        && !field.is_empty()
        && !item.is_empty()
        && !item.contains(':')
        && !address.contains('/'))
    .then(|| format!("{kind}/{field}/{item}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use automerge::transaction::Transactable;

    /// An item's older form names the same item at its stable address; anything else names none.
    #[test]
    fn an_items_older_form_names_its_stable_address() {
        assert_eq!(
            stable_item_address("chat.workspace/channels/c1").as_deref(),
            Some("chat.workspace.channels:c1")
        );
        assert_eq!(stable_item_address("chat.workspace.channels:c1"), None);
        assert_eq!(stable_item_address("tl:so.tilo.notes:root-x"), None);
        assert_eq!(stable_item_address("notes/pages/p1/blocks/b2"), None);
        assert_eq!(
            item_form_of("chat.workspace.messages:m1").as_deref(),
            Some("chat.workspace/messages/m1"),
            "a stable address names the item an app publishes in the item form"
        );
        assert_eq!(item_form_of("tl:so.tilo.notes:root-x"), None);
    }
    use automerge::{AutoCommit, ROOT, ReadDoc, ScalarValue};
    use serde::{Deserialize, Serialize};
    use tilo_automerge::ApplyIncoming;

    /// A real action: set a scalar under a key, and (for lists) append.
    /// Mutates only via the passed doc, no wall-clock/RNG — the determinism contract.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    enum Counter {
        Put { key: String, value: i64 },
        Append { key: String, value: String },
    }

    const COUNTER_TYPE: &str = "test.counter";

    impl Action for Counter {
        fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
            match self {
                Counter::Put { key, value } => {
                    doc.put(&ROOT, key, ScalarValue::Int(*value))?;
                }
                Counter::Append { key, value } => {
                    let list = match doc.get(&ROOT, key)? {
                        Some((automerge::Value::Object(automerge::ObjType::List), id)) => id,
                        _ => doc.put_object(&ROOT, key, automerge::ObjType::List)?,
                    };
                    let len = doc.length(&list);
                    doc.insert(&list, len, ScalarValue::Str(value.as_str().into()))?;
                }
            }
            Ok(())
        }

        fn locus(&self) -> ExecutionLocus {
            match self {
                // Appends prefer a host so a shared list is serialized.
                Counter::Append { .. } => ExecutionLocus::ServerPreferred,
                Counter::Put { .. } => ExecutionLocus::ClientLocal,
            }
        }
    }

    /// A read marker: shared state about the document, not its content.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct Seen(i64);

    const SEEN_TYPE: &str = "test.seen";

    impl Action for Seen {
        fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
            doc.put(&ROOT, "seen", ScalarValue::Int(self.0))?;
            Ok(())
        }

        fn change_kind(&self) -> ChangeKind {
            ChangeKind::Housekeeping
        }
    }

    fn registry() -> ActionRegistry {
        let mut r = ActionRegistry::new();
        r.register::<Counter>(COUNTER_TYPE);
        r.register::<Seen>(SEEN_TYPE);
        r
    }

    fn decode_seen(payload: &[u8]) -> Result<Box<dyn Action>, serde_json::Error> {
        serde_json::from_slice::<Seen>(payload).map(|seen| Box::new(seen) as Box<dyn Action>)
    }

    fn last_message(doc: &mut AutoCommit) -> Option<String> {
        let heads = doc.get_heads();
        doc.get_change_by_hash(heads.first()?)?
            .message()
            .map(ToString::to_string)
    }

    fn last_context(doc: &mut AutoCommit) -> Option<ActionContext> {
        ActionContext::from_change_message(&last_message(doc)?)
    }

    /// Seed two independent replicas that share history (so a replayed
    /// change has identical deps), each with its OWN actor for normal edits.
    fn two_replicas() -> (AutoCommit, AutoCommit) {
        let mut a = AutoCommit::new();
        a.put(&ROOT, "seed", ScalarValue::Str("s".into())).unwrap();
        a.commit();
        let bytes = a.save();
        let b = AutoCommit::load(&bytes).unwrap();
        (a, b)
    }

    /// THE HEADLINE TEST. An action applied on replica A, replicated, and
    /// replayed on replica B (from the same state) yields the **identical**
    /// document — same head hashes, not merely the same values.
    fn action_replays_to_identical_doc_on_peer() {
        let (mut a, mut b) = two_replicas();
        assert_eq!(
            a.get_heads(),
            b.get_heads(),
            "precondition: same base state"
        );

        let action = Counter::Put {
            key: "score".into(),
            value: 42,
        };
        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();

        let env = apply_local(&mut a, &action, encoded).unwrap();

        replay(&mut b, &env, &registry()).unwrap();

        // Identical *history*, not just identical materialized values.
        assert_eq!(
            a.get_heads(),
            b.get_heads(),
            "replay reproduces the identical change on the peer"
        );
        let av = a.get(&ROOT, "score").unwrap().unwrap().0;
        let bv = b.get(&ROOT, "score").unwrap().unwrap().0;
        assert_eq!(av.as_i64(), Some(42));
        assert_eq!(bv.as_i64(), av.as_i64());
    }

    /// Two peers can author from the same base and receive each other's
    /// envelopes after their own action has already advanced the live doc.
    /// Replay must still reproduce each action at its recorded base and merge
    /// the resulting CRDT change; applying either payload directly to the
    /// newer live state would make document-reading actions order-dependent.
    fn concurrent_envelopes_replay_from_their_recorded_base() {
        let (mut a, mut b) = two_replicas();
        let left = Counter::Put {
            key: "left".into(),
            value: 1,
        };
        let right = Counter::Put {
            key: "right".into(),
            value: 2,
        };

        let left_env = apply_local(
            &mut a,
            &left,
            EncodedAction::encode(COUNTER_TYPE, &left).unwrap(),
        )
        .unwrap();
        let right_env = apply_local(
            &mut b,
            &right,
            EncodedAction::encode(COUNTER_TYPE, &right).unwrap(),
        )
        .unwrap();

        replay(&mut a, &right_env, &registry()).unwrap();
        replay(&mut b, &left_env, &registry()).unwrap();

        assert_eq!(a.get_heads(), b.get_heads());
        for doc in [&a, &b] {
            assert_eq!(doc.get(&ROOT, "left").unwrap().unwrap().0.as_i64(), Some(1));
            assert_eq!(
                doc.get(&ROOT, "right").unwrap().unwrap().0.as_i64(),
                Some(2)
            );
        }
    }

    /// The replayed change is content-addressed *identical* to the origin's,
    /// so if the replicas later exchange native Automerge changes (ordinary
    /// CRDT sync) the duplicate dedupes instead of double-applying — why
    /// pinning actor + time on every apply matters.
    fn replayed_change_dedupes_against_native_automerge_merge() {
        let (mut a, mut b) = two_replicas();
        let action = Counter::Append {
            key: "queue".into(),
            value: "vid1".into(),
        };
        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
        // This test is about deterministic replay, not locus routing; apply it
        // explicitly at the origin and retain the resulting envelope.
        let env = apply_local(&mut a, &action, encoded).unwrap();

        // B replays the envelope -> reproduces the identical change.
        replay(&mut b, &env, &registry()).unwrap();
        assert_eq!(a.get_heads(), b.get_heads(), "replay == origin change");
        let heads_after_replay = b.get_heads();

        // Now B *also* receives A's native Automerge change via ordinary CRDT
        // sync. Since it's the same content-addressed change B already
        // replayed, the merge is a no-op: no second append.
        let a_bytes = a.save();
        let mut a_native = AutoCommit::load(&a_bytes).unwrap();
        b.merge_incoming(&mut a_native).unwrap();
        assert_eq!(
            b.get_heads(),
            heads_after_replay,
            "native merge of the identical change dedupes"
        );
        let (_, list) = b.get(&ROOT, "queue").unwrap().unwrap();
        assert_eq!(b.length(&list), 1, "no double-apply");
    }

    tilo_test_env::scenario! {
        fn dispatch_records_and_replay_reproduces_a_change;

        phase a_registered_decoder_decodes_its_type_and_names_it_when_it_cannot;
        // A type registered with a decoder of its own decodes, and applies, as
        // one registered by type; a payload it cannot decode is a decode error
        // naming the type.
        {
            let mut registry = ActionRegistry::new();
            registry.register_decoder(SEEN_TYPE, decode_seen);
            let action = registry
                .decode(&EncodedAction::encode(SEEN_TYPE, &Seen(7)).unwrap())
                .unwrap();
            let mut doc = AutoCommit::new();
            action.apply(&mut doc).unwrap();
            assert_eq!(
                doc.get(&ROOT, "seen")
                    .unwrap()
                    .map(|(value, _)| value.as_i64()),
                Some(Some(7))
            );
            let refused = registry.decode(&EncodedAction {
                type_id: SEEN_TYPE.to_owned(),
                payload: b"not a number".to_vec(),
            });
            assert!(
                matches!(&refused, Err(ActionError::Decode { type_id, .. }) if type_id == SEEN_TYPE),
                "{refused:?}"
            );
        }

        phase declared_kinds_travel_in_the_change_and_every_change_names_what_it_did;
        // The executor writes an action's declared kind into its change, with or
        // without a caller's context, and replay reproduces the same change.
        {
            let (mut a, mut b) = two_replicas();
            let env = apply_local(
                &mut a,
                &Seen(3),
                EncodedAction::encode(SEEN_TYPE, &Seen(3)).unwrap(),
            )
            .unwrap();
            assert!(
                env.context
                    .as_ref()
                    .is_some_and(ActionContext::is_housekeeping)
            );
            assert!(last_context(&mut a).is_some_and(|context| context.is_housekeeping()));
            replay(&mut b, &env, &registry()).unwrap();
            assert_eq!(a.get_heads(), b.get_heads(), "replay makes the same change");

            let labelled = ActionContext::for_resource("c:1", "chat.channel", "general");
            apply_local_with_context(
                &mut a,
                &Seen(4),
                EncodedAction::encode(SEEN_TYPE, &Seen(4)).unwrap(),
                None,
                labelled,
            )
            .unwrap();
            let context = last_context(&mut a).unwrap();
            assert!(context.is_housekeeping());
            assert_eq!(
                context.resource.as_ref().map(|r| r.label.as_str()),
                Some("general"),
                "the caller's context is kept"
            );

            let put = Counter::Put {
                key: "score".into(),
                value: 1,
            };
            let env = apply_local(
                &mut a,
                &put,
                EncodedAction::encode(COUNTER_TYPE, &put).unwrap(),
            )
            .unwrap();
            let entry = env
                .context
                .expect("every committed action records an entry");
            assert!(entry.change.is_step());
            assert_eq!(
                entry.what,
                Some(Did::verb(
                    ActionKey::new("test", COUNTER_TYPE, "put"),
                    [
                        ("key".to_string(), Scalar::from("score")),
                        ("value".to_string(), Scalar::from(1)),
                    ],
                )),
                "an action that describes nothing is named by its encoded verb"
            );
            assert_eq!(last_context(&mut a), Some(entry));

            // A context may say a content action is nobody's step this time; an
            // action's own declaration is never overridden by a context.
            let seeded = Counter::Put {
                key: "score".into(),
                value: 2,
            };
            let env = apply_local_with_context(
                &mut a,
                &seeded,
                EncodedAction::encode(COUNTER_TYPE, &seeded).unwrap(),
                None,
                ActionContext::default().with_change(ChangeKind::External),
            )
            .unwrap();
            assert_eq!(last_context(&mut a).unwrap().change, ChangeKind::External);
            assert!(!env.context.unwrap().change.is_step());
            apply_local_with_context(
                &mut a,
                &Seen(5),
                EncodedAction::encode(SEEN_TYPE, &Seen(5)).unwrap(),
                None,
                ActionContext::default().with_change(ChangeKind::External),
            )
            .unwrap();
            assert!(last_context(&mut a).unwrap().is_housekeeping());
        }

        phase the_executor_keeps_the_admitted_invocation_and_replays_the_identical_change;
        {
            let (mut origin, mut peer) = two_replicas();
            let action = Counter::Put {
                key: "score".into(),
                value: 42,
            };
            let invocation = InvocationId::new();
            let context = ActionContext {
                source_invocation: Some(invocation),
                ..Default::default()
            };
            let envelope = apply_local_with_context(
                &mut origin,
                &action,
                EncodedAction::encode(COUNTER_TYPE, &action).unwrap(),
                Some(b"actual-person-device-writer"),
                context,
            )
            .unwrap();
            let committed = last_context(&mut origin).unwrap();
            assert_eq!(committed.source_invocation, Some(invocation));
            assert_eq!(envelope.context, Some(committed));
            replay(&mut peer, &envelope, &registry()).unwrap();
            assert_eq!(origin.get_heads(), peer.get_heads());
            assert_eq!(
                origin.get_changes(&envelope.base_change_hashes())[0].raw_bytes(),
                peer.get_changes(&envelope.base_change_hashes())[0].raw_bytes(),
            );
        }

        phase a_callers_entry_replays_to_the_identical_change;
        {
            let (mut origin, mut peer) = two_replicas();
            let action = Counter::Put {
                key: "score".into(),
                value: 42,
            };
            let context = ActionContext::for_resource("score", "counter", "Score");
            let envelope = ActionEnvelope {
                id: ActionId::new(),
                action: EncodedAction::encode(COUNTER_TYPE, &action).unwrap(),
                base_heads: origin.get_heads().iter().map(|hash| hash.0).collect(),
                timestamp: 17,
                locus: ExecutionLocus::ClientLocal,
                actor: Some(b"legacy-person-device-writer".to_vec()),
                context: Some(context.clone()),
            };
            let old_message = context.change_message().unwrap();
            let wire = serde_json::to_vec(&envelope).unwrap();
            let decoded: ActionEnvelope = serde_json::from_slice(&wire).unwrap();
            assert_eq!(serde_json::to_vec(&decoded).unwrap(), wire);
            origin.set_actor(envelope.actor());
            action.apply(&mut origin).unwrap();
            origin.commit_with(
                automerge::transaction::CommitOptions::default()
                    .with_time(envelope.timestamp)
                    .with_message(old_message.clone()),
            );
            replay(&mut peer, &decoded, &registry()).unwrap();
            assert_eq!(last_message(&mut peer), Some(old_message));
            assert_eq!(origin.get_heads(), peer.get_heads());
            assert_eq!(
                origin.get_changes(&envelope.base_change_hashes())[0].raw_bytes(),
                peer.get_changes(&envelope.base_change_hashes())[0].raw_bytes(),
            );
        }

        phase envelopes_replay_deterministically_on_peers;
        // An action replays to an identical doc on a peer, concurrent envelopes replay from their
        // recorded base, and a replayed change dedupes against a native Automerge merge.
        // Invocations each phase below in order; every phase builds its own fixture.
        {
            action_replays_to_identical_doc_on_peer();
            concurrent_envelopes_replay_from_their_recorded_base();
            replayed_change_dedupes_against_native_automerge_merge();
        }

        phase dispatch_routes_by_placement_and_the_registry_knows_its_types;
        // Client-local dispatch applies and replicates; server-preferred routes to the host without a
        // local apply and refuses without a host; the registry rejects unknown types and flattens nested
        // resources.
        // Invocations each phase below in order; every phase builds its own fixture.
        {
            client_local_dispatch_applies_and_replicates();
            server_preferred_routes_to_host_without_local_apply();
            server_preferred_refuses_without_host();
            registry_rejects_unknown_type();
            flatten_walks_nested_resources();
        }
    }

    /// `ClientLocal` dispatch applies locally and replicates exactly one
    /// envelope through the transport.
    fn client_local_dispatch_applies_and_replicates() {
        let (mut a, _) = two_replicas();
        let action = Counter::Put {
            key: "likes".into(),
            value: 1,
        };
        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
        let mut tx = LocalTransport::new();
        let d = dispatch(&mut a, &action, encoded, &mut tx).unwrap();
        assert!(matches!(d, Dispatched::AppliedLocal(_)));
        assert!(d.mutated_local());
        assert_eq!(tx.replicated.len(), 1, "replicated exactly once");
        assert_eq!(a.get(&ROOT, "likes").unwrap().unwrap().0.as_i64(), Some(1));
    }

    /// A transport that speaks for a reachable host, proving the
    /// `ServerPreferred` plumbing is real: when a host accepts, the action is
    /// NOT applied to the local doc (the host will execute + broadcast).
    struct HostTransport {
        submitted: Vec<ActionEnvelope>,
    }
    impl ActionTransport for HostTransport {
        fn replicate(&mut self, _env: &ActionEnvelope) {}
        fn submit_to_host(&mut self, env: &ActionEnvelope) -> HostDecision {
            self.submitted.push(env.clone());
            HostDecision::AcceptedByHost
        }
    }

    fn server_preferred_routes_to_host_without_local_apply() {
        let (mut a, _) = two_replicas();
        let before = a.get_heads();
        let action = Counter::Append {
            key: "queue".into(),
            value: "vidX".into(),
        };
        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
        let mut tx = HostTransport { submitted: vec![] };
        let d = dispatch(&mut a, &action, encoded, &mut tx).unwrap();
        assert!(matches!(d, Dispatched::SubmittedToHost(_)));
        assert!(
            !d.mutated_local(),
            "host-accepted action is not applied locally"
        );
        assert_eq!(tx.submitted.len(), 1, "submitted to the host once");
        assert_eq!(a.get_heads(), before, "local doc untouched");
        assert_eq!(d.envelope().locus, ExecutionLocus::ServerPreferred);
    }

    fn server_preferred_refuses_without_host() {
        let (mut a, _) = two_replicas();
        let before = a.get_heads();
        let action = Counter::Append {
            key: "queue".into(),
            value: "vidY".into(),
        };
        let encoded = EncodedAction::encode(COUNTER_TYPE, &action).unwrap();
        let mut tx = LocalTransport::new();
        let error = dispatch(&mut a, &action, encoded, &mut tx).unwrap_err();
        assert!(matches!(error, ActionError::Refused(_)));
        assert_eq!(
            a.get_heads(),
            before,
            "an unavailable host grants no authority"
        );
        assert!(tx.replicated.is_empty());
        assert!(a.get(&ROOT, "queue").unwrap().is_none());
    }

    fn registry_rejects_unknown_type() {
        let reg = registry();
        let bogus = EncodedAction {
            type_id: "nope".into(),
            payload: b"{}".to_vec(),
        };
        let mut doc = AutoCommit::new();
        let env = ActionEnvelope {
            id: ActionId::new(),
            action: bogus,
            base_heads: vec![],
            timestamp: 0,
            locus: ExecutionLocus::ClientLocal,
            actor: None,
            context: None,
        };
        assert!(matches!(
            replay(&mut doc, &env, &reg),
            Err(ActionError::UnknownType(_))
        ));
    }

    /// Resource forests flatten depth-first, parents before children, with
    /// composite keys.
    fn flatten_walks_nested_resources() {
        let put = Counter::Put {
            key: "k".into(),
            value: 1,
        };
        let video = ResourceSpec::new("tube.video:v1", "tube.video", "A Video")
            .with_action(ActionSpec::immediate("like", "Like", COUNTER_TYPE, &put).unwrap())
            .with_child(
                ResourceSpec::new("tube.comment:v1:0", "tube.comment", "nice!").with_action(
                    ActionSpec::immediate("like", "Like comment", COUNTER_TYPE, &put).unwrap(),
                ),
            );
        let flat = flatten(std::slice::from_ref(&video));
        assert_eq!(flat.len(), 2);
        assert_eq!(flat[0].key, format!("tube.video:v1{KEY_SEP}like"));
        assert_eq!(flat[0].resource_kind, "tube.video");
        assert_eq!(flat[1].key, format!("tube.comment:v1:0{KEY_SEP}like"));
        assert_eq!(flat[1].resource_kind, "tube.comment");
    }
}