printobserver-server 0.12.0

The printobserver server.
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
//! Every declared operation, against the real machine and the real harness.
//!
//! One walk rather than several tests, because every step acts on one shared
//! machine and the order they run in is part of what is proven: an adjustment
//! needs a running print, a resume needs a paused one, and a cancel ends the
//! print the steps before it needed. A runner free to interleave them would be
//! proving something else.
//!
//! # Where each operation's effect is confirmed
//!
//! Seven of the eleven actions have a read-back at the machine — start, pause,
//! resume, cancel, the two heater targets and the acknowledgement that stops a
//! print — and are confirmed by a status read afterwards. Three have none:
//! `OctoPrint` reports neither an applied feedrate factor nor an applied
//! flowrate factor nor a fan setting. For those the observable is **what the
//! instance received**, read out of a recording proxy that forwards every
//! request verbatim to the real machine — so what was recorded is what the
//! machine ruled on rather than what this server believed it sent. The value
//! each is asserted to carry is computed with the adapter's own exported
//! conversion, because the number on the wire is that adapter's business and no
//! crate but that adapter may spell one.
//!
//! The eleventh, `close_print`, closes a record the machine has finished with,
//! and this walk's machine is never idle under an open record: a read ends one
//! the moment its job is over. So what is proven of it here is what the real
//! machine makes it refuse — a record whose job is running, and a record a
//! cancel already ended — and its acceptance is the command-line journeys'.

use printobserver_core::AgentAssessmentPayload;
use printobserver_obico::ObicoFailureAlertPayload;
use printobserver_octoprint::{
    FAN_PWM_PARAMETER, FAN_SET_COMMAND, fan_pwm_of_percent, percent_of_multiplier,
};
use printobserver_server::StartupReconciliationPayload;
use printobserver_server::{Effect, OPERATIONS, Operation};
use printobserver_supervisor_api::SupervisionSessionOpenedPayload;
use printobserver_types::serde_json::{Value, json};
use printobserver_types::{EventKind, EventPayload as _, PrintId};

use crate::composition::{
    AGENT_DURATION_S, AGENT_FACTOR, AGENT_REFUSED_FACTOR, Composed, NARROWED, SECRET,
    hold_the_print_running,
};
use crate::http_host::image_host;
use crate::proxy::Proxy;
use crate::scripted::Scripted;
use crate::waiting::until;

/// The file the scripted environment uploads and this walk starts.
const HOLD_FILE: &str = "hold.gcode";

/// Obico's own identifier for the print this walk's alerts are about.
const OBICO_PRINT: i64 = 4211;

/// How long a bounded adjustment stands for, in the step that bounds one.
const DURATION_S: i64 = 600;

/// The bytes this walk's own image host serves.
fn snapshot_bytes() -> Vec<u8> {
    // A recorded frame of a real print: a camera frame is judged before it is
    // kept, and bytes that are no picture are refused as the camera degraded.
    let frame =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/recorded-frame.jpg");
    std::fs::read(&frame).expect("the recorded frame reads")
}

/// The committed `Obico` failure alert, naming an image host this walk serves.
fn alert_body(image_url: &str) -> String {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../printobserver-obico/samples/obico/failure-alert.json");
    let mut sample: Value = printobserver_types::serde_json::from_str(
        &std::fs::read_to_string(&path).expect("the committed sample reads"),
    )
    .expect("the committed sample is JSON");
    sample["print"]["id"] = json!(OBICO_PRINT);
    // The job the bring-up started, named by the file the printer reports: that
    // is what joins this alert to the print a listing adopted for the job.
    sample["print"]["filename"] = json!(HOLD_FILE);
    sample["img_url"] = json!(image_url);
    sample.to_string()
}

/// One body carrying a reason and an operator, plus whatever else is given.
fn body(extra: &[(&str, Value)]) -> Value {
    let mut body = json!({ "reason": "the integration tier is asking", "actor": "operator" });
    let object = body.as_object_mut().expect("the body is an object");
    for (name, value) in extra {
        object.insert((*name).to_owned(), value.clone());
    }
    body
}

/// The same body, claiming the agent — which this tier's credential, the
/// operator's, is not.
fn as_the_agent(extra: &[(&str, Value)]) -> Value {
    let mut body = body(extra);
    body.as_object_mut().expect("the body is an object").insert(
        "actor".to_owned(),
        json!({ "agent": { "session_name": "watch-1" } }),
    );
    body
}

/// The manifest a start is bounded by, naming the file it is about.
fn manifest() -> Value {
    json!({
        "file_name": HOLD_FILE,
        "material": "PLA",
        "nozzle_diameter_mm": 0.4,
        "slicer_profile": "0.20mm QUALITY",
        "sheet": "smooth-pei",
        "allowed": { "feedrate": { "min": NARROWED.0, "max": NARROWED.1 } },
        "metadata": {},
    })
}

/// The body a manifest write takes: the manifest, and why it is written.
fn manifest_write(reason: Option<&str>) -> Value {
    let mut body = json!({ "manifest": manifest() });
    if let Some(reason) = reason {
        body.as_object_mut()
            .expect("the body is an object")
            .insert("reason".to_owned(), json!(reason));
    }
    body
}

/// What one mutating operation is asked, and what asking should do.
struct Live {
    /// A body the policy accepts.
    accepted: Value,
    /// A body the policy rejects, of this operation's own kind.
    rejected: Value,
    /// The state the machine should report once it has taken the accepted body,
    /// when the machine reports the effect at all.
    reaches: Option<&'static str>,
    /// Where a snapshot reports the value this operation set, and what it
    /// should read as.
    reported: Option<(&'static str, Value)>,
    /// What the instance should have received, for a value it reports nothing
    /// about: every fragment one recorded body has to carry.
    received: Vec<String>,
    /// The adjustable this operation changes, when it changes one.
    adjustable: Option<&'static str>,
}

/// A plan for an operation this machine only ever refuses: accepted by the
/// policy's grants, and with no effect at the machine to read back.
fn refused_at_the_machine(extra: &[(&str, Value)]) -> Live {
    Live {
        accepted: body(extra),
        rejected: as_the_agent(extra),
        reaches: None,
        reported: None,
        received: Vec::new(),
        adjustable: None,
    }
}

/// What every mutating operation is asked, by the name it is declared under.
///
/// The rejected body is of that operation's own kind: a value outside the
/// bounds the manifest narrowed for an adjustment, which the policy rejects;
/// and for the rest, a claim to be the agent, which the operator's credential
/// this tier presents is not — refused before the policy is asked anything.
fn live(name: &str) -> Live {
    match name {
        "pause" => Live {
            accepted: body(&[]),
            rejected: as_the_agent(&[]),
            reaches: Some("paused"),
            reported: None,
            received: Vec::new(),
            adjustable: None,
        },
        "resume" => Live {
            accepted: body(&[]),
            rejected: as_the_agent(&[]),
            reaches: Some("printing"),
            reported: None,
            received: Vec::new(),
            adjustable: None,
        },
        "cancel" => Live {
            accepted: body(&[]),
            rejected: as_the_agent(&[]),
            reaches: Some("operational"),
            reported: None,
            received: Vec::new(),
            adjustable: None,
        },
        "start_print" => Live {
            accepted: body(&[("file_name", json!(HOLD_FILE)), ("manifest", manifest())]),
            rejected: as_the_agent(&[("file_name", json!(HOLD_FILE)), ("manifest", manifest())]),
            reaches: Some("printing"),
            reported: None,
            received: Vec::new(),
            adjustable: None,
        },
        "acknowledge_failure" => Live {
            accepted: body(&[
                ("event_id", json!(printobserver_types::EventId::new())),
                ("disposition", json!("stop")),
            ]),
            rejected: as_the_agent(&[
                ("event_id", json!(printobserver_types::EventId::new())),
                ("disposition", json!("continue")),
            ]),
            // An acknowledgement asks nothing of the machine, `stop` included,
            // so the print it is about carries on.
            reaches: Some("printing"),
            reported: None,
            received: Vec::new(),
            adjustable: None,
        },
        "set_tool_target_c" => Live {
            accepted: body(&[("tool", json!(0)), ("target_c", json!(205.0))]),
            rejected: body(&[("tool", json!(0)), ("target_c", json!(900.0))]),
            reaches: None,
            reported: Some(("printer.tools.0.target_c.value", json!(205.0))),
            received: Vec::new(),
            adjustable: Some("tool_target:0"),
        },
        "set_bed_target_c" => Live {
            accepted: body(&[("target_c", json!(61.0))]),
            rejected: body(&[("target_c", json!(400.0))]),
            reaches: None,
            reported: Some(("printer.bed.target_c.value", json!(61.0))),
            received: Vec::new(),
            adjustable: Some("bed_target"),
        },
        "set_feedrate_factor" => Live {
            accepted: body(&[("factor", json!(1.13))]),
            rejected: body(&[("factor", json!(1.45))]),
            reaches: None,
            reported: None,
            received: vec![percent_of_multiplier(1.13).to_string()],
            adjustable: Some("feedrate"),
        },
        "set_flowrate_factor" => Live {
            accepted: body(&[("factor", json!(1.07))]),
            rejected: body(&[("factor", json!(4.0))]),
            reaches: None,
            reported: None,
            received: vec![percent_of_multiplier(1.07).to_string()],
            adjustable: Some("flowrate"),
        },
        "set_fan_percent" => Live {
            accepted: body(&[("percent", json!(55.0))]),
            rejected: body(&[("percent", json!(500.0))]),
            reaches: None,
            reported: None,
            // The one command this adapter ever sends, the parameter it binds
            // its number to, and the duty its own conversion gives for that
            // percentage — all three read off the adapter's own exports.
            received: vec![
                FAN_SET_COMMAND.to_owned(),
                FAN_PWM_PARAMETER.to_owned(),
                fan_pwm_of_percent(55.0).to_string(),
            ],
            adjustable: Some("fan"),
        },
        "close_print" => refused_at_the_machine(&[("outcome", json!("interrupted"))]),
        other => panic!("`{other}` is a mutating operation this walk does not know"),
    }
}

/// Deliver one alert to the real ingress, and wait its handling out.
///
/// The proxy's record and the responder's own log are forgotten first, so that
/// everything read afterwards is *this* turn's: the machine's requests since
/// this alert, and the actions the agent issued inside the turn it prompted.
/// Without that boundary an assertion about "the accepted action" would be
/// satisfied by one an earlier turn issued, and the walk would go on passing
/// with the turn after a restart doing nothing at all.
async fn deliver(world: &Composed, proxy: &Proxy, image_url: &str) {
    proxy.forget();
    world.forget_responder_log();
    let mut completions = world.server.completions();
    let status = world
        .client
        .post(format!("{}?token={SECRET}", world.server.ingress_url()))
        .header(reqwest::header::CONTENT_TYPE, "application/json")
        .body(alert_body(image_url))
        .send()
        .await
        .expect("the ingress answers")
        .status();
    assert_eq!(
        status,
        reqwest::StatusCode::ACCEPTED,
        "the real ingress did not take the committed sample"
    );
    completions.changed().await.expect("the handling finishes");
}

/// The print this walk's alerts opened.
async fn print_of(world: &Composed) -> PrintId {
    world
        .stores
        .prints
        .print_by_provider_id(OBICO_PRINT)
        .await
        .expect("the print reads")
        .expect("the alert opened a print")
        .id
}

fn prints_url(world: &Composed) -> String {
    format!(
        "http://{}{}",
        world.server.address(),
        printobserver_server::operation("prints")
            .expect("the prints read is served")
            .full_path()
    )
}

/// Take only the elapsed job times out of a listing, retaining every other
/// field for the whole-document comparison. A running job must report a
/// nonnegative elapsed time on each read.
fn elapsed_times(listing: &mut Value) -> Vec<u64> {
    listing["prints"]
        .as_array_mut()
        .expect("the prints are a list")
        .iter_mut()
        .map(|print| {
            print
                .as_object_mut()
                .expect("each print is an object")
                .remove("job_print_time_s")
                .expect("the running job reports its elapsed time")
                .as_u64()
                .expect("elapsed job time is a nonnegative integer")
        })
        .collect()
}

/// With no alert posted, a prints read names the job the bring-up started as
/// active — adopting it, since nothing has reported on it — a second read opens
/// nothing further, and the print it names can be read by that identifier.
async fn a_listing_adopts_the_running_job_before_any_alert(world: &Composed) -> PrintId {
    let (code, mut listed) = world.get(&prints_url(world)).await;
    assert_eq!(code, reqwest::StatusCode::OK, "{listed}");
    let active = listed["active"]
        .as_str()
        .unwrap_or_else(|| panic!("the job the bring-up started was not named active: {listed}"))
        .to_owned();
    let prints = listed["prints"].as_array().expect("the prints are a list");
    assert_eq!(
        prints.len(),
        1,
        "a supervisor over a fresh store listed prints beside the one it adopted: {listed}"
    );
    assert_eq!(prints[0]["id"], json!(active), "{listed}");
    assert_eq!(
        prints[0]["file_name"],
        json!(HOLD_FILE),
        "the adopted print does not carry the job's file name: {listed}"
    );
    assert!(
        prints[0].get("provider_print_id").is_none(),
        "the adopted print carries an identifier nothing reported: {listed}"
    );

    let (code, mut again) = world.get(&prints_url(world)).await;
    assert_eq!(code, reqwest::StatusCode::OK, "{again}");
    let before_times = elapsed_times(&mut listed);
    let after_times = elapsed_times(&mut again);
    assert_eq!(
        again, listed,
        "a second read while the same job runs changed the listing"
    );
    assert!(
        after_times
            .iter()
            .zip(&before_times)
            .all(|(after, before)| after >= before),
        "elapsed job time decreased: {before_times:?} to {after_times:?}"
    );

    let print_id: PrintId = active.parse().expect("a print identifier");
    let (code, context) = world.get(&world.operation_url("context", print_id)).await;
    assert_eq!(
        code,
        reqwest::StatusCode::OK,
        "the adopted print cannot be read by the identifier the listing gave: {context}"
    );
    assert_eq!(
        context["context"]["print"]["id"],
        json!(active),
        "{context}"
    );
    print_id
}

/// After the first alert, the listing shows one print for the job — the one it
/// adopted — now carrying `Obico`'s identifier.
async fn the_listing_shows_one_print_for_the_job(world: &Composed, print_id: PrintId) {
    let (code, listed) = world.get(&prints_url(world)).await;
    assert_eq!(code, reqwest::StatusCode::OK, "{listed}");
    let for_the_job: Vec<&Value> = listed["prints"]
        .as_array()
        .expect("the prints are a list")
        .iter()
        .filter(|print| print["file_name"] == json!(HOLD_FILE))
        .collect();
    assert_eq!(
        for_the_job.len(),
        1,
        "the alert opened a second print for the job: {listed}"
    );
    assert_eq!(
        for_the_job[0]["id"],
        json!(print_id.to_string()),
        "{listed}"
    );
    assert_eq!(
        for_the_job[0]["provider_print_id"],
        json!(OBICO_PRINT),
        "the adopted print does not carry the alert's identifier: {listed}"
    );
    assert_eq!(listed["active"], json!(print_id.to_string()), "{listed}");
}

/// One status read of the print.
async fn status(world: &Composed, print_id: PrintId) -> Value {
    let (code, answer) = world.get(&world.operation_url("status", print_id)).await;
    assert_eq!(code, reqwest::StatusCode::OK, "{answer}");
    answer
}

/// One value of an answer, by a dotted path through it.
fn at<'a>(answer: &'a Value, path: &str) -> &'a Value {
    let mut here = answer;
    for segment in path.split('.') {
        here = match segment.parse::<usize>() {
            Ok(index) => &here[index],
            Err(_) => &here[segment],
        };
    }
    here
}

/// Wait until the machine reports one connection state.
async fn until_state(world: &Composed, print_id: PrintId, wanted: &str) {
    until(&format!("the machine to report {wanted}"), || async {
        let seen = status(world, print_id).await["printer"]["connection"].clone();
        if seen == json!(wanted) {
            None
        } else {
            Some(seen.to_string())
        }
    })
    .await;
}

/// Ask for one operation, and answer what the server said.
async fn ask(world: &Composed, print_id: PrintId, name: &str, body: &Value) -> (u16, Value) {
    let url = world.operation_url(name, print_id);
    let (code, answer) = match name {
        "manifest_set" => world.put(&url, body).await,
        _ => world.post(&url, body).await,
    };
    (code.as_u16(), answer)
}

/// The whole loop.
pub async fn walk(instance: &Scripted) {
    let host = image_host(snapshot_bytes()).await;
    // An alert delivered to an idle machine ends the print it opens, so the
    // machine is printing before the first one arrives.
    hold_the_print_running(instance).await;
    let proxy = Proxy::in_front_of(&instance.url);
    let world = Composed::open(instance, &proxy.base_url()).await;

    let adopted = a_listing_adopts_the_running_job_before_any_alert(&world).await;
    let print_id =
        an_alert_joins_the_print_opens_a_session_and_stores_an_image(&world, &proxy, &host.url())
            .await;
    assert_eq!(
        print_id, adopted,
        "the first alert about the adopted job was handled against another print"
    );
    the_listing_shows_one_print_for_the_job(&world, print_id).await;
    the_agent_acted_through_the_api(&world, &proxy, print_id).await;
    the_reads_answer_the_records_they_name(&world, print_id).await;
    every_change_refuses_a_request_with_no_reason(&world, &proxy, print_id).await;
    every_mutating_operation_is_rejected_in_its_own_kind(&world, &proxy, print_id).await;
    every_adjustment_applies_the_duration_it_is_given(&world, print_id).await;
    // llmlint: ignore[live_tier_compiles_and_requires_credential] See suppressions.toml.
    let mut walked =
        every_operation_while_it_runs_has_its_own_effect(&world, &proxy, print_id).await;
    the_history_accounts_for_every_step(&world, print_id).await;

    // Restart, and a second alert continues the first alert's session — with the
    // agent acting through the API again inside it.
    hold_the_print_running(instance).await;
    let world = world.restart().await;
    assert!(
        world.server.reconciliation().adopted.contains(&print_id),
        "the restart did not adopt the print it was watching: {:?}",
        world.server.reconciliation()
    );
    let before = status(&world, print_id).await["session"]["session_name"].clone();
    deliver(&world, &proxy, &host.url()).await;
    let after = status(&world, print_id).await;
    assert_eq!(
        after["session"]["session_name"], before,
        "the second alert did not continue the first alert's session"
    );
    // The whole of the assertion again, against the boundary this alert set:
    // the turn after a restart has to act exactly as the first one did, and a
    // log read across both would be satisfied by the first turn alone.
    the_agent_acted_through_the_api(&world, &proxy, print_id).await;

    let reconciled = history(&world, print_id).await;
    assert!(
        reconciled.contains(&StartupReconciliationPayload::kind()),
        "the restart recorded none of what it adopted: {reconciled:?}"
    );
    assert_eq!(
        reconciled
            .iter()
            .filter(|kind| **kind == SupervisionSessionOpenedPayload::kind())
            .count(),
        1,
        "the second alert opened a session of its own: {reconciled:?}"
    );

    // Last, because a cancel ends the print every step above is about.
    walked
        .extend(a_cancel_ends_the_print_and_a_start_opens_its_own(&world, &proxy, print_id).await);
    every_mutating_operation_was_walked(walked);

    // Leave the environment as the bring-up recipe left it.
    hold_the_print_running(instance).await;
    world.server.stop().await;
}

/// The alert joins the print adopted for its job, stores its image, and opens a
/// session.
async fn an_alert_joins_the_print_opens_a_session_and_stores_an_image(
    world: &Composed,
    proxy: &Proxy,
    image_url: &str,
) -> PrintId {
    deliver(world, proxy, image_url).await;
    let print_id = print_of(world).await;
    let recorded = history(world, print_id).await;
    assert!(
        recorded.contains(&ObicoFailureAlertPayload::kind()),
        "the alert was not recorded: {recorded:?}"
    );
    assert!(
        recorded.contains(&SupervisionSessionOpenedPayload::kind()),
        "no session opened through the harness: {recorded:?}"
    );
    let opened = status(world, print_id).await;
    assert!(
        opened["session"]["session_name"]
            .as_str()
            .is_some_and(|name| !name.is_empty()),
        "the alert opened no session through the harness: {opened}"
    );
    stored_image_is_a_path(world, print_id).await;
    print_id
}

/// The agent asked this server for something, through the running API, in the
/// turn this alert prompted.
///
/// The responder issues both of its actions on every turn: one the policy admits
/// and one it does not. What is asserted here is about **that turn alone** — the
/// log and the machine's record were forgotten before the alert was delivered —
/// and it is asserted at the machine and at this server's own persisted records
/// rather than at the status the answer came under:
///
/// * the accepted action reached the real instance, which received the request
///   carrying the factor that adapter converts the asked-for one to;
/// * it opened an intervention whose expiry is the duration asked for, and that
///   intervention is the one the API answers as still in force;
/// * the action, the intervention and the assessment the turn wrote are all
///   about the same print and the same session;
/// * and the refused one is refused for the value it asked, with nothing
///   carrying that value reaching the machine.
async fn the_agent_acted_through_the_api(world: &Composed, proxy: &Proxy, print_id: PrintId) {
    let acted = world.responder_log();
    assert!(
        !acted.is_empty(),
        "the agent's own turn issued no action through the API; nothing was written \
         down since this alert"
    );

    let answered = |status: u16| -> Vec<&Value> {
        acted
            .iter()
            .filter(|line| line["status"] == json!(status))
            .collect()
    };
    let taken = answered(200);
    let refused = answered(409);
    assert_eq!(
        taken.len(),
        1,
        "this turn issued {} accepted actions and the agent issues one: {acted:?}",
        taken.len()
    );
    assert_eq!(
        refused.len(),
        1,
        "this turn issued {} refused actions and the agent issues one: {acted:?}",
        refused.len()
    );
    assert_eq!(
        acted.len(),
        2,
        "this turn issued something beside the two actions the agent is scripted \
         with: {acted:?}"
    );

    let accepted = &taken[0]["body"];
    let rejected = &refused[0]["body"];
    the_accepted_action_reached_the_machine(proxy);
    the_accepted_action_says_what_the_agent_asked(accepted, print_id);
    the_records_of_this_turn_are_about_one_print_and_one_session(world, print_id, accepted).await;
    the_refused_action_says_what_it_was_refused_for(rejected, print_id);
}

/// The instance received the request the accepted action asked for, and none
/// carrying the value the policy refused.
///
/// `OctoPrint` reports no applied feedrate factor at all, so the answer's own
/// `succeeded` says only that the instance did not refuse the request — what
/// says the request was made, and with what, is the machine's own record of it.
fn the_accepted_action_reached_the_machine(proxy: &Proxy) {
    let asked = percent_of_multiplier(AGENT_FACTOR).to_string();
    let bodies = proxy.bodies();
    assert!(
        bodies.iter().any(|body| body.contains(asked.as_str())),
        "the agent's accepted action answered `succeeded` and the instance received \
         no request carrying {asked:?}: {bodies:?}"
    );
    let never_sent = percent_of_multiplier(AGENT_REFUSED_FACTOR).to_string();
    assert!(
        !bodies.iter().any(|body| body.contains(never_sent.as_str())),
        "the value the policy refused reached the machine as {never_sent:?}: {bodies:?}"
    );
}

/// The answer says what the agent asked, and opened the intervention it asked
/// the change to stand for.
fn the_accepted_action_says_what_the_agent_asked(accepted: &Value, print_id: PrintId) {
    assert_eq!(
        accepted["record"]["decision"],
        json!("accepted"),
        "{accepted}"
    );
    assert_eq!(
        accepted["record"]["outcome"],
        json!("succeeded"),
        "{accepted}"
    );
    assert_eq!(
        accepted["record"]["print_id"],
        json!(print_id.to_string()),
        "the agent's action was recorded against another print: {accepted}"
    );
    let asked_for = &accepted["record"]["request"]["action"];
    assert_eq!(
        asked_for["action"],
        json!("set_feedrate_factor"),
        "{accepted}"
    );
    assert_eq!(asked_for["factor"], json!(AGENT_FACTOR), "{accepted}");
    assert_eq!(
        asked_for["duration_s"],
        json!(AGENT_DURATION_S),
        "{accepted}"
    );

    let intervention = &accepted["intervention"];
    assert!(
        !intervention.is_null(),
        "the bounded action the agent issued opened no intervention: {accepted}"
    );
    assert_eq!(intervention["adjustable"], json!("feedrate"), "{accepted}");
    assert_eq!(
        intervention["applied_value"],
        json!(AGENT_FACTOR),
        "the intervention is not about the value the agent asked for: {accepted}"
    );
    assert_eq!(
        instant(&intervention["expires_at"]) - instant(&intervention["applied_at"]),
        AGENT_DURATION_S,
        "the intervention's expiry is not the duration the agent asked for: {accepted}"
    );
    assert_eq!(
        intervention["action_id"], accepted["record"]["id"],
        "the intervention was opened by another action: {accepted}"
    );
    assert_eq!(
        intervention["print_id"],
        json!(print_id.to_string()),
        "the intervention is against another print: {accepted}"
    );
}

/// The action, the intervention and the assessment this turn wrote are about
/// one print and one session, read back out of this server's own records.
async fn the_records_of_this_turn_are_about_one_print_and_one_session(
    world: &Composed,
    print_id: PrintId,
    accepted: &Value,
) {
    let answered = status(world, print_id).await;
    let session = answered["session"]["session_name"].clone();
    assert_eq!(
        accepted["record"]["request"]["actor"]["agent"]["session_name"], session,
        "the action the agent issued names another session than the turn it ran in: \
         {accepted} against {session}"
    );

    let intervention = &accepted["intervention"];
    let held = answered["interventions"]
        .as_array()
        .expect("the interventions read")
        .iter()
        .find(|found| found["id"] == intervention["id"])
        .unwrap_or_else(|| {
            panic!(
                "the intervention the agent opened is not one this server holds in \
                 force: {answered}"
            )
        });
    assert_eq!(
        held["expires_at"], intervention["expires_at"],
        "the intervention this server holds expires at another instant: {held}"
    );
    assert_eq!(
        held["action_id"], accepted["record"]["id"],
        "the intervention this server holds was opened by another action: {held}"
    );
    assert_eq!(
        held["print_id"],
        json!(print_id.to_string()),
        "the intervention this server holds is against another print: {held}"
    );

    let assessed = history_records(world, print_id)
        .await
        .into_iter()
        // Newest first, so the first is the one this turn wrote.
        .find(|event| event["kind"] == json!("agent_assessment"))
        .unwrap_or_else(|| panic!("the turn wrote down no assessment for print {print_id}"));
    assert_eq!(
        assessed["print_id"],
        json!(print_id.to_string()),
        "the assessment is about another print: {assessed}"
    );
    assert_eq!(
        assessed["payload"]["session_name"], session,
        "the assessment names another session than the action the agent issued: \
         {assessed}"
    );
}

/// The refused action says the value it asked and the range it is held to, and
/// reached nothing.
fn the_refused_action_says_what_it_was_refused_for(rejected: &Value, print_id: PrintId) {
    assert_eq!(
        rejected["record"]["print_id"],
        json!(print_id.to_string()),
        "the refused action was recorded against another print: {rejected}"
    );
    let bounds = &rejected["record"]["decision"]["rejected"]["out_of_bounds"];
    assert_eq!(
        bounds["adjustable"],
        json!("feedrate"),
        "the policy refused the agent without naming what was out of bounds: {rejected}"
    );
    assert_eq!(
        bounds["requested"],
        json!(AGENT_REFUSED_FACTOR),
        "the policy refused a value other than the one the agent asked: {rejected}"
    );
    assert!(
        !bounds["allowed"].is_null(),
        "the policy refused the agent without the range it holds it to: {rejected}"
    );
    assert!(
        rejected["record"]["outcome"].is_null(),
        "a refused action reached the machine anyway: {rejected}"
    );
}

/// Every operation that changes something refuses a request carrying no reason.
async fn every_change_refuses_a_request_with_no_reason(
    world: &Composed,
    proxy: &Proxy,
    print_id: PrintId,
) {
    let mut walked = Vec::new();
    for operation in OPERATIONS {
        if !operation.is_mutating() {
            continue;
        }
        for (described, reason) in [
            ("no reason at all", None),
            ("a reason that is only whitespace", Some("   ")),
        ] {
            let before = stored(world, print_id).await;
            proxy.forget();
            let body = reasonless(&operation, reason);

            let (code, answer) = ask(world, print_id, operation.name, &body).await;

            assert_eq!(
                code, 400,
                "`{}` took a request carrying {described}: {answer}",
                operation.name
            );
            assert!(
                asked_by_an_action(proxy).is_empty(),
                "`{}` carried a request with {described} to the machine: {:?}",
                operation.name,
                asked_by_an_action(proxy)
            );
            assert_eq!(
                stored(world, print_id).await,
                before,
                "`{}` changed a stored record for a request with {described}",
                operation.name
            );
        }
        walked.push(operation.name);
    }
    let declared: Vec<&str> = OPERATIONS
        .iter()
        .filter(|operation| operation.is_mutating())
        .map(|operation| operation.name)
        .collect();
    assert_eq!(
        walked, declared,
        "the declared list holds an operation that changes something and this walk \
         did not reach"
    );
}

/// The body one mutating operation takes with the reason given — or with none.
///
/// The manifest it offers narrows the feedrate, so a server that wrote it before
/// ruling on the reason would move both the stored manifest and the print's
/// narrowings, and the record comparison would see it.
fn reasonless(operation: &Operation, reason: Option<&str>) -> Value {
    if operation.effect == Effect::Write {
        return manifest_write(reason);
    }
    let mut body = match operation.effect {
        Effect::Command(_) => ledger_body(operation.name),
        Effect::Recovery(_) => recovery_body(operation.name),
        _ => live(operation.name).accepted,
    };
    let object = body.as_object_mut().expect("the body is an object");
    match reason {
        Some(blank) => {
            object.insert("reason".to_owned(), json!(blank));
        }
        None => {
            object.remove("reason");
        }
    }
    body
}

/// A body one recovery action takes: the operator asking, and whatever else
/// the action needs.
fn recovery_body(name: &str) -> Value {
    let mut body = json!({ "reason": "the live walk is asking a recovery", "actor": "operator" });
    let object = body.as_object_mut().expect("the body is an object");
    let fields = match name {
        "recover_lift" => json!({ "mm": 5.0 }),
        "recover_fan" => json!({ "percent": 50.0 }),
        "recover_heat" => json!({ "tool": 0, "target_c": 150.0, "clearance_asserted": true }),
        "recover_park" | "recover_home_xy" => json!({ "clearance_asserted": true }),
        "recover_home_z" => json!({ "bed_clear_asserted": true }),
        _ => json!({}),
    };
    if let Value::Object(fields) = fields {
        object.extend(fields);
    }
    body
}

/// A body one spool command takes: the operator asking, and whatever else the
/// command needs.
fn ledger_body(name: &str) -> Value {
    let mut body = json!({ "reason": "the live walk is asking the ledger", "actor": "operator" });
    let object = body.as_object_mut().expect("the body is an object");
    match name {
        "register_spool" => {
            object.insert("name".to_owned(), json!("a live walk's spool"));
            object.insert("material".to_owned(), json!("PLA"));
            object.insert("initial_g".to_owned(), json!(1000.0));
        }
        "load_spool" => {
            object.insert("tool".to_owned(), json!(0));
        }
        "adjust_spool" => {
            object.insert("remaining_g".to_owned(), json!(500.0));
        }
        _ => {}
    }
    body
}

/// Every mutating operation is refused in its own kind, and moves nothing: an
/// adjustment out of bounds answers the policy's own rejection, recorded; a
/// request claiming an actor the credential is not is refused `403` before the
/// policy is asked, and recorded nowhere.
async fn every_mutating_operation_is_rejected_in_its_own_kind(
    world: &Composed,
    proxy: &Proxy,
    print_id: PrintId,
) {
    let mut walked = Vec::new();
    for operation in OPERATIONS {
        let Effect::Mutating(_) = operation.effect else {
            continue;
        };
        let plan = live(operation.name);
        let before = stored(world, print_id).await;
        let state_before = status(world, print_id).await["printer"]["connection"].clone();
        proxy.forget();

        let (code, answer) = ask(world, print_id, operation.name, &plan.rejected).await;

        if plan.adjustable.is_none() {
            assert_eq!(
                code, 403,
                "`{}` claiming the agent under the operator's credential was not refused: \
                 {answer}",
                operation.name
            );
            assert!(
                answer["error"]
                    .as_str()
                    .is_some_and(|said| said.contains("the operator") && said.contains("agent")),
                "`{}` was refused without naming who asked and who it claimed: {answer}",
                operation.name
            );
            assert!(
                asked_by_an_action(proxy).is_empty(),
                "`{}` was refused and the machine was asked {:?}",
                operation.name,
                asked_by_an_action(proxy)
            );
            assert_eq!(
                stored(world, print_id).await,
                before,
                "`{}` was refused before the policy and still moved the record",
                operation.name
            );
            walked.push(operation.name);
            continue;
        }
        assert_eq!(code, 409, "`{}` was not rejected: {answer}", operation.name);
        let rejection = &answer["record"]["decision"]["rejected"];
        assert!(
            !rejection.is_null(),
            "`{}` answered no rejection the caller can act on: {answer}",
            operation.name
        );
        {
            let adjustable = plan
                .adjustable
                .expect("only an adjustment reaches the policy here");
            let bounds = &rejection["out_of_bounds"];
            assert_eq!(
                bounds["adjustable"],
                json!(adjustable),
                "`{}` was rejected without naming what was out of bounds: {answer}",
                operation.name
            );
            assert!(
                !bounds["requested"].is_null() && !bounds["allowed"].is_null(),
                "`{}` was rejected without the value asked for and the range \
                 allowed: {answer}",
                operation.name
            );
        }
        assert!(
            asked_by_an_action(proxy).is_empty(),
            "`{}` was rejected and the machine was asked {:?}",
            operation.name,
            asked_by_an_action(proxy)
        );
        assert_eq!(
            status(world, print_id).await["printer"]["connection"],
            state_before,
            "`{}` was rejected and the machine moved anyway",
            operation.name
        );
        nothing_moved_but_the_record_of_the_rejection(
            world,
            print_id,
            &before,
            &answer["record"]["id"],
            operation.name,
        )
        .await;
        walked.push(operation.name);
    }
    assert_eq!(
        walked,
        vocabulary(),
        "the declared list holds a mutating operation this walk did not reject"
    );
}

/// Every adjustment applies the duration it is given, and opens nothing without.
async fn every_adjustment_applies_the_duration_it_is_given(world: &Composed, print_id: PrintId) {
    let mut walked = Vec::new();
    for operation in OPERATIONS {
        let Effect::Mutating(_) = operation.effect else {
            continue;
        };
        let plan = live(operation.name);
        let Some(adjustable) = plan.adjustable else {
            continue;
        };

        let mut bounded = plan.accepted.clone();
        bounded
            .as_object_mut()
            .expect("the body is an object")
            .insert("duration_s".to_owned(), json!(DURATION_S));
        let (code, answer) = ask(world, print_id, operation.name, &bounded).await;
        assert_eq!(code, 200, "`{}`: {answer}", operation.name);

        let intervention = &answer["intervention"];
        assert!(
            !intervention.is_null(),
            "`{}` was given a duration and opened no intervention: {answer}",
            operation.name
        );
        assert_eq!(
            intervention["adjustable"],
            json!(adjustable),
            "`{}` opened an intervention about something else: {answer}",
            operation.name
        );
        assert_eq!(
            instant(&intervention["expires_at"]) - instant(&intervention["applied_at"]),
            DURATION_S,
            "`{}` opened an intervention whose expiry is not the duration asked \
             for: {answer}",
            operation.name
        );

        let (code, answer) = ask(world, print_id, operation.name, &plan.accepted).await;
        assert_eq!(code, 200, "`{}`: {answer}", operation.name);
        assert!(
            answer["intervention"].is_null(),
            "`{}` was given no duration and opened an intervention anyway: {answer}",
            operation.name
        );
        walked.push(operation.name);
    }
    assert_eq!(
        walked.len(),
        5,
        "this walk bounded {} adjustments, and the vocabulary declares five: {walked:?}",
        walked.len()
    );
}

/// The order a shared machine admits while the print runs: the adjustments,
/// then pause and resume, then the acknowledgement.
const WHILE_IT_RUNS: [&str; 8] = [
    "set_bed_target_c",
    "set_tool_target_c",
    "set_feedrate_factor",
    "set_flowrate_factor",
    "set_fan_percent",
    "pause",
    "resume",
    "acknowledge_failure",
];

/// What ends the print and what begins the next, which the walk takes last: a
/// close is refused while the job runs and again once the record has ended, a
/// cancel ends the print every step before it is about, and a start opens a
/// print of its own.
const ENDING_IT: [&str; 3] = ["close_print", "cancel", "start_print"];

/// Every mutating operation the vocabulary declares was walked, by one of
/// [`every_operation_while_it_runs_has_its_own_effect`] and
/// [`a_cancel_ends_the_print_and_a_start_opens_its_own`].
fn every_mutating_operation_was_walked(mut walked: Vec<&'static str>) {
    walked.sort_unstable();
    let mut declared = vocabulary();
    declared.sort_unstable();
    assert_eq!(
        walked, declared,
        "the declared lists hold a mutating operation whose effect this walk did \
         not reach"
    );
}

/// The operations of [`WHILE_IT_RUNS`] have the effect each names, at the
/// machine itself; answers which were walked.
async fn every_operation_while_it_runs_has_its_own_effect(
    world: &Composed,
    proxy: &Proxy,
    print_id: PrintId,
) -> Vec<&'static str> {
    let mut walked = Vec::new();
    for name in WHILE_IT_RUNS {
        let plan = live(name);
        proxy.forget();
        let (code, answer) = ask(world, print_id, name, &plan.accepted).await;
        assert_eq!(code, 200, "`{name}` was not accepted: {answer}");
        assert_eq!(
            answer["record"]["decision"],
            json!("accepted"),
            "`{name}` answered a decision that is not acceptance: {answer}"
        );
        assert_eq!(
            answer["record"]["outcome"],
            json!("succeeded"),
            "`{name}` reached the real instance and it did not take it: {answer}"
        );

        if let Some(state) = plan.reaches {
            until_state(world, print_id, state).await;
        }
        if let Some((path, value)) = plan.reported {
            until(
                &format!("the machine to report {path} as {value}"),
                || async {
                    let seen = at(&status(world, print_id).await, path).clone();
                    if seen == value {
                        None
                    } else {
                        Some(seen.to_string())
                    }
                },
            )
            .await;
        }
        if !plan.received.is_empty() {
            let bodies = proxy.bodies();
            assert!(
                bodies.iter().any(|body| plan
                    .received
                    .iter()
                    .all(|fragment| body.contains(fragment.as_str()))),
                "`{name}` reports nothing a snapshot can read, and the instance \
                 received no request carrying all of {:?}: {bodies:?}",
                plan.received
            );
        }
        walked.push(name);
    }
    walked
}

/// A close is refused while the job runs, a cancel ends the print — a read of
/// it finds the job over — after which a close is refused again, and a start
/// from the idle machine opens a print of its own, which its answer names and
/// the job runs under; answers which were walked.
async fn a_cancel_ends_the_print_and_a_start_opens_its_own(
    world: &Composed,
    proxy: &Proxy,
    print_id: PrintId,
) -> Vec<&'static str> {
    let [close, cancel, start] = ENDING_IT;
    a_close_is_refused(
        world,
        proxy,
        print_id,
        &json!({ "print_still_active": { "state": "printing" } }),
    )
    .await;

    proxy.forget();
    let (code, cancelled) = ask(world, print_id, cancel, &live(cancel).accepted).await;
    assert_eq!(code, 200, "`{cancel}` was not accepted: {cancelled}");
    assert_eq!(
        cancelled["record"]["outcome"],
        json!("succeeded"),
        "{cancelled}"
    );
    until_state(world, print_id, "operational").await;
    // Whichever read first found the job over ended it: a real machine passes
    // through cancelling on its way to idle.
    let ended = status(world, print_id).await;
    assert!(
        ended["print"]["end_reason"]
            .as_str()
            .is_some_and(|reason| reason.starts_with("the print reached ")),
        "a read of the cancelled print did not end it: {ended}"
    );
    a_close_is_refused(world, proxy, print_id, &json!("print_already_ended")).await;

    let (code, started) = ask(world, print_id, start, &live(start).accepted).await;
    assert_eq!(code, 200, "`{start}` was not accepted: {started}");
    assert_eq!(
        started["record"]["outcome"],
        json!("succeeded"),
        "{started}"
    );
    let opened: PrintId = started["record"]["print_id"]
        .as_str()
        .and_then(|text| text.parse().ok())
        .unwrap_or_else(|| panic!("the start named no print it was recorded against: {started}"));
    assert_ne!(
        opened, print_id,
        "the start was recorded against the ended print"
    );
    until_state(world, opened, "printing").await;
    let running = status(world, opened).await;
    assert!(running["print"].get("ended_at").is_none(), "{running}");
    assert_eq!(
        prints_active(world).await,
        json!(opened.to_string()),
        "the listing does not name the print the start opened as the running job's"
    );
    vec![close, cancel, start]
}

/// A close the real machine's state makes the policy refuse, as the rejection
/// named: answered `409` naming it, nothing asked of the machine, and nothing
/// stored but the record of the rejection.
async fn a_close_is_refused(world: &Composed, proxy: &Proxy, print_id: PrintId, named: &Value) {
    let close = ENDING_IT[0];
    let before = stored(world, print_id).await;
    proxy.forget();

    let (code, answer) = ask(world, print_id, close, &live(close).accepted).await;

    assert_eq!(code, 409, "`{close}` was not rejected as {named}: {answer}");
    assert_eq!(
        answer["record"]["decision"]["rejected"], *named,
        "`{close}` was rejected for something else: {answer}"
    );
    assert!(
        asked_by_an_action(proxy).is_empty(),
        "`{close}` was rejected and the machine was asked {:?}",
        asked_by_an_action(proxy)
    );
    nothing_moved_but_the_record_of_the_rejection(
        world,
        print_id,
        &before,
        &answer["record"]["id"],
        close,
    )
    .await;
}

/// The print the listing names as the running job's.
async fn prints_active(world: &Composed) -> Value {
    let (code, listed) = world.get(&prints_url(world)).await;
    assert_eq!(code, reqwest::StatusCode::OK, "{listed}");
    listed["active"].clone()
}

/// Every read answers the record it names, read back out of the store.
async fn the_reads_answer_the_records_they_name(world: &Composed, print_id: PrintId) {
    let (code, written) = ask(
        world,
        print_id,
        "manifest_set",
        &manifest_write(Some("the integration tier is narrowing the bounds")),
    )
    .await;
    assert_eq!(code, 200, "{written}");

    let (code, read_back) = world
        .get(&world.operation_url("manifest_get", print_id))
        .await;
    assert_eq!(code, reqwest::StatusCode::OK);
    assert_eq!(
        read_back["manifest"],
        manifest(),
        "the manifest read back is not the one written"
    );

    let answered = status(world, print_id).await;
    assert_eq!(answered["print"]["id"], json!(print_id.to_string()));
    assert!(
        !answered["printer"]["connection"].is_null(),
        "the status carries nothing the machine reported: {answered}"
    );

    let (code, context) = world.get(&world.operation_url("context", print_id)).await;
    assert_eq!(code, reqwest::StatusCode::OK);
    assert_eq!(
        context["context"]["manifest"],
        manifest(),
        "the context does not carry the manifest that was written"
    );
    assert_eq!(
        context["context"]["print"]["id"],
        json!(print_id.to_string()),
        "the context is about another print: {context}"
    );

    let (code, events) = world.get(&world.operation_url("history", print_id)).await;
    assert_eq!(code, reqwest::StatusCode::OK);
    assert!(
        events["events"]
            .as_array()
            .is_some_and(|found| !found.is_empty()),
        "the history answered no events at all: {events}"
    );
}

/// The image the alert brought is a path on this host whose contents are what
/// the record declares.
async fn stored_image_is_a_path(world: &Composed, print_id: PrintId) {
    let image = world
        .stores
        .events
        .history(printobserver_core::store::HistoryQuery {
            print_id,
            kinds: Vec::new(),
            since: None,
            until: None,
            limit: None,
        })
        .await
        .expect("the history reads")
        .into_iter()
        .find_map(|event| event.image)
        .expect("the alert's image was stored");
    let url = format!(
        "http://{}{}",
        world.server.address(),
        printobserver_server::operation("image")
            .expect("image is served")
            .full_path()
            .replace("{image_id}", &image.id.to_string())
    );
    let (code, answer) = world.get(&url).await;
    assert_eq!(code, reqwest::StatusCode::OK, "{answer}");
    let path = std::path::PathBuf::from(
        answer["path"]
            .as_str()
            .unwrap_or_else(|| panic!("the image answer carries no path: {answer}")),
    );
    assert!(path.is_absolute() && path.exists(), "{}", path.display());
    assert_eq!(
        digest_at(&path),
        answer["record"]["sha256"].as_str().expect("a digest"),
        "what is at the path this server answered is not what the record declares"
    );
}

/// The history afterwards accounts for every step, and ties them together.
///
/// Every kind this walk's own steps raise has to be there — the alert that
/// started it, the session the turn opened, the assessment it wrote, and the
/// port failure the image host's own teardown raises is deliberately *not*
/// among them, because a walk that required one would be requiring a failure.
/// And the events are not read as a set of kinds alone: the alert, the session
/// and the assessment are asserted to be about the same print and the same
/// session the agent's own action named, which is what makes the history an
/// account of one loop rather than a list of things that happened.
async fn the_history_accounts_for_every_step(world: &Composed, print_id: PrintId) {
    let records = history_records(world, print_id).await;
    let kinds: Vec<Value> = records.iter().map(|event| event["kind"].clone()).collect();
    for wanted in [
        ObicoFailureAlertPayload::kind(),
        SupervisionSessionOpenedPayload::kind(),
        AgentAssessmentPayload::kind(),
    ] {
        let spelled = printobserver_types::serde_json::to_value(&wanted).expect("a kind renders");
        assert!(
            kinds.contains(&spelled),
            "the history does not account for {wanted:?}: {kinds:?}"
        );
    }
    assert!(
        records
            .iter()
            .all(|event| event["print_id"] == json!(print_id.to_string())),
        "the history of one print carries an event about another: {records:?}"
    );

    let session = status(world, print_id).await["session"]["session_name"].clone();
    let opened = records
        .iter()
        .find(|event| event["kind"] == json!("supervision_session_opened"))
        .expect("the history accounts for the session that opened");
    assert_eq!(
        opened["payload"]["session_name"], session,
        "the session the history says opened is not the one this print is watched \
         through: {opened}"
    );
    for assessment in records
        .iter()
        .filter(|event| event["kind"] == json!("agent_assessment"))
    {
        assert_eq!(
            assessment["payload"]["session_name"], session,
            "an assessment was written into a session this print is not watched \
             through: {assessment}"
        );
    }

    // The alert that started it is the one the producer sent, carrying its own
    // identifier for the print and the bytes it arrived as.
    let alert = records
        .iter()
        .find(|event| event["kind"] == json!("obico_failure_alert"))
        .expect("the history accounts for the alert");
    assert_eq!(
        alert["payload"]["obico_print_id"],
        json!(OBICO_PRINT),
        "the alert in the history is about another of the producer's prints: {alert}"
    );
    assert!(
        !alert["raw"].is_null(),
        "the alert in the history carries none of the bytes that arrived: {alert}"
    );
    assert!(
        !alert["image"].is_null(),
        "the alert in the history carries no image: {alert}"
    );
}

/// Every record this system stores about one print, as a caller reads them.
///
/// The printer's own snapshot is deliberately not among them: it carries the
/// instant it was observed at, so two reads of an unchanged machine differ. Nor
/// is what a read saw of the print's job (`job_print_time_s`, `job_started_at`):
/// every read of a running job records it, and the job runs on between two.
async fn stored(world: &Composed, print_id: PrintId) -> Value {
    let mut answered = status(world, print_id).await;
    if let Some(print) = answered["print"].as_object_mut() {
        print.remove("job_print_time_s");
        print.remove("job_started_at");
    }
    let (_, events) = world.get(&world.operation_url("history", print_id)).await;
    let (_, manifest) = world
        .get(&world.operation_url("manifest_get", print_id))
        .await;
    // The spool ledger is the printer's rather than the print's, and a spool
    // command refused for its reason wrote nothing into it either.
    let (_, spools) = world
        .get(&format!(
            "{}?include_retired=true",
            world.operation_url("spools", print_id)
        ))
        .await;
    json!({
        "print": answered["print"],
        "session": answered["session"],
        "interventions": answered["interventions"],
        "events": events["events"],
        "manifest": manifest,
        "spools": spools,
    })
}

/// A rejected request left the record exactly as it was, plus the two events
/// that put the rejection in the print's own history.
///
/// The reason a mutating request carries is what makes that history worth
/// reading afterwards, so a rejection **does** move the record: it writes down
/// what was asked for and what the policy made of it, and nothing else.
async fn nothing_moved_but_the_record_of_the_rejection(
    world: &Composed,
    print_id: PrintId,
    before: &Value,
    action_id: &Value,
    named: &str,
) {
    let mut after = stored(world, print_id).await;
    let events = after["events"]
        .as_array()
        .expect("a history answers a list")
        .clone();
    let written: Vec<&Value> = events.iter().take(2).collect();
    for (event, kind) in written.iter().zip(["action_rejected", "action_requested"]) {
        assert_eq!(
            event["kind"], kind,
            "`{named}` was rejected and the newest events are not the record of that: {event}"
        );
        assert_eq!(
            event["payload"]["action_id"], *action_id,
            "`{named}` was rejected and the events written are about another action: {event}"
        );
    }
    after["events"] = json!(events[2..]);
    assert_eq!(
        after, *before,
        "`{named}` was rejected and something beside the record of that rejection moved"
    );
}

/// Every operation of the action vocabulary, in the order it is declared.
fn vocabulary() -> Vec<&'static str> {
    OPERATIONS
        .iter()
        .filter(|operation| matches!(operation.effect, Effect::Mutating(_)))
        .map(|operation| operation.name)
        .collect()
}

/// Every event the print's history carries, newest first.
async fn history_records(world: &Composed, print_id: PrintId) -> Vec<Value> {
    let (code, answer) = world.get(&world.operation_url("history", print_id)).await;
    assert_eq!(code, reqwest::StatusCode::OK, "{answer}");
    answer["events"]
        .as_array()
        .expect("a history is a list")
        .clone()
}

/// Every kind the print's history carries.
async fn history(world: &Composed, print_id: PrintId) -> Vec<EventKind> {
    let (code, answer) = world.get(&world.operation_url("history", print_id)).await;
    assert_eq!(code, reqwest::StatusCode::OK, "{answer}");
    answer["events"]
        .as_array()
        .expect("a history is a list")
        .iter()
        .filter_map(|event| printobserver_types::serde_json::from_value(event["kind"].clone()).ok())
        .collect()
}

/// One instant of an answer, as whole seconds after the epoch.
fn instant(value: &Value) -> i64 {
    let text = value.as_str().expect("an instant is a string");
    let parsed: printobserver_types::Timestamp = text.parse().expect("an instant is RFC 3339");
    parsed.as_utc().timestamp()
}

/// The digest of what is at one path, lowercase hexadecimal.
fn digest_at(path: &std::path::Path) -> String {
    use sha2::{Digest as _, Sha256};
    let bytes = std::fs::read(path).expect("the image reads");
    let mut hasher = Sha256::new();
    hasher.update(&bytes);
    hasher
        .finalize()
        .iter()
        .fold(String::new(), |mut rendered, byte| {
            use core::fmt::Write as _;
            let _ = write!(rendered, "{byte:02x}");
            rendered
        })
}

/// Every request body the machine received but the push channel's own
/// passive login. A server behind the recording proxy is refused its push
/// socket's upgrade and keeps asking for one, each time logging in first —
/// on its own schedule, whatever it was asked — so an assertion that an action
/// sent the machine nothing reads every request that action could have sent.
fn asked_by_an_action(proxy: &Proxy) -> Vec<String> {
    proxy.bodies_but_to(printobserver_octoprint::push::LOGIN_PATH)
}