tilo-actions 0.5.0

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store, search index entries included.
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
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
//! Machine-readable operational semantics for exported actions.
//!
//! Labels explain an action to a person. This module explains it to callers
//! that must plan safely without seeing the application: whether it is
//! currently available, what confirmation it needs, whether a failed call may
//! be retried, how it completes, and what it returns.

use serde::{Deserialize, Serialize};
pub use tilo_action_policy::ActionKind;

use crate::action::{OperationKind, undo_takes_back};
use crate::context::ChangeKind;

/// Whether an action can be invoked in the resource's current state.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "state", rename_all = "snake_case")]
pub enum Availability {
    #[default]
    Available,
    Unavailable {
        /// Stable programmatic reason such as `offline` or `selection_empty`.
        code: String,
        /// Localised explanation suitable for a person or an agent transcript.
        reason: String,
    },
}

read_through_json_value!(Availability);

impl Availability {
    /// The code of an action its caller's permissions deny ([`Self::not_allowed`]).
    pub const NOT_ALLOWED: &'static str = "not_allowed";

    pub fn is_available(&self) -> bool {
        matches!(self, Self::Available)
    }

    /// An action an agent's permissions deny it, as it is listed to the agent: told, in one
    /// sentence, what refuses it (`by`, where the check knows) and where that is changed, rather
    /// than left to read the action's absence as there being no such action.
    #[must_use]
    pub fn not_allowed(by: Option<tilo_action_policy::Refuser>) -> Self {
        let reason = match by {
            Some(tilo_action_policy::Refuser::Settings) => {
                "the person you work for set this to Deny for you in this workspace; they can \
                 change it under Workspace settings → Agents"
            }
            Some(tilo_action_policy::Refuser::Workspace) => {
                "this workspace's own rules don't let agents or keys do this here"
            }
            None => Self::NOT_ALLOWED_HERE,
        };
        Self::Unavailable {
            code: Self::NOT_ALLOWED.to_owned(),
            reason: reason.to_owned(),
        }
    }

    /// What an action refused by a check that does not say which rule refused it is told.
    pub const NOT_ALLOWED_HERE: &'static str = "this workspace's permissions don't let you do \
         this here; the person you work for can change what you may do under Workspace \
         settings → Agents";

    /// The code of an action only the person at its device invokes
    /// ([`Self::shown_here`]).
    pub const PRIVATE_VIEW: &'static str = "private_view";

    /// An action that only changes what the person at its device sees (a
    /// form it opens, a place it shows), as an agent that names it is told
    /// of it: never listed to it, and refused as that person's alone rather
    /// than as an action the app does not have.
    #[must_use]
    pub fn shown_here() -> Self {
        Self::Unavailable {
            code: Self::PRIVATE_VIEW.to_owned(),
            reason: Self::SHOWN_HERE.to_owned(),
        }
    }

    /// Why an action [`Self::shown_here`] is refused to anyone but the
    /// person at its device.
    pub const SHOWN_HERE: &'static str =
        "only changes what the person at this device sees; only they invoke it";

    /// The code and reason of an action listed to an agent as refused
    /// ([`Self::not_allowed`], [`Self::shown_here`]), when it is.
    #[must_use]
    pub fn refusal(&self) -> Option<(&str, &str)> {
        match self {
            Self::Unavailable { code, reason }
                if code == Self::NOT_ALLOWED || code == Self::PRIVATE_VIEW =>
            {
                Some((code, reason))
            }
            Self::Available | Self::Unavailable { .. } => None,
        }
    }
}

/// Consequence class used by policy, confirmation UI, and audit logs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RiskLevel {
    /// Presentation-only or otherwise observational.
    None,
    /// A reversible edit or ordinary external effect.
    #[default]
    Low,
    /// Deletes, overwrites, publishes, purchases, or otherwise causes a
    /// consequential change that is not cheaply reversible.
    Destructive,
    /// Crosses an administrative or security boundary.
    Privileged,
    /// Reads or exports private user data. It needs an explicit confirmation,
    /// but unlike deletion it does not itself alter the source resource.
    ///
    /// This is deliberately appended: `RiskLevel` is also encoded by compact
    /// serde formats, where reordering variants would reinterpret old audit
    /// records and envelopes.
    Sensitive,
}

impl RiskLevel {
    /// Whether a change of this class must be explicitly confirmed before it
    /// runs: deletions and overwrites, crossings of a security boundary, and
    /// exports of private data.
    pub fn requires_confirmation(self) -> bool {
        matches!(self, Self::Destructive | Self::Privileged | Self::Sensitive)
    }

    /// Whether a change of this class that `can_be_undone` must be
    /// confirmed before it runs. Undo is a system service: a deletion Undo
    /// takes back runs at once and offers Undo, and is never asked about.
    /// What Undo cannot take back is still asked: an irreversible deletion,
    /// a crossing of a security boundary, an export of private data.
    #[must_use]
    pub fn requires_confirmation_when(self, can_be_undone: bool) -> bool {
        match self {
            Self::Destructive => !can_be_undone,
            Self::Privileged | Self::Sensitive => true,
            Self::None | Self::Low => false,
        }
    }

    /// The level's name, as it is written outside a typed message (a
    /// question a host relays, an activity facet).
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Low => "low",
            Self::Destructive => "destructive",
            Self::Privileged => "privileged",
            Self::Sensitive => "sensitive",
        }
    }

    /// The level [`Self::name`] names; `None` for any other word.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        [
            Self::None,
            Self::Low,
            Self::Destructive,
            Self::Privileged,
            Self::Sensitive,
        ]
        .into_iter()
        .find(|level| level.name() == name)
    }
}

/// [`ActionContract::tags`] entry of an action any member of a workspace may ask
/// the workspace's host to run for themselves on a record of the workspace (linking
/// their own account elsewhere). The host runs it as that member, under
/// their own access, so the action's API and its own checks decide what
/// it may do; its answer goes back to the asking device alone.
pub const MEMBER_OWN_TAG: &str = "host:member-own";

/// [`ActionContract::tags`] entry of an effect a host answers in a render
/// service of its own rather than in the record's confined app worker:
/// rendering a timeline to video needs a GPU and a media stack, which a
/// confined worker has neither of. A host without such a service leaves the
/// effect out of what its agents are offered.
pub const HOST_RENDER_TAG: &str = "host:render";

/// [`ActionContract::tags`] entry of an action for [`Audience::Agents`].
pub const AGENTS_AUDIENCE_TAG: &str = "audience:agents";

/// [`ActionContract::tags`] entry of an action for [`Audience::People`].
pub const PEOPLE_AUDIENCE_TAG: &str = "audience:people";

/// Who an action is listed for. The app declares it. Most actions are for
/// [`Everyone`](Self::Everyone), which is the default. An action outside a
/// listing's audience stays published, resolvable and invocable by address,
/// under the same permission, confirmation and history rules as any other.
/// It just isn't offered there.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Audience {
    #[default]
    Everyone,
    /// Listed for people only: an action whose point is what a person sees
    /// or does next, such as copying a link to the clipboard. Agent listings
    /// leave it out.
    People,
    /// Listed for agents, scripts and the controls that submit it, never for
    /// a person to pick (the palette, menus). Examples: reading a message's
    /// content, revealing a text range by offsets, an edit addressed by an
    /// internal part number.
    Agents,
}

impl Audience {
    /// Whether people's listings (the palette, menus) offer it.
    pub const fn reaches_people(self) -> bool {
        !matches!(self, Self::Agents)
    }

    /// Whether agents' listings offer it.
    pub const fn reaches_agents(self) -> bool {
        !matches!(self, Self::People)
    }

    /// The contract tag recording it, `None` for everyone.
    pub const fn tag(self) -> Option<&'static str> {
        match self {
            Self::Everyone => None,
            Self::People => Some(PEOPLE_AUDIENCE_TAG),
            Self::Agents => Some(AGENTS_AUDIENCE_TAG),
        }
    }
}

/// [`ActionContract::tags`] entry of an action whose result carries content
/// from outside the user's own data (a web page's text, its logs): data for
/// the caller to reason about, never instructions to follow.
pub const UNTRUSTED_CONTENT_TAG: &str = "content:untrusted";

/// [`ActionContract::tags`] entry of an action whose risk, and therefore
/// whether it needs confirmation, depends on the arguments it is invoked
/// with (a generic edit that may delete). The publishing host classifies each
/// invocation; a caller that cannot classify arguments treats the action as
/// requiring confirmation (see [`ActionContract::advertised_confirmation`]).
pub const ARGUMENT_RISK_TAG: &str = "confirmation:by-argument";

/// [`ActionContract::tags`] entry of an action that carries its resource's
/// other actions (a generic typed edit, a group of edits) and is no verb of
/// its own: what it does is what it carries. Whoever decides for such an
/// action or words it for a person reads the actions it carries; a lasting
/// permission is for the action that asked, never for what carried it. See
/// [`ActionSpec::carrying`](crate::ActionSpec::carrying).
pub const CARRIER_TAG: &str = "carries:actions";

/// The parameter of a generic field edit that carries the edit.
pub const FIELD_EDIT_PARAM: &str = "edit";

/// The operation and path of a field edit in its JSON form
/// (`{path: [{field: name} | {item: id} | {key: k} | {cell: ..}], op, ..}`).
fn edit_parts(
    edit: &serde_json::Value,
) -> Option<(&str, Vec<tilo_action_policy::edits::EditStep<'_>>)> {
    use tilo_action_policy::edits::EditStep;
    let op = edit.get("op")?.as_str()?;
    let path = edit
        .get("path")?
        .as_array()?
        .iter()
        .map(|step| {
            let (kind, value) = step.as_object()?.iter().next()?;
            Some(match kind.as_str() {
                "field" => EditStep::Field(value.as_str()?),
                _ => EditStep::Item,
            })
        })
        .collect::<Option<Vec<_>>>()?;
    Some((op, path))
}

/// [`ActionContract::tags`] entry of a document action carried out on another
/// document than the one its resource is kept in ([`crate::ActionSpec::routed`]):
/// published as an effect so that the app keeping that document applies it,
/// it is still only a change of a document. It reads none of the content its
/// resource refers to, so nothing hands it that content, as for any document
/// change: finding that content reads every part the resource keeps.
pub const ROUTED_CHANGE_TAG: &str = "routed:document-change";

/// [`ActionContract::tags`] entry of the read-only action that answers, when
/// invoked with no arguments, the first page of the document an app has
/// open (a word processor's text, a sheet's used cells, a deck's outline).
/// A caller that just opened a file reads it through this action without
/// knowing the app.
pub const DOCUMENT_READ_TAG: &str = "read:document";

/// [`ActionContract::tags`] entry of a read-only action that reads what its
/// record holds (a version of it, a review of one) and moves nothing, though
/// it takes arguments and so is no [`DOCUMENT_READ_TAG`] a caller reads a
/// document's first page through. Like a document read, it is anyone's to
/// run who may read the record, and it discloses the record it sits on to
/// them: History's `review-restore`, a step for agents, is how an agent is
/// shown a record that has no document read (Terminal's session).
pub const RESOURCE_READ_TAG: &str = "read:record";

/// [`ActionContract::tags`] entry of the action that opens the file its
/// `path` parameter names in this app instance, reading it inside the app's
/// sandbox. A caller that launched the app with a file opens it through
/// this action, and only through an action that declares it: one taking a
/// `path` for another purpose (importing an installer image, exporting)
/// is never guessed from its name.
pub const OPENS_PATH_TAG: &str = "open:path";

/// Prefix of the [`ActionContract::tags`] entries naming a capability of
/// the host the action needs: `requires-host:native-paths`. On a host
/// without it the action is published unavailable, coded
/// [`HOST_UNSUPPORTED_CODE`], and so refused, wherever it is offered: an
/// app declares what its action needs once instead of hiding it per host.
/// A requirement the host does not know is one it lacks.
pub const REQUIRES_HOST_PREFIX: &str = "requires-host:";

/// [`REQUIRES_HOST_PREFIX`] entry of an action that reaches files through
/// their file system path, as importing a folder by its path does; browser
/// storage has no paths.
pub const REQUIRES_NATIVE_PATHS_TAG: &str = "requires-host:native-paths";

/// [`Availability::Unavailable`] code of an action whose
/// [`REQUIRES_HOST_PREFIX`] requirement this host cannot meet.
pub const HOST_UNSUPPORTED_CODE: &str = "host_unsupported";

/// Prefix of the [`ActionContract::tags`] entries naming the file
/// extensions (lowercase, without the dot) an [`OPENS_PATH_TAG`] action
/// opens: `open:path-ext:csv`. An opener naming none opens any file.
pub const OPENS_PATH_EXTENSION_PREFIX: &str = "open:path-ext:";

/// Prefix of the [`ActionContract::tags`] entries naming an outside capability
/// an action's body hands an effect to with `outside(capability, ...)`:
/// `outside:youtube.search`. A query naming a kind of an outside service (a
/// `youtube.channel`) finds, through this, the app's own action that asks its
/// origin for what the query names — the service's `search` capability.
pub const OUTSIDE_CAPABILITY_PREFIX: &str = "outside:";

/// The tag of an action an app declares as its search over a remote service (`search: Found`):
/// the system's search asks it for what its query names, and the records it writes are its
/// answers.
pub const SEARCH_TAG: &str = "search";

/// The tag naming the kind an app's declared search answers with, after this prefix
/// (`search_kind:tl.so.tilo.ebook.Found`): the type its `search:` names.
pub const SEARCH_KIND_PREFIX: &str = "search_kind:";

/// Facet the executor writes on a change made by a verb its app marks
/// `#[action(incoming_message)]`: a message someone received. The
/// `IncomingMessage` trigger fires on it without knowing the app's schema.
pub const INCOMING_MESSAGE_FACET: &str = "incoming-message";
/// Contract tag on the declaration of such a verb, so a surface and a
/// catalogue show it.
pub const INCOMING_MESSAGE_TAG: &str = "trigger:incoming-message";
/// Facet a writer sets on a change that copies another member's change (a
/// service mirroring a message back in, a sync of something written
/// elsewhere): the actor bytes of the member whose change it copies
/// (`agent:<id>`, a person's id). A trigger tells a copy of a change from a
/// new one by it, whoever wrote the copy.
pub const ORIGIN_FACET: &str = "origin";

/// Facet the executor writes on a change of what only some members read
/// ([`Action::readers`](crate::Action::readers)): the members who alone read
/// it, as a JSON list of what each member's changes are named by
/// ([`MemberId::actor_bytes`](crate::MemberId::actor_bytes)). History lists
/// the change to them alone ([`reads_change`]).
pub const READERS_FACET: &str = "readers";

/// The value of a [`READERS_FACET`] naming `readers`.
#[must_use]
pub fn readers_facet(readers: &[crate::MemberId]) -> String {
    let named: Vec<String> = readers.iter().map(reader_name).collect();
    serde_json::Value::from(named).to_string()
}

/// How a [`READERS_FACET`] names `member`.
#[must_use]
pub fn reader_name(member: &crate::MemberId) -> String {
    String::from_utf8_lossy(&member.actor_bytes()).into_owned()
}

/// The names of the members who alone read a change whose context has
/// `facets` ([`READERS_FACET`]); `None` when every member reads it. A facet
/// that does not read as a list of names names nobody: never everyone.
#[must_use]
pub fn readers_named(facets: &[crate::ActionFacet]) -> Option<Vec<String>> {
    let facet = facets.iter().find(|facet| facet.key == READERS_FACET)?;
    Some(tilo_failure::ignored!(
        "a readers list that does not read names nobody, which keeps the change from everyone",
        serde_json::from_str(&facet.value).unwrap_or_default()
    ))
}

/// Whether `reader` reads a change whose context has `facets`: every member
/// reads a change no [`READERS_FACET`] marks; one it marks, only the members
/// it names ([`readers_named`]).
#[must_use]
pub fn reads_change(facets: &[crate::ActionFacet], reader: Option<&crate::MemberId>) -> bool {
    readers_named(facets)
        .is_none_or(|named| reader.is_some_and(|reader| named.contains(&reader_name(reader))))
}

/// [`ActionContract::tags`] entry of an action that reaches outside its
/// document through a queue (a file rename the device carries out) and whose
/// undo queues the compensating change. It is still an
/// [`Outside`](ActionKind::Outside) action for the grants deciding it, but it
/// can be taken back: a person reviewing it is told it changes their work,
/// not that it sends something away.
pub const COMPENSATED_UNDO_TAG: &str = "undo:compensated";

/// [`ActionContract::tags`] entry of an action whose document change Undo
/// reverts but which also loses something Undo cannot bring back (an
/// account's secret every device forgets): it cannot be taken back, so a
/// destructive one is confirmed through every API.
pub const IRREVERSIBLE_TAG: &str = "undo:irreversible";

/// Contract tag on the declaration of a housekeeping verb: a change about the
/// record rather than to it (`#[action(housekeeping)]`, such as marking a
/// channel read). An app does these on its own, so nobody is asked to review
/// or confirm one: one an app emits while History shows a past version is
/// dropped, and the app does it again once the person is back.
pub const HOUSEKEEPING_TAG: &str = "change:housekeeping";

/// What one invocation of an action is, for the grants deciding it: its kind,
/// the one field of its resource it writes when it writes only one (a reply
/// writes the `comments`), which places it below that field in the tree, and
/// whether it is privileged ([`RiskLevel::Privileged`]): it exercises
/// authority over the workspace or others in it, so the person's own grants must
/// allow it (`tilo_action_policy::Verdict::privileged`).
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ActionNeed {
    pub kind: ActionKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub privileged: bool,
}

/// The node of the resource `resource` (of kind `resource_kind`) the app
/// `app` publishes, below `base` (a workspace, or the root for a path relative to
/// one): where a reading of it is decided, as an action of it is at
/// [`action_node`].
#[must_use]
pub fn resource_node(
    base: &tilo_action_policy::TreePath,
    app: &str,
    resource_kind: &str,
    resource: &str,
) -> tilo_action_policy::TreePath {
    let (resource_kind, resource) =
        if tilo_action_policy::roles::is_workspace_moderation(app, resource)
            || (resource_kind == "tilo.moderation"
                && resource == resource_kind
                && tilo_action_policy::roles::is_workspace_moderation(
                    app,
                    tilo_action_policy::roles::WORKSPACE_MODERATION_DOCUMENT,
                ))
        {
            ("chat.workspace", "")
        } else {
            (resource_kind, resource)
        };
    base.clone().app(app).kind(resource_kind).resource(resource)
}

/// The node of the action `action` on the resource `resource` (of kind
/// `resource_kind`) the app `app` publishes, below `base` (a workspace, or the
/// root for a path relative to one), and below the one `field` it writes if
/// any: where every API decides it.
#[must_use]
pub fn action_node(
    base: &tilo_action_policy::TreePath,
    app: &str,
    resource_kind: &str,
    resource: &str,
    field: Option<&str>,
    action: &str,
) -> tilo_action_policy::TreePath {
    let node = resource_node(base, app, resource_kind, resource);
    match field {
        Some(field) => node.field(field),
        None => node,
    }
    .action(action)
}

impl ActionNeed {
    /// An action of `kind` on the resource as a whole.
    #[must_use]
    pub const fn of(kind: ActionKind) -> Self {
        Self {
            kind,
            field: None,
            privileged: false,
        }
    }

    /// An undoable change of the resource's comments: what someone who may
    /// only comment may do.
    #[must_use]
    pub fn comments() -> Self {
        Self {
            kind: ActionKind::Undoable,
            field: Some(tilo_action_policy::roles::COMMENTS_FIELD.to_owned()),
            privileged: false,
        }
    }

    /// An undoable change of reactions, wherever they are: what someone who
    /// may only comment may do too.
    #[must_use]
    pub fn reactions() -> Self {
        Self {
            kind: ActionKind::Undoable,
            field: Some(tilo_action_policy::roles::REACTIONS_FIELD.to_owned()),
            privileged: false,
        }
    }

    /// An undoable change under the resource's `moderation` node: acting on
    /// other people's content, which Moderators and the owner may do.
    #[must_use]
    pub fn moderation() -> Self {
        Self {
            kind: ActionKind::Undoable,
            field: Some(tilo_action_policy::roles::MODERATION_FIELD.to_owned()),
            privileged: false,
        }
    }
}

const fn undoable() -> ActionKind {
    ActionKind::Undoable
}

/// Confirmation required after argument binding and immediately before run.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "mode", rename_all = "snake_case")]
pub enum ConfirmationPolicy {
    #[default]
    None,
    Confirm,
    /// Requires an exact phrase, useful for irreversible bulk operations.
    Phrase {
        phrase: String,
    },
}

read_through_json_value!(ConfirmationPolicy);

/// Words that confirm without naming anything: typing one proves only that
/// the person can read the prompt.
const GENERIC_CONFIRMATION_WORDS: &[&str] = &[
    "confirm",
    "confirmed",
    "yes",
    "ok",
    "okay",
    "sure",
    "agree",
    "i agree",
    "continue",
    "proceed",
    "accept",
    "delete",
    "remove",
    "erase",
    "wipe",
    "reset",
    "destroy",
];

/// Whether a typed confirmation `phrase` names what the action destroys
/// (a drive's name, an app's name), rather than a generic word such as
/// "CONFIRM". A typed phrase is for irreversible, high-risk actions, and
/// its point is that the person reads what they are about to lose.
#[must_use]
pub fn phrase_is_meaningful(phrase: &str) -> bool {
    let phrase = phrase.trim();
    !phrase.is_empty()
        && !GENERIC_CONFIRMATION_WORDS
            .iter()
            .any(|word| phrase.eq_ignore_ascii_case(word))
}

/// What a caller may safely do after losing the completion response.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RetryPolicy {
    /// Repeating the call has the same externally observable result.
    Idempotent,
    /// The implementation deduplicates calls by invocation id.
    RetryWithInvocationId,
    /// Never automatically repeat; the first call may have completed.
    #[default]
    AtMostOnce,
}

/// Completion behavior advertised before invocation.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "mode", rename_all = "snake_case")]
pub enum ExecutionMode {
    /// Expected to finish in the request/response window.
    #[default]
    Immediate,
    /// Returns a durable job handle and may report progress.
    Background { cancellable: bool },
    /// Produces ordered values, each checked against `item_schema`, until a
    /// terminal result.
    Streaming {
        cancellable: bool,
        item_schema: serde_json::Value,
    },
    /// A read that stays current: each item, checked against
    /// `item_schema`, is the whole result as it is now, sent again whenever
    /// the provider's answer changes. It ends only when the caller cancels
    /// it, its permission is withdrawn, or the provider fails.
    Live { item_schema: serde_json::Value },
}

read_through_json_value!(ExecutionMode);

impl ExecutionMode {
    /// Whether a caller may cancel a running invocation.
    #[must_use]
    pub const fn cancellable(&self) -> bool {
        matches!(
            self,
            Self::Background { cancellable: true }
                | Self::Streaming {
                    cancellable: true,
                    ..
                }
                | Self::Live { .. }
        )
    }

    /// What each item of a streaming or live invocation must match; `None`
    /// for a mode that sends no items.
    #[must_use]
    pub const fn item_schema(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Streaming { item_schema, .. } | Self::Live { item_schema } => Some(item_schema),
            Self::Immediate | Self::Background { .. } => None,
        }
    }
}

/// Shape of a successful result. Schemas use JSON Schema so non-Rust callers
/// do not need a parallel Tilo-only type system.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "type", rename_all = "snake_case")]
pub enum ResultSpec {
    #[default]
    None,
    Json {
        schema: serde_json::Value,
    },
    Resource {
        resource_kind: String,
    },
    Job,
}

read_through_json_value!(ResultSpec);

/// The fields a write adds beside the answer it declared: the ids it minted
/// (`minted`), each item it made, with the item's id and the address it is
/// published under (`made`), and the text it wrote (`wrote`,
/// [`crate::ActionOutput::wrote`]). What a write answers its caller, whether or
/// not its action declares a result.
pub const MADE_FIELDS: [&str; 3] = ["made", "minted", "wrote"];

impl crate::ActionOutput {
    /// The answer the action declared, without what a write adds beside it
    /// ([`MADE_FIELDS`]): `None` when it declared nothing.
    #[must_use]
    pub fn declared(&self) -> Option<serde_json::Value> {
        let value = self.value.as_ref()?;
        let Some(fields) = value.as_object() else {
            return Some(value.clone());
        };
        let kept: serde_json::Map<String, serde_json::Value> = fields
            .iter()
            .filter(|(key, _)| !MADE_FIELDS.contains(&key.as_str()))
            .map(|(key, value)| (key.clone(), value.clone()))
            .collect();
        if fields.is_empty() {
            // An empty answer is the empty result it always was.
            return Some(serde_json::Value::Object(kept));
        }
        // An answer holding only what the write made declared nothing.
        (!kept.is_empty()).then_some(serde_json::Value::Object(kept))
    }
}

impl ResultSpec {
    /// Check that a completed action returned the shape it advertised.
    pub fn validate(&self, output: &crate::ActionOutput) -> Result<(), String> {
        // What the write made rides beside whatever it declared, so an action
        // with no result may still answer what it created.
        let declared = output.declared();
        match self {
            Self::None | Self::Job if declared.is_none() => Ok(()),
            Self::None => Err("action declared no result but returned one".into()),
            // An absent value is `null`: a result its schema lets be null may be
            // left out by an executor with nothing to report. An answer that
            // holds only what the write made is still the object it answered.
            Self::Json { schema } => match declared.or_else(|| output.value.clone()) {
                Some(value) => crate::params::validate_schema(&value, schema),
                None => crate::params::validate_schema(&serde_json::Value::Null, schema)
                    .map_err(|_| "action did not return its declared JSON result".to_string()),
            },
            Self::Resource { resource_kind }
                if !output.resources.is_empty()
                    && output.resources.iter().all(|address| {
                        address == resource_kind
                            || address.strip_prefix(resource_kind).is_some_and(|suffix| {
                                suffix.starts_with(':') || suffix.starts_with('/')
                            })
                    }) =>
            {
                Ok(())
            }
            Self::Resource { resource_kind } => Err(format!(
                "action did not return a `{resource_kind}` resource address"
            )),
            // The broker assigns and returns the durable invocation id at
            // admission. Applications must not mint a second, unrelated job
            // identity merely to satisfy the result validator.
            Self::Job => Err("job action returned an undeclared terminal value".into()),
        }
    }
}

/// The contract tag of an action that needs its person attending: it opens
/// a chooser for them, asks them for a credential or a sign-in, or shows
/// something only they may see. Whoever acts for a person (an agent, a bot,
/// an app) is always asked first, and no answer allows it unasked, not even
/// one given for that very action. The person's own click needs no workspace's
/// consent: the chooser, the sign-in or the reveal in front of them is
/// their decision, so like an effect of [`OWN_DEVICE_SCOPE`] it needs only
/// what reading needs and runs only on the device of whoever starts it.
pub const ATTENDED_TAG: &str = "tilo.attended";

/// The contract tag of an effect that only changes what is on the screen it is
/// invoked on, as its app declares it (`#[effect(screen)]`): a form it opens, a
/// panel or a place it shows. It reads and answers nothing. Only the person at
/// that screen invokes it, and no agent is listed it: anyone else would move
/// their window and learn nothing ([`ActionContract::only_shows`]).
pub const SCREEN_TAG: &str = "tilo.screen";

/// The contract tag of an effect of [`SCREEN_TAG`] offered on a row or item
/// (`#[effect(screen, on = Row)]`), which shows the row it is offered on. It is
/// answered against its caller's view: anyone else is placed at that row in
/// their own view of the window, where the person sees their presence, and the
/// person's own screen does not move. So it is not the person's alone
/// ([`ActionContract::only_shows`]).
pub const SCREEN_PLACE_TAG: &str = "tilo.screen.place";

/// The contract tag of an action whose answer is a secret (recovery words, a sealed backup): it
/// is handed to its caller once, and whatever dispatches it keeps no copy of it, in no cache of
/// answers, invocation record or history. What is kept says only that it was given
/// ([`ActionContract::answers_a_secret`]).
pub const SECRET_ANSWER_TAG: &str = "tilo.answer.secret";

/// The contract tag of an action only the person's root signs: taking a key back, certifying an
/// agent's. A device that keeps no root of its person's is capped for it
/// (`tilo_action_policy::Cap`), and the call is answered at one of their devices that keeps it
/// ([`ActionContract::root_only`]).
pub const ROOT_ONLY_TAG: &str = "tilo.root-only";

/// The contract tag of an effect whose whole scope is the invoking
/// person's own device: it touches nothing a workspace shares and no one else
/// (their clipboard, their own appearance, a network test from their own
/// browser, a draft of their own). A workspace's grants have nothing to consent
/// to, so it needs only what reading needs ([`ActionContract::need`]), and
/// a guest presses it as the workspace's owner does. Whatever shared it goes on
/// to change goes through that change's own action and is decided there.
/// Being the invoker's own device, it runs only for the person at the
/// device it acts on and those acting for them. An effect that reaches
/// other people (a direct message, a call, a shared live context) is not of
/// this scope.
pub const OWN_DEVICE_SCOPE: &str = "tilo.scope.own-device";

/// Complete operational contract copied into every inert descriptor.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionContract {
    #[serde(default)]
    pub availability: Availability,
    /// What the action is able to do: read, change only the document, or
    /// reach outside it. Whether Undo takes it back and whether it asks
    /// first follow from it. What a grant must allow is its
    /// [`need`](Self::need), which every API decides with the action's
    /// place in the published tree: the kind, unless the action's scope
    /// reaches nothing a workspace governs ([`Self::scoped`]).
    #[serde(default = "undoable")]
    pub kind: ActionKind,
    /// The one field of its resource the action writes, when it writes only
    /// one: the action sits below that field in the tree, so a grant on the
    /// field (commenting is writing `comments`) reaches it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    #[serde(default)]
    pub risk: RiskLevel,
    #[serde(default)]
    pub confirmation: ConfirmationPolicy,
    #[serde(default)]
    pub retry: RetryPolicy,
    #[serde(default)]
    pub execution: ExecutionMode,
    #[serde(default)]
    pub result: ResultSpec,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// The action is heavy enough to run on another of the invoker's devices,
    /// and how: see [`Offload`]. `None` (the default) runs it where it is
    /// invoked, always.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offload: Option<Offload>,
    /// The kind of step it takes, as its declaration names it
    /// ([`crate::StepKind`]): what presence says in the
    /// reader's language ("Writing in Trip plan", "Schreibt in Trip plan").
    /// `None` for an action whose declaration names none, whose step reads as
    /// the part of the record it acts on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step: Option<crate::StepKind>,
    /// The collection of its resource a create adds to (`writes = issues`),
    /// when its declaration names one: what it makes, which presence says by
    /// that collection's own noun ("Creating an issue in Issues"). `None` for
    /// an action that makes nothing, or whose declaration names no collection.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub creates: Option<String>,
    /// The collection whose item the action acts on, when its declaration
    /// says it acts on one (`item = issues`) and no item is bound to it yet:
    /// "Open issue" on the tracker itself. It is offered only where an item
    /// is in hand, bound on that item, so a listing that holds none (a
    /// palette with nothing selected, an agent's listing of the tracker)
    /// leaves it out ([`Self::needs_an_item`]). A caller that names the
    /// action and its item still invokes it here. `None` for an action that
    /// needs no item, or one already bound to its item.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub item: Option<String>,
    /// The arguments the person reads before answering, when the action
    /// asks first ([`ConfirmationPolicy::Confirm`]): what admission shows on
    /// its ask, read from the call itself.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shows: Vec<crate::remote::asked::Shown>,
    /// What the person types where they answer its ask, in order: a site's user name and
    /// password, a passphrase. It reaches the action with their approve
    /// ([`crate::remote::asked::Approval::typed`]), never as an argument of the call, so a secret
    /// is in no record of it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub takes: Vec<crate::remote::asked::Take>,
    /// What it writes beside its own resource, each as the app, kind and verb of the step it
    /// takes there ([`crate::ActionEffect`]). What a caller reads to know what the action
    /// changes; what a device reading such a record checks to admit a step the call itself does
    /// not name; and what a call its app makes for one of its invocations is held to: a call to
    /// an action named here is covered by the yes that invocation was given and asks nobody
    /// again, a call to any other action asks as any call does. Never from the call, always from
    /// this declaration.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<crate::ActionEffect>,
}

/// Largest CPU time an [`Offload`] may declare: a compute job's ceiling.
pub const MAX_OFFLOAD_CPU_TIME_MS: u64 = 5 * 60 * 1_000;
/// Largest memory an [`Offload`] may declare: a compute job's ceiling.
pub const MAX_OFFLOAD_MEMORY_BYTES: u64 = 8 * 1024 * 1024 * 1024;
/// Smallest memory an [`Offload`] may declare: a compute job's floor.
pub const MIN_OFFLOAD_MEMORY_BYTES: u64 = 16 * 1024 * 1024;
/// Largest output an [`Offload`] may declare: a compute job's ceiling.
pub const MAX_OFFLOAD_OUTPUT_BYTES: u64 = 16 * 1024 * 1024;

/// What an offloadable action needs of the device that runs it.
///
/// An offloadable action is a pure content transform: its inputs are
/// content (files the invoker can read), its outputs are content, and the
/// outputs are a function of the inputs alone, byte for byte, whichever
/// device computes them. That is what lets the system run it on the
/// invoker's best-placed device: the action itself is dispatched to that
/// device's provider — a tilolang app or an engine alike — under the
/// caller's grants, and answers exactly what a local run returns. When no
/// device is better placed, or the offload fails for any reason other than
/// the action's own, it runs locally.
///
/// The declaration names no package and no command line: it says what the
/// work needs of a device, and the action runs there as itself.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Offload {
    /// Whether it needs a GPU.
    ///
    /// Encoded always, false or not: the declaration travels inside frames of
    /// formats that carry no field names or lengths, where a field skipped
    /// when absent is read out of the next field's bytes.
    #[serde(default)]
    pub gpu: bool,
    pub cpu_time_ms: u64,
    /// Memory ceiling, in bytes. The inputs count against it.
    pub memory_bytes: u64,
    /// Ceiling on all outputs together, in bytes.
    pub output_bytes: u64,
}

impl Offload {
    /// Why this declaration is outside the bounds of the work a device takes,
    /// if it is.
    #[must_use]
    pub fn validate(&self) -> Vec<String> {
        let mut errors = Vec::new();
        if self.cpu_time_ms == 0 || self.cpu_time_ms > MAX_OFFLOAD_CPU_TIME_MS {
            errors.push("offload cpu time is outside the compute bounds".into());
        }
        if !(MIN_OFFLOAD_MEMORY_BYTES..=MAX_OFFLOAD_MEMORY_BYTES).contains(&self.memory_bytes) {
            errors.push("offload memory is outside the compute bounds".into());
        }
        if self.output_bytes == 0 || self.output_bytes > MAX_OFFLOAD_OUTPUT_BYTES {
            errors.push("offload output is outside the compute bounds".into());
        }
        errors
    }
}

impl Default for ActionContract {
    fn default() -> Self {
        Self {
            availability: Availability::Available,
            kind: ActionKind::Undoable,
            field: None,
            risk: RiskLevel::Low,
            confirmation: ConfirmationPolicy::None,
            retry: RetryPolicy::AtMostOnce,
            execution: ExecutionMode::Immediate,
            result: ResultSpec::None,
            tags: Vec::new(),
            offload: None,
            step: None,
            creates: None,
            item: None,
            shows: Vec::new(),
            takes: Vec::new(),
            effects: Vec::new(),
        }
    }
}

impl ActionContract {
    /// Whether it declares the call of `provider`'s `address` as one of its own steps
    /// ([`Self::effects`]).
    #[must_use]
    pub fn declares(&self, provider: &str, address: &crate::ActionAddress) -> bool {
        self.effects.iter().any(|effect| {
            effect.app == provider
                && effect.kind == address.resource
                && effect.verb == address.action
        })
    }

    /// What an invocation needs when its value does not say otherwise: its
    /// kind, [`scoped`](Self::scoped).
    #[must_use]
    pub fn need(&self) -> ActionNeed {
        self.scoped(ActionNeed {
            kind: self.kind,
            field: self.field.clone(),
            privileged: self.risk == RiskLevel::Privileged,
        })
    }

    /// The authority `need` asks of a workspace once this action's scope is
    /// accounted for. The kind says what the action does (whether Undo takes
    /// it back, whether it asks first); the need says what a grant must
    /// allow, and the scope is where they part: an outside effect on the
    /// person's own device ([`OWN_DEVICE_SCOPE`], [`ATTENDED_TAG`]) reaches
    /// nothing a workspace's grants govern, so it needs only what reading
    /// needs. Every change of a record is the workspace's to decide.
    #[must_use]
    pub fn scoped(&self, mut need: ActionNeed) -> ActionNeed {
        if need.kind == ActionKind::Outside && self.runs_on_invokers_device() {
            need.kind = ActionKind::Read;
        }
        need
    }

    /// Safe defaults for a presentation-only operation.
    pub fn view() -> Self {
        Self {
            risk: RiskLevel::None,
            kind: ActionKind::Read,
            retry: RetryPolicy::Idempotent,
            ..Self::default()
        }
    }

    /// A view whose result stays current ([`ExecutionMode::Live`]), each
    /// item matching `item_schema`.
    pub fn live_view(item_schema: serde_json::Value) -> Self {
        Self {
            execution: ExecutionMode::Live { item_schema },
            ..Self::view()
        }
    }

    /// Whether the action's result stays current ([`ExecutionMode::Live`]).
    #[must_use]
    pub const fn is_live(&self) -> bool {
        matches!(self.execution, ExecutionMode::Live { .. })
    }

    /// The defaults for an operation of `operation`'s kind: a view reads, a
    /// document operation changes only the document, an effect reaches
    /// outside it.
    pub fn for_operation(operation: OperationKind) -> Self {
        match operation {
            OperationKind::View => Self::view(),
            OperationKind::Document => Self::default(),
            OperationKind::Effect => Self {
                kind: ActionKind::Outside,
                ..Self::default()
            },
        }
    }

    /// Whether the effect's scope is the invoking person's own device and
    /// nothing shared. See [`OWN_DEVICE_SCOPE`].
    pub fn is_own_device(&self) -> bool {
        self.tags.iter().any(|tag| tag == OWN_DEVICE_SCOPE)
    }

    /// Whether the action needs its person attending. See [`ATTENDED_TAG`].
    pub fn is_attended(&self) -> bool {
        self.tags.iter().any(|tag| tag == ATTENDED_TAG)
    }

    /// Whether the action acts on the device of whoever invokes it, so only
    /// the person at that device (and those acting for them) runs it: an
    /// effect of [`OWN_DEVICE_SCOPE`] or one its person attends
    /// ([`ATTENDED_TAG`]).
    pub fn runs_on_invokers_device(&self) -> bool {
        self.is_own_device() || self.is_attended()
    }

    /// Whether an effect under this contract only changes what is on the
    /// screen it is invoked on, as its app declares ([`SCREEN_TAG`]): a form it
    /// opens, a panel or a place it shows. Only the person at that screen
    /// invokes it; for anyone else it would move their window and tell the
    /// caller nothing. Nothing else about the contract decides it: an effect
    /// that reads and answers nothing may still write, and is decided as
    /// what it declares.
    pub fn only_shows(&self) -> bool {
        self.tags.iter().any(|tag| tag == SCREEN_TAG) && !self.shows_a_place()
    }

    /// Whether only the person's root signs it ([`ROOT_ONLY_TAG`]).
    pub fn root_only(&self) -> bool {
        self.tags.iter().any(|tag| tag == ROOT_ONLY_TAG)
    }

    /// Whether its answer is a secret, handed over once and kept nowhere ([`SECRET_ANSWER_TAG`]).
    pub fn answers_a_secret(&self) -> bool {
        self.tags.iter().any(|tag| tag == SECRET_ANSWER_TAG)
    }

    /// Whether the effect shows the row it is offered on, answered against its
    /// caller's view ([`SCREEN_PLACE_TAG`]).
    pub fn shows_a_place(&self) -> bool {
        self.tags.iter().any(|tag| tag == SCREEN_PLACE_TAG)
    }

    /// Safe defaults for an effect that only changes what is on the screen it
    /// is invoked on ([`Self::only_shows`]).
    pub fn screen() -> Self {
        let mut contract = Self::view();
        contract.tags.push(SCREEN_TAG.to_owned());
        contract
    }

    /// Who the action is listed for, as its tags record it. See [`Audience`].
    pub fn audience(&self) -> Audience {
        if self.tags.iter().any(|tag| tag == AGENTS_AUDIENCE_TAG) {
            Audience::Agents
        } else if self.tags.iter().any(|tag| tag == PEOPLE_AUDIENCE_TAG) {
            Audience::People
        } else {
            Audience::Everyone
        }
    }

    /// Record `audience` in the tags, replacing any audience before it.
    pub fn set_audience(&mut self, audience: Audience) {
        self.tags
            .retain(|tag| tag != AGENTS_AUDIENCE_TAG && tag != PEOPLE_AUDIENCE_TAG);
        if let Some(tag) = audience.tag() {
            self.tags.push(tag.to_owned());
        }
    }

    /// Whether people's listings offer it. See [`Audience::reaches_people`].
    pub fn reaches_people(&self) -> bool {
        self.audience().reaches_people()
    }

    /// Whether agents' listings offer it. See [`Audience::reaches_agents`].
    pub fn reaches_agents(&self) -> bool {
        self.audience().reaches_agents()
    }

    /// Whether it acts on an item it has not been given ([`Self::item`]):
    /// what only a place holding an item offers.
    #[must_use]
    pub fn needs_an_item(&self) -> bool {
        self.item.is_some()
    }

    /// Whether a listing that holds no item offers it to a person: one for
    /// people that needs no item ([`Self::needs_an_item`]). The palette with
    /// nothing selected, a window's controls and a search list this.
    #[must_use]
    pub fn offered_to_people(&self) -> bool {
        self.reaches_people() && !self.needs_an_item()
    }

    /// Whether a person may take it from a list now: offered to people
    /// ([`Self::offered_to_people`]) and with something to act on in the
    /// window's state. One that can only say why it cannot run (an event's
    /// `Invite` with no event selected) takes no row: the person who typed its
    /// name meant the thing that works.
    #[must_use]
    pub fn a_person_can_take_now(&self) -> bool {
        self.offered_to_people() && self.availability.is_available()
    }

    /// [`Self::offered_to_people`] for agents: what an agent's listing of a
    /// resource offers it, an action that needs an item being offered on
    /// the item.
    #[must_use]
    pub fn offered_to_agents(&self) -> bool {
        self.reaches_agents() && !self.needs_an_item()
    }

    /// Whether the action reads the open document's first page. See
    /// [`DOCUMENT_READ_TAG`].
    pub fn reads_document(&self) -> bool {
        self.tags.iter().any(|tag| tag == DOCUMENT_READ_TAG)
    }

    /// Whether the action reads what its record holds and moves nothing: a
    /// document read ([`DOCUMENT_READ_TAG`]) or another read of the record's
    /// state ([`RESOURCE_READ_TAG`]).
    pub fn reads_resource(&self) -> bool {
        self.reads_document() || self.tags.iter().any(|tag| tag == RESOURCE_READ_TAG)
    }

    /// Whether a view under this contract shows its resource to callers other
    /// than its publisher: a read of the record ([`Self::reads_resource`]) or
    /// the caller's own presence view. Any other view changes only what
    /// its caller sees, and keeps the resource it alone discloses private
    /// (the action directory's disclosure, `agent_disclosure`).
    pub fn discloses_resource(&self) -> bool {
        self.reads_resource() || self.is_presence_view()
    }

    /// Which of a resource's views the action directory discloses it
    /// through, lowest first and the first of equals: a document read, then
    /// another read of the record, then any other view.
    pub fn disclosure_rank(&self) -> u8 {
        if self.reads_document() {
            0
        } else if self.reads_resource() {
            1
        } else {
            2
        }
    }

    /// Whether the action opens the file its `path` names. See
    /// [`OPENS_PATH_TAG`].
    pub fn opens_path(&self) -> bool {
        self.tags.iter().any(|tag| tag == OPENS_PATH_TAG)
    }

    /// The file extensions an [`opens_path`](Self::opens_path) action is
    /// declared for; none means any file. See
    /// [`OPENS_PATH_EXTENSION_PREFIX`].
    pub fn opened_extensions(&self) -> impl Iterator<Item = &str> {
        self.tags
            .iter()
            .filter_map(|tag| tag.strip_prefix(OPENS_PATH_EXTENSION_PREFIX))
    }

    /// Whether the action's result carries content from outside the user's
    /// own data. See [`UNTRUSTED_CONTENT_TAG`].
    pub fn carries_untrusted_content(&self) -> bool {
        self.tags.iter().any(|tag| tag == UNTRUSTED_CONTENT_TAG)
    }

    /// Whether the action carries its resource's other actions and is no
    /// verb of its own. See [`CARRIER_TAG`].
    #[must_use]
    pub fn carries_actions(&self) -> bool {
        self.tags.iter().any(|tag| tag == CARRIER_TAG)
    }

    /// The outside capabilities the action hands an effect to
    /// (`youtube.search`), as its tags record them. See
    /// [`OUTSIDE_CAPABILITY_PREFIX`].
    pub fn outside_capabilities(&self) -> impl Iterator<Item = &str> {
        self.tags
            .iter()
            .filter_map(|tag| tag.strip_prefix(OUTSIDE_CAPABILITY_PREFIX))
    }

    /// Whether the action, once taken, can be undone: the host's undo
    /// reverts an [`Undoable`](ActionKind::Undoable) change, and an outside
    /// one declared with its compensation ([`COMPENSATED_UNDO_TAG`]) is
    /// undone by queueing it. One that also loses what Undo cannot bring
    /// back ([`IRREVERSIBLE_TAG`]) cannot.
    pub fn can_be_undone(&self) -> bool {
        (self.kind == ActionKind::Undoable
            || self.tags.iter().any(|tag| tag == COMPENSATED_UNDO_TAG))
            && !self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG)
    }

    /// Whether an invocation of this action must be confirmed before it
    /// runs: its risk asks for it and Undo cannot take it back
    /// ([`RiskLevel::requires_confirmation_when`]).
    #[must_use]
    pub fn requires_confirmation(&self) -> bool {
        self.risk.requires_confirmation_when(self.can_be_undone())
    }

    /// Bring the declared policy in line with the risk and whether Undo
    /// takes the action back: a deletion Undo takes back asks nothing, one
    /// it cannot asks with a click. An explicit typed phrase, and the policy
    /// of any other risk, stay as declared. Every builder that changes the
    /// risk, the undo or the tags calls this, so the order they are called
    /// in never decides whether a person is asked.
    ///
    /// The kind is read through
    /// [`settled_kind`](Self::settled_kind), so a deletion built before the
    /// kind that makes it undoable still ends up asking nothing, and one a
    /// declaration says reaches outside still asks.
    pub fn settle_confirmation(&mut self) {
        if self.risk != RiskLevel::Destructive {
            return;
        }
        let undoable = undo_takes_back(
            self.settled_kind(),
            ChangeKind::Content,
            self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG),
        );
        match (&self.confirmation, undoable) {
            (ConfirmationPolicy::Confirm, true) => self.confirmation = ConfirmationPolicy::None,
            (ConfirmationPolicy::None, false) => self.confirmation = ConfirmationPolicy::Confirm,
            _ => {}
        }
    }

    /// The kind this contract says the action is, where [`kind`](Self::kind)
    /// cannot say it alone: a change to its own document is undoable unless
    /// it keeps something Undo cannot bring back ([`IRREVERSIBLE_TAG`]), or
    /// unless it reaches outside and queues its compensation
    /// ([`COMPENSATED_UNDO_TAG`]).
    #[must_use]
    pub fn settled_kind(&self) -> ActionKind {
        let irreversible = self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG);
        let undoable = self.kind == ActionKind::Undoable
            || self.tags.iter().any(|tag| tag == COMPENSATED_UNDO_TAG);
        if undoable && !irreversible {
            return ActionKind::Undoable;
        }
        if self.kind == ActionKind::Undoable {
            return ActionKind::Outside;
        }
        self.kind
    }

    /// The kind of a deletion, which has to say which it is: what its kind
    /// settles to, less where Undo cannot take the change back at all.
    #[must_use]
    pub fn deletion_kind(&self) -> ActionKind {
        let irreversible = self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG);
        let kind = self.settled_kind();
        if undo_takes_back(kind, ChangeKind::Content, irreversible) {
            kind
        } else {
            ActionKind::Outside
        }
    }

    /// Whether confirmation depends on the invocation's arguments. See
    /// [`ARGUMENT_RISK_TAG`].
    pub fn confirmation_depends_on_arguments(&self) -> bool {
        self.tags.iter().any(|tag| tag == ARGUMENT_RISK_TAG)
    }

    /// The confirmation a caller that cannot classify arguments must assume:
    /// the declared policy, or [`ConfirmationPolicy::Confirm`] for an action
    /// whose risk depends on its arguments. A trust boundary that only sees
    /// this inert contract (the session broker) waits for it; the publishing
    /// host, which can classify, asks
    /// [`ActionSpec::confirmation_for_json`](crate::ActionSpec::confirmation_for_json).
    pub fn advertised_confirmation(&self) -> ConfirmationPolicy {
        // An action whose risk depends on its arguments is a generic edit or
        // a verb that may delete: what Undo takes back asks nothing,
        // whichever value it carries.
        if self.confirmation == ConfirmationPolicy::None
            && self.confirmation_depends_on_arguments()
            && !self.can_be_undone()
        {
            ConfirmationPolicy::Confirm
        } else {
            self.confirmation.clone()
        }
    }

    /// Whether an invocation with `argument` asks the person an agent acts
    /// for, whatever their broader answers allow: it needs a confirmation
    /// ([`Self::confirmation_for_argument`]) or its person attending
    /// ([`Self::is_attended`]).
    pub fn asks_for_argument(&self, argument: Option<&str>) -> bool {
        self.is_attended() || self.confirmation_for_argument(argument) != ConfirmationPolicy::None
    }

    /// The confirmation an invocation with `argument` (the wire argument:
    /// typed JSON behind [`ARGUMENTS_JSON_PREFIX`](crate::ARGUMENTS_JSON_PREFIX))
    /// needs, decided without the publishing app's code: the declared
    /// policy; for a generic field edit, the edit itself read by
    /// [`tilo_action_policy::edits::field_edit_asks`]; for any other action
    /// whose risk depends on its arguments, [`Self::advertised_confirmation`].
    pub fn confirmation_for_argument(&self, argument: Option<&str>) -> ConfirmationPolicy {
        if self.confirmation != ConfirmationPolicy::None
            || !self.confirmation_depends_on_arguments()
            || !self
                .tags
                .iter()
                .any(|tag| tag == tilo_action_policy::edits::FIELD_EDIT_TAG)
        {
            return self.advertised_confirmation();
        }
        let edit = argument
            .and_then(|text| text.strip_prefix(crate::ARGUMENTS_JSON_PREFIX))
            .and_then(|json| serde_json::from_str::<serde_json::Value>(json).ok())
            .and_then(|arguments| arguments.get(FIELD_EDIT_PARAM).cloned());
        let tagged = |prefix: &str| -> Vec<&str> {
            self.tags
                .iter()
                .filter_map(|tag| tag.strip_prefix(prefix))
                .collect()
        };
        let quiet = tagged(tilo_action_policy::edits::QUIET_REMOVAL_TAG);
        let guarded = tagged(tilo_action_policy::edits::GUARDED_FIELD_TAG);
        let weakening: Vec<_> = tagged(tilo_action_policy::edits::WEAKENING_FIELD_TAG)
            .into_iter()
            .filter_map(tilo_action_policy::edits::WeakeningField::parse)
            .collect();
        let value = edit
            .as_ref()
            .and_then(|edit| edit.get("value"))
            .map(serde_json::Value::to_string);
        // Whatever a generic edit of an undoable record removes, Undo puts
        // back: only a field that exposes the person or weakens their
        // security still asks.
        let undoable = self.can_be_undone();
        let asks = |op: &str, path: &[tilo_action_policy::edits::EditStep<'_>]| {
            if undoable {
                tilo_action_policy::edits::guarded_at(path, &guarded)
            } else {
                tilo_action_policy::edits::field_edit_asks(op, path, &quiet, &guarded)
            }
        };
        match edit.as_ref().and_then(edit_parts) {
            Some((op, path))
                if !asks(op, &path)
                    && !tilo_action_policy::edits::weakening_edit(
                        op,
                        &path,
                        value.as_deref(),
                        &weakening,
                    ) =>
            {
                ConfirmationPolicy::None
            }
            // An edit nobody can read asks, unless the record has no field
            // that exposes the person or weakens their security and Undo
            // takes back whatever it changes.
            None if undoable && guarded.is_empty() && weakening.is_empty() => {
                ConfirmationPolicy::None
            }
            _ => ConfirmationPolicy::Confirm,
        }
    }

    /// Validate the contract as inert protocol data. This is intentionally
    /// usable at both publication ends: a well-behaved app checks before it
    /// sends, and the broker repeats the check at its trust boundary.
    pub fn validate_declaration(&self) -> Vec<String> {
        let mut errors = Vec::new();
        if let Availability::Unavailable { code, reason } = &self.availability
            && (code.trim().is_empty() || reason.trim().is_empty())
        {
            errors.push("unavailable action needs a code and reason".into());
        }
        if self.requires_confirmation() && matches!(self.confirmation, ConfirmationPolicy::None) {
            errors.push("consequential action requires confirmation".into());
        }
        if let ConfirmationPolicy::Phrase { phrase } = &self.confirmation {
            if phrase.trim().is_empty() {
                errors.push("confirmation phrase must not be empty".into());
            } else if !phrase_is_meaningful(phrase) {
                errors.push(format!(
                    "confirmation phrase \"{phrase}\" says nothing about what is lost; name it (the drive, the app, the item)"
                ));
            }
            if self.can_be_undone() {
                errors.push(
                    "an action Undo takes back is never confirmed by typing; it runs at once and offers Undo".into(),
                );
            }
        }
        if matches!(self.retry, RetryPolicy::RetryWithInvocationId) {
            errors.push(
                "retry_with_invocation_id requires a caller-supplied deduplication key, which this transport does not yet expose".into(),
            );
        }
        if matches!(self.execution, ExecutionMode::Background { .. })
            && matches!(self.result, ResultSpec::None)
        {
            errors.push("background action must declare a result or job".into());
        }
        if matches!(self.execution, ExecutionMode::Immediate)
            && matches!(self.result, ResultSpec::Job)
        {
            errors.push("immediate action cannot declare a background job result".into());
        }
        if let Some(item_schema) = self.execution.item_schema()
            && let Err(reason) = crate::params::validate_schema_definition(item_schema)
        {
            errors.push(format!("invalid streaming item {reason}"));
        }
        if self.is_live() && self.kind != ActionKind::Read {
            errors.push("a live result must be a read".into());
        }
        if let ResultSpec::Json { schema } = &self.result
            && let Err(reason) = crate::params::validate_schema_definition(schema)
        {
            errors.push(format!("invalid result {reason}"));
        }
        if self.tags.iter().any(|tag| tag.trim().is_empty()) {
            errors.push("contract tags must not be empty".into());
        }
        let unique_tags = self.tags.iter().collect::<std::collections::HashSet<_>>();
        if unique_tags.len() != self.tags.len() {
            errors.push("contract tags must be unique".into());
        }
        if let Some(offload) = &self.offload {
            errors.extend(offload.validate());
            // A transform of content: it changes nothing where it runs.
            if self.kind != ActionKind::Read {
                errors.push("an offloadable action must be a read".into());
            }
        }
        errors
    }
}

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

    fn risk_level_keeps_existing_compact_wire_discriminants() {
        // `RiskLevel` appears in recorded action contracts. Postcard encodes
        // enum variants by ordinal, so the old values are a compatibility
        // boundary rather than an implementation detail.
        assert_eq!(postcard::to_allocvec(&RiskLevel::None).unwrap(), vec![0]);
        assert_eq!(postcard::to_allocvec(&RiskLevel::Low).unwrap(), vec![1]);
        assert_eq!(
            postcard::to_allocvec(&RiskLevel::Destructive).unwrap(),
            vec![2]
        );
        assert_eq!(
            postcard::to_allocvec(&RiskLevel::Privileged).unwrap(),
            vec![3]
        );
        assert_eq!(
            postcard::from_bytes::<RiskLevel>(&[2]).unwrap(),
            RiskLevel::Destructive
        );
        assert_eq!(
            postcard::from_bytes::<RiskLevel>(&[3]).unwrap(),
            RiskLevel::Privileged
        );
    }

    fn broker_owned_job_identity_is_not_a_second_application_result() {
        assert!(
            ResultSpec::Job
                .validate(&crate::ActionOutput::default())
                .is_ok()
        );
        assert!(
            ResultSpec::Job
                .validate(&crate::ActionOutput {
                    value: Some(serde_json::json!("a second job id")),
                    resources: Vec::new(),
                })
                .is_err()
        );
    }

    /// A write answers what it made beside whatever it declared, so an
    /// action that declares no result may still say which items it created —
    /// and one that declares a result is judged on that result alone.
    #[test]
    fn what_a_write_made_rides_beside_the_result_it_declared() {
        let made = crate::ActionOutput {
            value: Some(serde_json::json!({
                "made": [{"id": "a1", "address": "notes.page/pages/a1"}],
                "minted": ["a1"],
            })),
            resources: vec!["notes.page/pages/a1".into()],
        };
        assert!(ResultSpec::None.validate(&made).is_ok());
        assert!(ResultSpec::Job.validate(&made).is_ok());
        let schema = serde_json::json!({"type": "object", "required": ["count"],
            "properties": {"count": {"type": "integer"}}});
        let with_count = crate::ActionOutput {
            value: Some(serde_json::json!({
                "count": 2,
                "made": [{"id": "a1", "address": "notes.page/pages/a1"}],
            })),
            resources: Vec::new(),
        };
        assert!(ResultSpec::Json { schema }.validate(&with_count).is_ok());
        assert!(
            ResultSpec::None
                .validate(&crate::ActionOutput {
                    value: Some(serde_json::json!({"count": 2})),
                    resources: Vec::new(),
                })
                .is_err(),
            "a result an action did not declare is still refused"
        );
    }

    tilo_test_env::scenario! {
        fn a_contract_declares_consent_audience_and_wire_shape;

        phase an_attended_or_own_device_effect_needs_no_workspace_consent;
        // An outside effect the person attends (their chooser, a sign-in) or
        // one on their own device needs only what reading needs, so a workspace's
        // guest starts it with no workspace consent; it runs on the device of
        // whoever starts it. Any other outside effect still reaches outside.
        {
            let outside = ActionContract::for_operation(OperationKind::Effect);
            assert_eq!(outside.need().kind, ActionKind::Outside);
            assert!(!outside.runs_on_invokers_device());
            for tag in [ATTENDED_TAG, OWN_DEVICE_SCOPE] {
                let mut contract = outside.clone();
                contract.tags.push(tag.to_owned());
                assert_eq!(contract.need().kind, ActionKind::Read, "{tag}");
                assert!(contract.runs_on_invokers_device(), "{tag}");
            }
        }

        phase undoable_deletes_ask_nothing_and_typed_phrases_name_what_is_lost;
        // Undoable actions run at once and offer Undo, with no confirmation.
        // A typed confirmation is for irreversible, high-risk actions only, and
        // its word names what is lost (the item's name), never a generic word.
        {
            // A deletion Undo takes back asks nothing, whichever order the
            // contract learned it was a deletion and that Undo takes it back.
            let mut contract = ActionContract {
                risk: RiskLevel::Destructive,
                ..ActionContract::default()
            };
            contract.settle_confirmation();
            assert_eq!(contract.confirmation, ConfirmationPolicy::None);
            assert!(!contract.requires_confirmation());
            assert!(contract.validate_declaration().is_empty());
            let mut compensated = ActionContract {
                risk: RiskLevel::Destructive,
                confirmation: ConfirmationPolicy::Confirm,
                tags: vec![COMPENSATED_UNDO_TAG.to_owned()],
                ..ActionContract::default()
            };
            compensated.settle_confirmation();
            assert_eq!(compensated.confirmation, ConfirmationPolicy::None);

            // One Undo cannot take back still asks, with a click: an effect
            // reaches outside the state its resource owns, so nothing brings
            // back what it did, and the declaration says as much by naming it.
            let mut irreversible = ActionContract {
                kind: ActionKind::Outside,
                risk: RiskLevel::Destructive,
                ..ActionContract::default()
            };
            irreversible.settle_confirmation();
            assert_eq!(irreversible.confirmation, ConfirmationPolicy::Confirm);
            assert!(irreversible.requires_confirmation());
            // Nor can it take back what the document change lost outside it (a
            // secret every device forgot), however the change itself reverts.
            let mut forgets = ActionContract {
                kind: ActionKind::Outside,
                risk: RiskLevel::Destructive,
                tags: vec![IRREVERSIBLE_TAG.to_owned()],
                ..ActionContract::default()
            };
            forgets.settle_confirmation();
            assert_eq!(forgets.confirmation, ConfirmationPolicy::Confirm);
            // Crossing a security boundary or exporting private data asks even
            // when Undo would take the change back.
            assert!(RiskLevel::Privileged.requires_confirmation_when(true));
            assert!(RiskLevel::Sensitive.requires_confirmation_when(true));

            // A generic edit of an undoable record asks nothing for any value.
            let edit = ActionContract {
                tags: vec![
                    ARGUMENT_RISK_TAG.to_owned(),
                    tilo_action_policy::edits::FIELD_EDIT_TAG.to_owned(),
                ],
                ..ActionContract::default()
            };
            assert_eq!(edit.advertised_confirmation(), ConfirmationPolicy::None);
            assert_eq!(
                edit.confirmation_for_argument(None),
                ConfirmationPolicy::None
            );

            // A typed phrase is refused on an undoable action, and when it names
            // nothing.
            let phrase = |phrase: &str, kind: ActionKind| ActionContract {
                risk: RiskLevel::Destructive,
                kind,
                confirmation: ConfirmationPolicy::Phrase {
                    phrase: phrase.into(),
                },
                ..ActionContract::default()
            };
            assert!(
                phrase("Hacker News", ActionKind::Undoable)
                    .validate_declaration()
                    .iter()
                    .any(|error| error.contains("Undo takes back"))
            );
            for generic in ["CONFIRM", "yes", "Delete"] {
                assert!(
                    phrase(generic, ActionKind::Outside)
                        .validate_declaration()
                        .iter()
                        .any(|error| error.contains("says nothing")),
                    "{generic}"
                );
            }
            assert!(
                phrase("nvme0n1", ActionKind::Outside)
                    .validate_declaration()
                    .is_empty()
            );
            assert!(phrase_is_meaningful("Windows 11"));
            assert!(!phrase_is_meaningful(" confirm "));
        }

        phase an_actions_audience_decides_whose_listings_offer_it;
        // An action is for everyone unless the app says otherwise, and the
        // audience it says replaces the one before: people's listings leave out
        // what is for agents, agents' leave out what is for people.
        {
            let mut contract = ActionContract::default();
            assert_eq!(contract.audience(), Audience::Everyone);
            assert!(contract.reaches_people() && contract.reaches_agents());
            contract.set_audience(Audience::Agents);
            assert_eq!(contract.audience(), Audience::Agents);
            assert!(!contract.reaches_people() && contract.reaches_agents());
            contract.set_audience(Audience::People);
            assert_eq!(contract.audience(), Audience::People);
            assert!(contract.reaches_people() && !contract.reaches_agents());
            assert_eq!(
                contract
                    .tags
                    .iter()
                    .filter(|tag| tag.starts_with("audience:"))
                    .count(),
                1,
                "one audience at a time: {:?}",
                contract.tags
            );
            contract.set_audience(Audience::Everyone);
            assert!(
                contract
                    .tags
                    .iter()
                    .all(|tag| !tag.starts_with("audience:"))
            );
        }

        phase the_contract_keeps_wire_discriminants_and_one_job_identity;
        // Risk levels keep their compact wire discriminants and a broker-owned job identity is not a
        // second application result.
        // Runs each phase below in order; every phase builds its own fixture.
        {
            risk_level_keeps_existing_compact_wire_discriminants();
            broker_owned_job_identity_is_not_a_second_application_result();
        }

        phase only_a_nullable_json_result_may_be_left_out;
        {
            let nullable = ResultSpec::Json {
                schema: serde_json::json!({"type": ["string", "null"]}),
            };
            let required = ResultSpec::Json {
                schema: serde_json::json!({"type": "string"}),
            };
            let none = crate::ActionOutput::default();
            assert!(nullable.validate(&none).is_ok());
            assert!(required.validate(&none).is_err());
            let text = crate::ActionOutput {
                value: Some(serde_json::json!("changed")),
                resources: Vec::new(),
            };
            assert!(nullable.validate(&text).is_ok());
            assert!(required.validate(&text).is_ok());
        }

        phase offload_is_an_additive_bounded_declaration_on_reads;
        // An offload declaration is additive on the wire, bounded like a
        // compute job, and only declarable on a read that may leave the device.
        {
            let local = ActionContract::view();
            let json = serde_json::to_value(&local).unwrap();
            assert!(json.get("offload").is_none(), "absent stays off the wire");
            let old: ActionContract = serde_json::from_value(json).unwrap();
            assert_eq!(old.offload, None);

            let offload = Offload {
                gpu: false,
                cpu_time_ms: 60_000,
                memory_bytes: 512 * 1024 * 1024,
                output_bytes: 8 * 1024 * 1024,
            };
            let heavy = ActionContract {
                offload: Some(offload.clone()),
                ..ActionContract::view()
            };
            assert!(heavy.validate_declaration().is_empty());
            let round: ActionContract =
                serde_json::from_value(serde_json::to_value(&heavy).unwrap()).unwrap();
            assert_eq!(round, heavy);

            let unbounded = ActionContract {
                offload: Some(Offload {
                    cpu_time_ms: 0,
                    memory_bytes: MAX_OFFLOAD_MEMORY_BYTES + 1,
                    output_bytes: MAX_OFFLOAD_OUTPUT_BYTES + 1,
                    ..offload
                }),
                ..ActionContract::view()
            };
            assert_eq!(unbounded.validate_declaration().len(), 3);
            let writes = ActionContract {
                offload: Some(offload),
                ..ActionContract::default()
            };
            assert_eq!(
                writes.validate_declaration(),
                vec!["an offloadable action must be a read".to_string()]
            );
        }
    }
}