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
//! A device's one record of each invocation it was asked for, by the invocation's id: who asked,
//! what they asked, in which workspace, when, how it stands, and the provider it runs at.
//!
//! However the device is asked about an invocation afterwards (on the connection that started it,
//! from another device of the person, over `/v1` or MCP, or as one of [`PROVIDER`]'s actions),
//! it answers from this record, and the record asks the provider the call went to. A host that
//! hands a call on to another host records where it went ([`Invocations::record`] again), so
//! following, cancelling and waiting reach the host that runs it with no map of its own.
//!
//! [`PROVIDER`]: super::workspace_invocations::PROVIDER

use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError};

use super::secret_arguments::{SecretAnswers, SecretParameters, secret_arguments, without_secrets};
use super::workspace_invocations::{CANCEL, Origin, PROVIDER, RETRY, Spend, UNDO};
use super::{
    ActionCallError, ActionProvider, Caller, CatalogueQuery, InvocationReceipt, InvocationState,
    InvokeArgument, InvokeRequest, MAX_CATALOGUE_PAGE, Pending, ReceiptStatus, RemoteActionTarget,
    ResourceWake, pending,
};
use crate::InvocationId;

/// Whether `caller` may write the resource an invocation was made from
/// ([`Recorded::origin`]): what a provider's own grant check answers at the moment it is
/// asked, so a person's access to that resource decides it then, never as it was.
pub type OriginWrites<'a> = dyn Fn(&Caller, &Origin) -> bool + 'a;

/// The most invocations a device keeps a record of; the oldest goes first.
const KEPT: usize = 4096;

/// Why an invocation is not run again from its record: it keeps none of what it was asked with
/// that may be secret.
pub const NOT_KEPT: &str = "what it was asked with is not kept with its record: ask for it again";

/// Why an invocation is not taken back at a provider: the record there offers no history.
pub const NO_HISTORY: &str = "the record it changed offers no history to take back";

/// `state`, with what a secret answer said replaced by the word that it was given.
fn given(mut state: InvocationState) -> InvocationState {
    if let crate::InvocationUpdate::Succeeded { output, .. } = &mut state.update {
        *output = crate::ActionOutput {
            value: Some(serde_json::json!({ "given": true })),
            resources: Vec::new(),
        };
    }
    state
}

/// Where an invocation runs: the provider, and the caller it runs as there.
pub type Route = (Arc<dyn ActionProvider + Send + Sync>, Caller);

/// One invocation as the device recorded it.
#[derive(Clone)]
pub struct Recorded {
    /// Who asked for it.
    pub caller: Caller,
    /// Who the workspace names as having asked: the same caller, or the agent the person's
    /// device handed the run to, which the caller alone does not say. Display only; who may
    /// follow and stop the call is [`Self::caller`].
    pub asked: Caller,
    pub request: InvokeRequest,
    /// The arguments [`Self::request`] was asked with that the record keeps none of, by name:
    /// those its action declares secret, or all where no descriptor of it was found.
    pub sealed: Vec<String>,
    /// The workspace it acts in, when it acts in one.
    pub workspace: Option<String>,
    /// When it was asked for and when it ended, in ms since the epoch.
    pub started_ms: u64,
    pub ended_ms: Option<u64>,
    /// How it stood when last asked.
    pub state: Option<InvocationState>,
    /// How often its state was seen to change: what a follower waits past.
    pub changes: u64,
    /// It was answered as waiting for its person, and has not ended since: the call goes on and
    /// ends once they decide.
    pub waiting: bool,
    /// The resource the call was made from, when it named one: the caller's `$from`, else the
    /// conversation its turn belongs to. Whoever may write it may stop the invocation or run it
    /// again.
    pub origin: Option<Origin>,
    /// The invocation this one runs again, when it is a retry: the same action, arguments and
    /// caller, under a new id.
    pub retries: Option<InvocationId>,
    /// What a model call it made cost, as the model endpoint wrote it.
    pub spend: Option<Spend>,
    /// What it changed was taken back, through its record's own history.
    pub undone: bool,
    /// Its answer is a secret ([`crate::SECRET_ANSWER_TAG`]): the record keeps neither what it
    /// was asked with nor what it answered, only that it was answered.
    pub secret: bool,
    route: Route,
}

/// The invocations one device was asked for.
#[derive(Default)]
pub struct Invocations {
    kept: Mutex<Kept>,
    /// What each call's action declares secret, as the device's dispatch reads it from its
    /// registry of actions ([`Self::keep_no_secrets`]): no record here keeps those arguments.
    secrets: std::sync::OnceLock<SecretParameters>,
    /// Whether each call's action answers a secret, as the device's dispatch reads its
    /// declaration ([`Self::keep_secret_answers`]): no record here keeps its answer.
    answers: std::sync::OnceLock<SecretAnswers>,
}

#[derive(Default)]
struct Kept {
    by_id: HashMap<InvocationId, Recorded>,
    order: VecDeque<InvocationId>,
    /// Readers of a workspace's invocations, by the workspace: each woken once by the next
    /// invocation recorded there ([`Invocations::watch`]).
    watching: Vec<(String, ResourceWake)>,
}

impl Invocations {
    fn kept(&self) -> std::sync::MutexGuard<'_, Kept> {
        self.kept.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Keep none of the arguments `secrets` names for a call's action, from now on: they reach
    /// the provider in the call alone, and one run again from its record is refused for want
    /// of them. Named once, by the device's dispatch.
    pub fn keep_no_secrets(&self, secrets: SecretParameters) {
        let _ = self.secrets.set(secrets);
    }

    /// Decide whether a call's action answers a secret ([`crate::SECRET_ANSWER_TAG`]) by
    /// `answers`, from now on: its declaration, as the device's dispatch reads it, keeps every
    /// record of the call from holding its answer, whoever asked and wherever it was dispatched.
    /// Named once, by the device's dispatch.
    pub fn keep_secret_answers(&self, answers: SecretAnswers) {
        let _ = self.answers.set(answers);
    }

    /// `request` as its record keeps it: without the arguments its action declares secret, or
    /// any where no descriptor of it is found, beside their names. A call of the vault's add by
    /// its address through the action registry carries the add's own arguments inside its
    /// `arguments`, and keeps none of the add's secrets either.
    fn journaled(&self, request: &InvokeRequest) -> (InvokeRequest, Vec<String>) {
        let names = self.secrets.get().map_or_else(Vec::new, |secrets| {
            secret_arguments(request, secrets(&request.target))
        });
        let (mut kept, taken) = without_secrets(request, &names);
        let mut sealed: Vec<String> = taken.keys().cloned().collect();
        if super::person_vault::calls_by_address(request, super::person_vault::ADD)
            && let Some(secrets) = self.secrets.get()
            && let InvokeArgument::Json(arguments) = &mut kept.argument
            && let Some(serde_json::Value::Object(inner)) = arguments.get_mut("arguments")
        {
            let add = super::person_vault::target(super::person_vault::ADD);
            let names = secrets(&add).unwrap_or_else(|| inner.keys().cloned().collect());
            for name in names {
                if inner.remove(&name).is_some() {
                    sealed.push(format!("arguments.{name}"));
                }
            }
        }
        (kept, sealed)
    }

    /// Record that `caller` asked for `request` in `workspace`, running at `route`, as `asked`
    /// names the asking. Recorded again, the invocation keeps who asked and when, and runs
    /// where it was handed on to.
    pub fn record(
        &self,
        caller: &Caller,
        asked: &Caller,
        request: &InvokeRequest,
        workspace: Option<&str>,
        route: Route,
    ) {
        self.recorded(caller, asked, request, workspace, route, None);
    }

    /// [`Self::record`] for an invocation that runs `retries` again: what a retry records beside
    /// what it runs.
    fn recorded(
        &self,
        caller: &Caller,
        asked: &Caller,
        request: &InvokeRequest,
        workspace: Option<&str>,
        route: Route,
        retries: Option<InvocationId>,
    ) {
        let id = request.invocation;
        let secret = self.answers_a_secret(request);
        let (mut journaled, sealed) = self.journaled(request);
        if secret {
            // What it was asked with may be as telling as what it answered; neither is kept.
            journaled.argument = InvokeArgument::None;
        }
        let recorded = Recorded {
            caller: caller.clone(),
            asked: asked.clone(),
            request: journaled,
            sealed,
            workspace: workspace.map(str::to_owned),
            started_ms: tilo_clock::unix_now_ms(),
            ended_ms: None,
            state: None,
            changes: 0,
            waiting: false,
            origin: origin_of(caller, request),
            retries,
            spend: None,
            undone: false,
            secret,
            route,
        };
        let mut kept = self.kept();
        if let Some(known) = kept.by_id.get_mut(&id) {
            known.route = recorded.route;
            return;
        }
        kept.by_id.insert(id, recorded);
        kept.order.push_back(id);
        while kept.order.len() > KEPT {
            if let Some(oldest) = kept.order.pop_front() {
                kept.by_id.remove(&oldest);
            }
        }
        let woken: Vec<ResourceWake> = match workspace {
            Some(workspace) => {
                let (woken, still) = std::mem::take(&mut kept.watching)
                    .into_iter()
                    .partition(|(watched, _)| watched == workspace);
                kept.watching = still;
                woken.into_iter().map(|(_, wake)| wake).collect()
            }
            None => Vec::new(),
        };
        drop(kept);
        for wake in woken {
            wake.wake();
        }
    }

    /// Whether `request`'s action answers a secret ([`Self::keep_secret_answers`]): kept out of
    /// every record of it, its answer and its arguments alike.
    fn answers_a_secret(&self, request: &InvokeRequest) -> bool {
        self.answers.get().map_or_else(
            || super::person_vault::answers_secret(request),
            |answers| answers(request),
        )
    }

    /// Wake `wake` once `workspace`'s invocations next change: another is recorded there, or
    /// one that has not ended changes at the provider it runs at. What a reader that follows a
    /// workspace's invocations waits on before it reads them again; watched before that read,
    /// so nothing recorded between the two is missed.
    pub fn watch(&self, workspace: &str, wake: &ResourceWake) {
        let going: Vec<(InvocationId, Route)> = {
            let mut kept = self.kept();
            kept.watching.retain(|(_, waiting)| waiting.waiting());
            kept.watching.push((workspace.to_owned(), wake.clone()));
            kept.by_id
                .iter()
                .filter(|(_, recorded)| {
                    recorded.workspace.as_deref() == Some(workspace) && recorded.ended_ms.is_none()
                })
                .map(|(id, recorded)| (*id, recorded.route.clone()))
                .collect()
        };
        for (id, (provider, runs_as)) in going {
            if let Some(changed) = provider.next_change(&runs_as, &id) {
                let wake = wake.clone();
                changed.then(move |_| wake.wake());
            }
        }
    }

    /// The record of `id`, as `caller` may read it: `None` when the device was not asked for it,
    /// or not by `caller` ([`Caller::continues`]): a call is followed and stopped by the caller
    /// that made it, never by another execution of the same person.
    #[must_use]
    pub fn get(&self, caller: &Caller, id: &InvocationId) -> Option<Recorded> {
        self.kept()
            .by_id
            .get(id)
            .filter(|recorded| caller.continues(&recorded.caller))
            .cloned()
    }

    /// How `id` stands, asked of the provider it runs at.
    #[must_use]
    pub fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState> {
        self.get(caller, id)?;
        self.refreshed(id)?.state
    }

    /// Every invocation this device was asked for in `workspace`, oldest first, its state asked
    /// again of the provider it runs at: what a listing of the workspace's invocations reads.
    ///
    /// This is the records alone, as the device keeps them. Which of them a caller may read is
    /// not decided here: the reader of a listing admits its caller and checks each record's
    /// address against what that caller's grants allow, before it reads this.
    #[must_use]
    pub fn listed(&self, workspace: &str) -> Vec<Recorded> {
        let ids: Vec<InvocationId> = {
            let kept = self.kept();
            kept.order
                .iter()
                .filter(|id| {
                    kept.by_id
                        .get(id)
                        .is_some_and(|recorded| recorded.workspace.as_deref() == Some(workspace))
                })
                .copied()
                .collect()
        };
        ids.iter().filter_map(|id| self.refreshed(id)).collect()
    }

    /// Note that the model call `id` made cost `spend`: what the model endpoint writes as it
    /// answers, so the listing says what a run paid for.
    pub fn note_spend(&self, id: &InvocationId, spend: Spend) {
        if let Some(recorded) = self.kept().by_id.get_mut(id) {
            recorded.spend = Some(spend);
        }
    }

    /// Forget what every record already kept of a secret answer: each of an action whose
    /// declaration answers a secret ([`Self::keep_secret_answers`]) keeps only that it was given.
    /// What the device's dispatch calls once it names them, so a record written before the
    /// declaration carried the tag holds none of the answer either.
    pub fn drop_secret_answers(&self) {
        let answers = self.answers.get();
        let mut kept = self.kept();
        for recorded in kept.by_id.values_mut() {
            let secret = recorded.secret
                || answers.is_some_and(|answers| answers(&recorded.request))
                || super::person_vault::answers_secret(&recorded.request);
            if secret {
                recorded.secret = true;
                recorded.request.argument = InvokeArgument::None;
                recorded.state = recorded.state.take().map(given);
            }
        }
    }

    /// Note that `id` answers a secret ([`crate::SECRET_ANSWER_TAG`]): its record forgets what
    /// it was asked with, and keeps of its answer only that it was given. The secret reaches its
    /// caller in the receipt alone.
    pub fn keep_secret(&self, id: &InvocationId) {
        if let Some(recorded) = self.kept().by_id.get_mut(id) {
            recorded.secret = true;
            recorded.request.argument = InvokeArgument::None;
            recorded.state = recorded.state.take().map(given);
        }
    }

    /// Note that `id` was answered as waiting for its person: the call goes on and ends once
    /// they decide.
    pub fn note_waiting(&self, id: &InvocationId) {
        if let Some(recorded) = self.kept().by_id.get_mut(id) {
            recorded.waiting = true;
        }
    }

    /// `id`'s record, its state asked of the provider it runs at and kept.
    fn refreshed(&self, id: &InvocationId) -> Option<Recorded> {
        let (provider, runs_as) = self.kept().by_id.get(id)?.route.clone();
        let state = provider.observe(&runs_as, id);
        let ended = state
            .as_ref()
            .is_some_and(|state| state.update.is_terminal());
        let mut kept = self.kept();
        let recorded = kept.by_id.get_mut(id)?;
        if recorded.state.as_ref() != state.as_ref() {
            recorded.changes = recorded.changes.saturating_add(1);
        }
        if ended && recorded.ended_ms.is_none() {
            recorded.ended_ms = Some(tilo_clock::unix_now_ms());
        }
        recorded.state = if recorded.secret {
            state.map(given)
        } else {
            state
        };
        let recorded = recorded.clone();
        drop(kept);
        Some(recorded)
    }

    /// What resolves when `id` next changes, at the provider it runs at.
    #[must_use]
    pub fn next_change(&self, caller: &Caller, id: &InvocationId) -> Option<Pending<()>> {
        let (provider, runs_as) = self.get(caller, id)?.route;
        provider.next_change(&runs_as, id)
    }

    /// The answer to `request` when it asks one of [`PROVIDER`]'s invocations to stop
    /// ([`CANCEL`]), to run again ([`RETRY`]), or to take back what it changed ([`UNDO`]): the
    /// invocation is the resource, by its id. `None` for any other request, a read included: a
    /// record is read through the record API, never as an action.
    ///
    /// A call is stopped, run again or taken back by its caller, by the person its agent works
    /// for, or by whoever `may_write_origin` says may write the resource it was made from.
    /// Anyone else is refused in words a person reads.
    #[must_use]
    pub fn answer(
        self: &Arc<Self>,
        caller: &Caller,
        request: &InvokeRequest,
        may_write_origin: &OriginWrites<'_>,
    ) -> Option<Pending<Result<InvocationReceipt, ActionCallError>>> {
        let target = &request.target;
        let action = target.address.action.as_str();
        if target.provider != PROVIDER || ![CANCEL, RETRY, UNDO].contains(&action) {
            return None;
        }
        let Some(id) = uuid::Uuid::parse_str(&target.address.resource)
            .ok()
            .map(InvocationId)
        else {
            return Some(Pending::ready(Err(ActionCallError::UnknownInvocation)));
        };
        let Some(recorded) = self.find(&id) else {
            return Some(Pending::ready(Err(ActionCallError::UnknownInvocation)));
        };
        if !Self::may_manage(caller, &recorded, may_write_origin) {
            let verb = match action {
                RETRY => "run it again",
                UNDO => "take it back",
                _ => "stop it",
            };
            return Some(Pending::ready(Err(refused(verb, recorded.origin.as_ref()))));
        }
        if action == RETRY {
            return Some(Self::retry(self, &recorded, request.invocation));
        }
        if action == UNDO {
            let asked = request.invocation;
            let taken = Self::take_back_recorded(self, &recorded);
            let (complete, answer) = pending();
            taken.then(move |done| {
                complete.complete(match done {
                    Some(Ok(())) => Ok(InvocationReceipt {
                        invocation: asked,
                        status: ReceiptStatus::Completed {
                            output: crate::ActionOutput::default(),
                        },
                    }),
                    Some(Err(error)) => Err(error),
                    None => Err(ActionCallError::Unavailable {
                        reason: "the record did not answer".into(),
                    }),
                });
            });
            return Some(answer);
        }
        let (provider, runs_as) = recorded.route;
        let invocation = request.invocation;
        Some(provider.cancel(&runs_as, &id).map(move |stopped| {
            stopped.map(|()| InvocationReceipt {
                invocation,
                status: ReceiptStatus::Completed {
                    output: crate::ActionOutput::default(),
                },
            })
        }))
    }

    /// Take back what one record's invocation changed, and say so of the record.
    fn take_back_recorded(
        records: &Arc<Self>,
        recorded: &Recorded,
    ) -> Pending<Result<(), ActionCallError>> {
        if recorded.undone {
            return Pending::ready(Err(already_taken_back()));
        }
        let id = recorded.request.invocation;
        let at = recorded.request.target.provider.clone();
        let run = id.0.to_string();
        let (complete, answer) = pending();
        let records = Arc::clone(records);
        take_back_run(&recorded.route, &at, None, &run, None).then(move |done| {
            let result = match done {
                None => Err(ActionCallError::Unavailable {
                    reason: "the record did not answer".into(),
                }),
                Some(Err(error)) => Err(error),
                Some(Ok(())) => {
                    records.mark_undone(&id);
                    Ok(())
                }
            };
            complete.complete(result);
        });
        answer
    }

    /// Note that what `id` changed was taken back.
    fn mark_undone(&self, id: &InvocationId) {
        if let Some(recorded) = self.kept().by_id.get_mut(id) {
            recorded.undone = true;
        }
    }

    /// Run `recorded`'s action again under a new invocation id, as the caller that made it and
    /// with the same arguments and on-behalf-of, at the provider it ran at. The new record says
    /// it retries the old one, and the answer to `asked` names the new record's address. A
    /// request its caller signed on another device binds its first id and is not signed again
    /// here: the caller asks for it again from there.
    fn retry(
        records: &Arc<Self>,
        recorded: &Recorded,
        asked: InvocationId,
    ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
        if recorded.request.signed.is_some() {
            return Pending::ready(Err(ActionCallError::Refused {
                reason: "it was asked for from another device: run it again from there".to_owned(),
            }));
        }
        // Run again without what it was asked with, it would not be the call it was.
        if !recorded.sealed.is_empty() {
            return Pending::ready(Err(ActionCallError::Refused {
                reason: NOT_KEPT.to_owned(),
            }));
        }
        let original = recorded.request.invocation;
        let mut request = recorded.request.clone();
        request.invocation = InvocationId::new();
        let fresh = request.invocation;
        records.recorded(
            &recorded.caller,
            &recorded.asked,
            &request,
            recorded.workspace.as_deref(),
            recorded.route.clone(),
            Some(original),
        );
        let (provider, runs_as) = recorded.route.clone();
        let waiting = Arc::clone(records);
        provider.invoke(&runs_as, request).map(move |result| {
            if result
                .as_ref()
                .err()
                .is_some_and(ActionCallError::awaits_person)
            {
                waiting.note_waiting(&fresh);
            }
            result.map(|_| InvocationReceipt {
                invocation: asked,
                status: ReceiptStatus::Completed {
                    output: crate::ActionOutput {
                        value: Some(serde_json::json!({
                            "invocation": fresh.0.to_string(),
                            "address": format!("{PROVIDER}/{}", fresh.0),
                            "retries": original.0.to_string(),
                        })),
                        ..crate::ActionOutput::default()
                    },
                },
            })
        })
    }

    /// The record of `id`, whoever asked for it: what stopping or running it again reads before
    /// it decides who may.
    fn find(&self, id: &InvocationId) -> Option<Recorded> {
        self.kept().by_id.get(id).cloned()
    }

    /// Whether `caller` may stop `recorded` or run it again: it is its caller
    /// ([`Caller::continues`]), the person the agent that made it works for, or someone who may
    /// write the resource it was made from, as `may_write_origin` reads it now.
    fn may_manage(
        caller: &Caller,
        recorded: &Recorded,
        may_write_origin: &OriginWrites<'_>,
    ) -> bool {
        caller.continues(&recorded.caller)
            || agent_person_is(caller, &recorded.caller)
            || recorded
                .origin
                .as_ref()
                .is_some_and(|origin| may_write_origin(caller, origin))
    }

    /// Stop every call still running in `workspace` that the agent `agent` made, as `caller`
    /// (the person the agent works for) asks: each at the provider it runs at, through
    /// [`Self::cancel`], and only those `caller` may manage.
    #[must_use]
    pub fn stop_agent(
        &self,
        caller: &Caller,
        workspace: &str,
        agent: &tilo_action_policy::MemberId,
        may_write_origin: &OriginWrites<'_>,
    ) -> Vec<Pending<Result<(), ActionCallError>>> {
        let ids: Vec<InvocationId> = {
            let kept = self.kept();
            kept.order
                .iter()
                .filter_map(|id| {
                    let recorded = kept.by_id.get(id)?;
                    if recorded.workspace.as_deref() != Some(workspace)
                        || recorded.ended_ms.is_some()
                        || recorded.caller.acting().member_id() != Some(agent)
                    {
                        return None;
                    }
                    Some(*id)
                })
                .collect()
        };
        ids.into_iter()
            .filter_map(|id| self.cancel(caller, &id, may_write_origin))
            .collect()
    }

    /// Stop `id` at the provider it runs at, for a caller that may manage it. `None` when the
    /// device was asked for no such invocation.
    #[must_use]
    pub fn cancel(
        &self,
        caller: &Caller,
        id: &InvocationId,
        may_write_origin: &OriginWrites<'_>,
    ) -> Option<Pending<Result<(), ActionCallError>>> {
        let recorded = self.find(id)?;
        if !Self::may_manage(caller, &recorded, may_write_origin) {
            return Some(Pending::ready(Err(refused(
                "stop it",
                recorded.origin.as_ref(),
            ))));
        }
        let (provider, runs_as) = recorded.route;
        Some(provider.cancel(&runs_as, id))
    }
}

/// Take back what the run `run` changed, through the record's own history: `at` is the provider
/// whose record holds the changes, and `root` the address prefix of the history action there
/// when the provider keeps many records (a session's own services), `None` when it keeps one.
/// `step` names the one change of that record to take back, as the record's own history names
/// it; absent to take back the run's whole share of the record.
///
/// The store's change history knows which changes a run made, so nothing is rebuilt here: the
/// record publishes the history verb `undo` with an `invocation` argument, and this runs it as
/// the route's caller. `#undo` and a decline both ask it, keyed by the invocation.
pub fn take_back_run(
    route: &Route,
    at: &str,
    root: Option<&str>,
    run: &str,
    step: Option<&str>,
) -> Pending<Result<(), ActionCallError>> {
    let (provider, runs_as) = route.clone();
    let query = CatalogueQuery {
        provider: Some(at.to_owned()),
        needle: UNDO.to_owned(),
        max_results: MAX_CATALOGUE_PAGE,
        ..CatalogueQuery::default()
    };
    let run = run.to_owned();
    let step = step.map(str::to_owned);
    let root = root.map(str::to_owned);
    let (complete, answer) = pending();
    provider.query(&runs_as, query).then(move |page| {
        let found = match page {
            None => Err(ActionCallError::Unavailable {
                reason: "the record did not answer".into(),
            }),
            Some(Err(error)) => Err(error),
            Some(Ok(page)) => {
                undo_action(&page.rows, root.as_deref()).ok_or_else(|| ActionCallError::Refused {
                    reason: NO_HISTORY.to_owned(),
                })
            }
        };
        let (token, address) = match found {
            Ok(found) => found,
            Err(error) => {
                complete.complete(Err(error));
                return;
            }
        };
        let mut arguments = serde_json::Map::new();
        arguments.insert("invocation".to_owned(), serde_json::Value::String(run));
        if let Some(step) = step {
            arguments.insert("step".to_owned(), serde_json::Value::String(step));
        }
        let request = InvokeRequest {
            invocation: InvocationId::new(),
            target: RemoteActionTarget {
                provider: token,
                address,
            },
            argument: InvokeArgument::Json(arguments),
            context: None,
            confirmation: None,
            revision: None,
            on_behalf_of: None,
            wait_ms: None,
            appearance: None,
            signed: None,
        };
        provider.invoke(&runs_as, request).then(move |answered| {
            complete.complete(match answered {
                None => Err(ActionCallError::Unavailable {
                    reason: "the record did not answer".into(),
                }),
                Some(Ok(receipt)) => taken(receipt.status),
                Some(Err(error)) => Err(error),
            });
        });
    });
    answer
}

/// The `undo` action `rows` offer that takes an invocation back, its provider and address:
/// the one whose history lies at `root` when `root` names a prefix, preferring a verb that
/// names the invocation it takes.
fn undo_action(
    rows: &[super::CatalogueRow],
    root: Option<&str>,
) -> Option<(String, crate::ActionAddress)> {
    let mut fallback = None;
    for row in rows {
        let Some(action) = &row.action else {
            continue;
        };
        if action.address.action != UNDO {
            continue;
        }
        if root.is_some_and(|root| !action.address.resource.starts_with(root)) {
            continue;
        }
        if action.params.iter().any(|param| param.name == "invocation") {
            return Some((row.provider.clone(), action.address.clone()));
        }
        fallback.get_or_insert_with(|| (row.provider.clone(), action.address.clone()));
    }
    fallback
}

/// How taking back ended.
fn taken(status: ReceiptStatus) -> Result<(), ActionCallError> {
    match status {
        ReceiptStatus::Completed { .. } => Ok(()),
        ReceiptStatus::Failed { error } => Err(ActionCallError::Refused {
            reason: error.message,
        }),
        ReceiptStatus::Rejected { error } => Err(error),
        ReceiptStatus::Cancelled { .. } => Err(ActionCallError::Refused {
            reason: "taking it back was stopped".into(),
        }),
        ReceiptStatus::Accepted => Err(ActionCallError::Unavailable {
            reason: "taking it back is still running".into(),
        }),
    }
}

/// Why an invocation whose changes are gone is not taken back again.
fn already_taken_back() -> ActionCallError {
    ActionCallError::Refused {
        reason: "what this invocation changed is already taken back".into(),
    }
}

/// The resource `caller` made `request` from, when the call named one: its `$from`, else the
/// conversation the caller's turn belongs to.
fn origin_of(caller: &Caller, request: &InvokeRequest) -> Option<Origin> {
    if let InvokeArgument::Json(arguments) = &request.argument
        && let Some(from) = arguments
            .get(crate::params::FROM_ARGUMENT)
            .and_then(crate::params::MadeFrom::from_json)
        && let Some(origin) = Origin::parse(&from.resource, Some(&from.kind))
    {
        return Some(origin);
    }
    caller
        .turn()
        .and_then(|turn| Origin::parse(&turn.conversation, None))
}

/// Whether `caller` is the person `owner` works for, when `owner` is an agent's caller.
fn agent_person_is(caller: &Caller, owner: &Caller) -> bool {
    let Some(person) = owner.acting_for_person() else {
        return false;
    };
    let acting = caller.acting();
    acting.person_id() == Some(person)
        && !acting.is_agent()
        && !acting.is_bot()
        && acting.app().is_none()
}

/// Why `caller` may not `verb` an invocation: who may, and the resource that decides it.
fn refused(verb: &str, origin: Option<&Origin>) -> ActionCallError {
    let may = match origin {
        Some(origin) => format!(
            "the caller who made this invocation, the person its agent works for, or someone \
             who may write {} may",
            origin.address()
        ),
        None => {
            "the caller who made this invocation, or the person its agent works for, may".to_owned()
        }
    };
    ActionCallError::Refused {
        reason: format!("only {may} {verb}"),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicBool, Ordering};

    use super::*;
    use crate::remote::{
        CataloguePage, CatalogueQuery, InvokeArgument, PendingPoll, RemoteActionTarget,
    };
    use crate::{ActionOutput, InvocationUpdate};

    /// A host that runs every invocation until it is stopped, and whose record takes a run's
    /// writes back through its own history `undo`.
    #[derive(Default)]
    struct Runs {
        stopped: AtomicBool,
        /// The writes still in effect, each by the invocation it was one of, oldest first.
        written: Mutex<Vec<(String, String)>>,
    }

    impl Runs {
        /// The writes the invocation `id` made, as the record keeps them.
        fn writes(&self, id: &InvocationId) -> Vec<String> {
            self.written
                .lock()
                .unwrap()
                .iter()
                .filter(|(of, _)| of == &id.0.to_string())
                .map(|(_, what)| what.clone())
                .collect()
        }
    }

    impl ActionProvider for Runs {
        fn query(
            &self,
            _: &Caller,
            query: CatalogueQuery,
        ) -> Pending<Result<CataloguePage, ActionCallError>> {
            let mut page = CataloguePage::default();
            if query.provider.as_deref() == Some("terminal") {
                page.rows.push(super::super::CatalogueRow::for_action(
                    "terminal",
                    "terminal",
                    crate::ActionDescriptor {
                        address: crate::ActionAddress::new("tl:terminal:", UNDO),
                        semantic_identity: None,
                        resource_kind: "terminal".into(),
                        resource_label: "Terminal".into(),
                        action_label: "Undo".into(),
                        keywords: Vec::new(),
                        did: None,
                        icon: None,
                        description: None,
                        state: crate::ActionState::default(),
                        locus: crate::ExecutionLocus::ClientLocal,
                        kind: crate::OperationKind::Effect,
                        contract: crate::ActionContract::default(),
                        input: crate::InputSpec::None,
                        params: vec![crate::ActionParam::optional(
                            "invocation",
                            crate::ParamType::Text,
                            "The invocation whose changes are taken back.",
                        )],
                        view: None,
                    },
                ));
            }
            Pending::ready(Ok(page))
        }

        fn invoke(
            &self,
            _: &Caller,
            request: InvokeRequest,
        ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
            if request.target.address.action != UNDO {
                return Pending::ready(Err(ActionCallError::UnknownAction));
            }
            let InvokeArgument::Json(arguments) = &request.argument else {
                return Pending::ready(Err(ActionCallError::InvalidRequest {
                    reason: "the undo names no invocation".into(),
                }));
            };
            let named = arguments
                .get("invocation")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default();
            // The store's history knows which changes the run made: exactly those go.
            self.written.lock().unwrap().retain(|(of, _)| of != named);
            Pending::ready(Ok(InvocationReceipt {
                invocation: request.invocation,
                status: ReceiptStatus::Completed {
                    output: ActionOutput::default(),
                },
            }))
        }

        fn observe(&self, _: &Caller, id: &InvocationId) -> Option<InvocationState> {
            let update = if self.stopped.load(Ordering::SeqCst) {
                InvocationUpdate::Succeeded {
                    invocation: *id,
                    output: ActionOutput::default(),
                }
            } else {
                InvocationUpdate::Accepted { invocation: *id }
            };
            Some(InvocationState::new(*id, update))
        }

        fn cancel(&self, _: &Caller, _: &InvocationId) -> Pending<Result<(), ActionCallError>> {
            self.stopped.store(true, Ordering::SeqCst);
            Pending::ready(Ok(()))
        }
    }

    fn request() -> InvokeRequest {
        InvokeRequest {
            invocation: InvocationId::new(),
            target: RemoteActionTarget {
                provider: "terminal".into(),
                address: crate::ActionAddress::new("terminal", "run"),
            },
            argument: InvokeArgument::Text("make".into()),
            context: None,
            confirmation: None,
            revision: None,
            on_behalf_of: None,
            wait_ms: None,
            appearance: None,
            signed: None,
        }
    }

    /// The request of one of a record's actions: stopping it, running it again, taking it back.
    fn record_action(id: &InvocationId, action: &str) -> InvokeRequest {
        let mut request = request();
        request.invocation = InvocationId::new();
        request.target = RemoteActionTarget {
            provider: PROVIDER.into(),
            address: crate::ActionAddress::new(id.0.to_string(), action),
        };
        request.argument = InvokeArgument::None;
        request
    }

    /// Record two writes of the run `id` in `runs`' history, as an action it ran made them.
    fn made(runs: &Runs, id: &InvocationId, first: &str, second: &str) {
        let mut written = runs.written.lock().unwrap();
        written.push((id.0.to_string(), first.to_owned()));
        written.push((id.0.to_string(), second.to_owned()));
    }

    /// How `answer` took a record action: ready, without a provider to wait on.
    fn answered(
        invocations: &Arc<Invocations>,
        caller: &Caller,
        request: &InvokeRequest,
        never: &OriginWrites<'_>,
    ) -> Result<InvocationReceipt, ActionCallError> {
        invocations
            .answer(caller, request, never)
            .expect("the record answers its own action")
            .poll_ready()
            .ready()
    }

    trait Ready<T> {
        fn ready(self) -> T;
    }

    impl<T: std::fmt::Debug> Ready<T> for PendingPoll<T> {
        fn ready(self) -> T {
            match self {
                PendingPoll::Ready(value) => value,
                other => panic!("the answer was ready, not {other:?}"),
            }
        }
    }

    /// A call is recorded as every call is, and its record keeps none of the arguments its
    /// action declares secret: not the secret, not the note, not a field's value. What is safe
    /// to say of it stays.
    #[test]
    fn a_call_is_recorded_without_what_its_action_declares_secret() {
        let invocations = Arc::new(Invocations::default());
        let params = [
            crate::ActionParam::required("kind", crate::ParamType::Text, "kind"),
            crate::ActionParam::required("title", crate::ParamType::Text, "title"),
            crate::ActionParam::required("secret", crate::ParamType::Secret, "secret"),
            crate::ActionParam::optional("notes", crate::ParamType::Secret, "notes"),
            crate::ActionParam::optional("fields", crate::ParamType::Secret, "fields"),
        ];
        let target = super::super::person_vault::target(super::super::person_vault::ADD);
        let described = target.clone();
        // The registry's own `call` is described too: its address and arguments are no secrets.
        invocations.keep_no_secrets(Arc::new(move |asked: &RemoteActionTarget| {
            if asked.provider == crate::remote::ACTIONS_PROVIDER {
                return Some(Vec::new());
            }
            (*asked == described)
                .then(|| super::super::secret_arguments::secret_parameters(&params))
        }));
        let asked = Caller::local_person("ada").in_new_execution();
        let mut request = request();
        request.target = target;
        let serde_json::Value::Object(arguments) = serde_json::json!({
            "kind": "login",
            "belongsTo": ["https://bank.example"],
            "title": "Bank",
            "secret": "made-up-password-0451",
            "notes": "made-up-recovery-words",
            "fields": [{"label": "PIN", "value": "made-up-pin-7351"}],
        }) else {
            unreachable!("an object");
        };
        // Passwords' code calls the same add by its address, through the action registry.
        let mut called = request.clone();
        called.invocation = InvocationId::new();
        called.target = RemoteActionTarget {
            provider: crate::remote::ACTIONS_PROVIDER.to_owned(),
            address: crate::ActionAddress::new("actions", "call"),
        };
        let mut by_address = serde_json::Map::new();
        by_address.insert("address".into(), "tilo.vault/vault#add".into());
        by_address.insert("arguments".into(), arguments.clone().into());
        called.argument = InvokeArgument::Json(by_address);
        request.argument = InvokeArgument::Json(arguments);
        let runs = Arc::new(Runs::default());
        invocations.record(&asked, &asked, &request, Some("w1"), (runs, asked.clone()));
        let runs = Arc::new(Runs::default());
        invocations.record(&asked, &asked, &called, Some("w1"), (runs, asked.clone()));
        let kept = invocations.get(&asked, &request.invocation).unwrap();
        let kept_call = invocations.get(&asked, &called.invocation).unwrap();
        let written = serde_json::to_string(&kept.request).unwrap()
            + &serde_json::to_string(&kept_call.request).unwrap()
            + &invocations
                .listed("w1")
                .iter()
                .map(|listed| serde_json::to_string(&listed.request).unwrap())
                .collect::<String>();
        for secret in [
            "made-up-password-0451",
            "made-up-recovery-words",
            "made-up-pin-7351",
        ] {
            assert!(!written.contains(secret), "{written}");
        }
        assert!(written.contains("https://bank.example"), "{written}");
        assert!(written.contains("Bank"), "{written}");
    }

    /// A call of an action described nowhere on the device is recorded with none of what it
    /// was asked with, its text included, only the names of what it left out; run again from
    /// its record, it is refused, saying to ask for it again.
    #[test]
    fn a_call_of_an_undescribed_action_is_recorded_without_its_arguments() {
        let invocations = Arc::new(Invocations::default());
        invocations.keep_no_secrets(Arc::new(|_: &RemoteActionTarget| None));
        let asked = Caller::local_person("ada").in_new_execution();
        let mut request = request();
        request.argument = InvokeArgument::Text("made-up-passphrase-3317".into());
        let id = request.invocation;
        let runs = Arc::new(Runs::default());
        invocations.record(&asked, &asked, &request, Some("w1"), (runs, asked.clone()));
        let kept = invocations.get(&asked, &id).unwrap();
        assert_eq!(kept.request.argument, InvokeArgument::None);
        assert_eq!(kept.sealed, [super::super::secret_arguments::TEXT_ARGUMENT]);
        let listed = invocations
            .listed("w1")
            .iter()
            .map(|listed| serde_json::to_string(&listed.request).unwrap())
            .collect::<String>();
        assert!(!listed.contains("made-up-passphrase-3317"), "{listed}");
        let never = |_: &Caller, _: &Origin| false;
        match answered(&invocations, &asked, &record_action(&id, RETRY), &never) {
            Err(ActionCallError::Refused { reason }) => assert_eq!(reason, NOT_KEPT),
            other => panic!("run again without what it was asked with: {other:?}"),
        }
    }

    /// A vault reveal and a cloud mount's sign-in answer secrets, asked of their provider or
    /// through the action registry by address, so their records keep only that they were
    /// answered.
    #[test]
    fn a_vault_reveal_is_recorded_as_answering_a_secret() {
        use super::super::{person_accounts, person_vault};
        let invocations = Arc::new(Invocations::default());
        let asked = Caller::local_person("ada").in_new_execution();
        let mut reveal = request();
        reveal.target = person_vault::target(person_vault::REVEAL);
        let mut credential = request();
        credential.target = person_accounts::target(person_accounts::CLOUD_CREDENTIAL);
        let serde_json::Value::Object(signing_in) = serde_json::json!({
            "account": "files-1",
        }) else {
            unreachable!("an object");
        };
        credential.argument = InvokeArgument::Json(signing_in);
        let mut called = request();
        called.target = RemoteActionTarget {
            provider: "tilo.actions".to_owned(),
            address: crate::ActionAddress::new("actions", "call"),
        };
        let serde_json::Value::Object(arguments) = serde_json::json!({
            "address": "tilo.workspace/workspace.permissions:w1/vault#reveal",
            "arguments": {"item": "vault.item:00"},
        }) else {
            unreachable!("an object");
        };
        called.argument = InvokeArgument::Json(arguments);
        let mut called_credential = called.clone();
        called_credential.invocation = InvocationId::new();
        let serde_json::Value::Object(signing_in_call) = serde_json::json!({
            "address": "tilo.accounts/accounts#cloud-credential",
            "arguments": {"account": "files-1"},
        }) else {
            unreachable!("an object");
        };
        called_credential.argument = InvokeArgument::Json(signing_in_call);
        let mut listed = called.clone();
        listed.invocation = InvocationId::new();
        let serde_json::Value::Object(listing) = serde_json::json!({
            "address": "tilo.workspace/workspace.permissions:w1/vault#list",
        }) else {
            unreachable!("an object");
        };
        listed.argument = InvokeArgument::Json(listing);
        for (request, secret) in [
            (&reveal, true),
            (&credential, true),
            (&called, true),
            (&called_credential, true),
            (&listed, false),
        ] {
            assert_eq!(person_vault::answers_secret(request), secret);
            let runs = Arc::new(Runs::default());
            invocations.record(&asked, &asked, request, Some("w1"), (runs, asked.clone()));
            let kept = invocations.get(&asked, &request.invocation).unwrap();
            assert_eq!(kept.secret, secret, "{:?}", request.target);
            if secret {
                assert_eq!(
                    kept.request.argument,
                    InvokeArgument::None,
                    "{:?} keeps none of what it was asked with",
                    request.target
                );
            }
        }
    }

    #[test]
    fn an_invocation_takes_back_the_writes_its_run_made() {
        let invocations = Arc::new(Invocations::default());
        let never = |_: &Caller, _: &Origin| false;
        let asked = Caller::local_person("ada").in_new_execution();
        let request = request();
        let id = request.invocation;
        let runs = Arc::new(Runs::default());
        invocations.record(
            &asked,
            &asked,
            &request,
            Some("w1"),
            (runs.clone(), asked.clone()),
        );
        made(&runs, &id, "Shipping notes.", " Sent.");
        assert_eq!(runs.writes(&id).len(), 2, "the run made two writes");

        let undone = answered(&invocations, &asked, &record_action(&id, UNDO), &never)
            .expect("its caller takes it back");
        assert!(matches!(undone.status, ReceiptStatus::Completed { .. }));
        assert!(
            runs.writes(&id).is_empty(),
            "both writes the run made are taken back"
        );
        assert!(
            invocations.get(&asked, &id).unwrap().undone,
            "the record says what it changed was taken back"
        );
    }

    #[test]
    fn someone_who_may_not_manage_the_run_is_refused_in_words() {
        let invocations = Arc::new(Invocations::default());
        let never = |_: &Caller, _: &Origin| false;
        let asked = Caller::local_person("ada").in_new_execution();
        let request = request();
        let id = request.invocation;
        let runs = Arc::new(Runs::default());
        invocations.record(
            &asked,
            &asked,
            &request,
            Some("w1"),
            (runs.clone(), asked.clone()),
        );
        made(&runs, &id, "Shipping notes.", " Sent.");

        let stranger = Caller::local_person("bob").in_new_execution();
        let refused = answered(&invocations, &stranger, &record_action(&id, UNDO), &never)
            .expect_err("a stranger is refused");
        let ActionCallError::Refused { reason } = &refused else {
            panic!("a stranger is refused in words, not {refused:?}");
        };
        assert!(
            reason.starts_with("only the caller who made this invocation"),
            "{reason}"
        );
        assert!(
            reason.ends_with("take it back"),
            "the refusal names what they may not do: {reason}"
        );
        assert_eq!(runs.writes(&id).len(), 2, "nothing was taken back");
    }

    #[test]
    fn taking_an_invocation_back_twice_is_refused_in_words() {
        let invocations = Arc::new(Invocations::default());
        let never = |_: &Caller, _: &Origin| false;
        let asked = Caller::local_person("ada").in_new_execution();
        let request = request();
        let id = request.invocation;
        let runs = Arc::new(Runs::default());
        invocations.record(
            &asked,
            &asked,
            &request,
            Some("w1"),
            (runs.clone(), asked.clone()),
        );
        made(&runs, &id, "Shipping notes.", " Sent.");
        answered(&invocations, &asked, &record_action(&id, UNDO), &never)
            .expect("the first takes it back");

        let refused = answered(&invocations, &asked, &record_action(&id, UNDO), &never)
            .expect_err("the second is refused");
        let ActionCallError::Refused { reason } = &refused else {
            panic!("a second undo is a refusal in words, not {refused:?}");
        };
        assert_eq!(
            reason, "what this invocation changed is already taken back",
            "a person reads what stands"
        );
    }

    #[test]
    fn an_invocations_person_takes_back_a_run_of_its_agents() {
        let invocations = Arc::new(Invocations::default());
        let never = |_: &Caller, _: &Origin| false;
        let agent = Caller::local_agent("scout", "ada");
        let request = request();
        let id = request.invocation;
        let runs = Arc::new(Runs::default());
        invocations.record(
            &agent,
            &agent,
            &request,
            Some("w1"),
            (runs.clone(), agent.clone()),
        );
        made(&runs, &id, "Shipping notes.", " Sent.");

        let person = Caller::local_person("ada").in_new_execution();
        answered(&invocations, &person, &record_action(&id, UNDO), &never)
            .expect("the person the agent works for takes it back");
        assert!(
            runs.writes(&id).is_empty(),
            "both of the agent's writes went"
        );
    }

    #[test]
    fn an_invocation_is_followed_and_stopped_where_it_was_handed_on_to() {
        let invocations = Arc::new(Invocations::default());
        let never = |_: &Caller, _: &Origin| false;
        let asked = Caller::local_person("ada").in_new_execution();
        let request = request();
        let id = request.invocation;
        let here: Arc<Runs> = Arc::default();
        invocations.record(&asked, &asked, &request, Some("w1"), (here, asked.clone()));
        // Handed on to the workspace's host, which runs it as the workspace's caller.
        let there: Arc<Runs> = Arc::default();
        let runs_as = Caller::local_agent("host", "ada");
        invocations.record(
            &asked,
            &asked,
            &request,
            Some("w1"),
            (Arc::clone(&there) as _, runs_as),
        );

        // Its caller follows it where it runs; someone else, or another execution of the same
        // person, reads nothing of it.
        let running = invocations
            .observe(&asked, &id)
            .expect("its caller follows it");
        assert!(!running.update.is_terminal());
        for stranger in [
            Caller::local_person("bob"),
            asked.clone().in_new_execution(),
        ] {
            assert!(invocations.observe(&stranger, &id).is_none());
            assert!(matches!(
                invocations
                    .cancel(&stranger, &id, &never)
                    .expect("the device knows it")
                    .poll_ready(),
                PendingPoll::Ready(Err(ActionCallError::Refused { .. }))
            ));
        }

        let stopped = invocations
            .cancel(&asked, &id, &never)
            .expect("its caller stops it");
        let mut stopped = std::pin::pin!(stopped);
        let answered = std::future::Future::poll(
            stopped.as_mut(),
            &mut std::task::Context::from_waker(std::task::Waker::noop()),
        );
        assert_eq!(answered, std::task::Poll::Ready(Some(Ok(()))));
        assert!(
            there.stopped.load(Ordering::SeqCst),
            "stopped where it runs"
        );
        let ended = invocations.observe(&asked, &id).unwrap();
        assert!(ended.update.is_terminal());
        let recorded = invocations.get(&asked, &id).unwrap();
        assert_eq!(recorded.workspace.as_deref(), Some("w1"));
        assert_eq!(recorded.caller, asked, "who asked stays who asked");
        assert!(recorded.ended_ms.is_some());
        assert_eq!(recorded.changes, 2);

        // A record is read through the record API, never as one of its actions: what a model
        // call it made cost is what the reading carries.
        let mut get = request.clone();
        get.invocation = InvocationId::new();
        get.target = RemoteActionTarget {
            provider: PROVIDER.into(),
            address: crate::ActionAddress::new(id.0.to_string(), "get"),
        };
        assert!(
            invocations.answer(&asked, &request, &never).is_none(),
            "not one of its actions"
        );
        assert!(
            invocations.answer(&asked, &get, &never).is_none(),
            "a record is no action's to read"
        );
        invocations.note_spend(
            &id,
            Spend {
                provider: Some("Models".into()),
                model: Some("judge-small".into()),
                input_tokens: 3,
                output_tokens: 2,
                cost_micros: 4321,
            },
        );
        let spent = invocations.get(&asked, &id).unwrap().spend.unwrap();
        assert_eq!(spent.cost_micros, 4321);
    }
}