printobserver-core 0.14.0

Supervision logic for printobserver.
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
//! The loop: one normalized event becomes one supervised turn.
//!
//! The order is the contract. **The store's event append is the first thing the
//! loop does**, before the image is written, before the printer is read and
//! before a supervision turn is run, so that a failure of any of those is
//! recorded against an event that is already in the history. The one failure
//! that cannot be covered that way is the append itself: the store is where the
//! record lives, so when the append fails there is nowhere to record it. The
//! loop then calls no other port for that event, answers the store's own error
//! to its caller rather than swallowing it, and goes on to handle the next
//! event. Losing the alert that way is an availability failure; acting on the
//! printer with no record behind it would be a safety one, and this crate takes
//! the first over the second.
//!
//! # Context reads gather the print's current state
//!
//! A turn reads its print's context by running the command
//! [`CoreConfig::context_command_for`](crate::CoreConfig::context_command_for)
//! names, and that command reads it back through [`Supervisor::context`]. Each
//! read gathers the current printer, job and interventions, even while a turn
//! is running, so an operator's completed action is visible immediately. The
//! turn's event and situation still describe what prompted it; a look
//! ([`crate::look`]) also takes a fresh camera frame.
//!
//! # Everything a check decides from is in its prompt
//!
//! A turn is handed its print's facts — the context read as it begins, its
//! events cut to those since the agent last answered
//! ([`crate::context::turn_facts`]) — and the check's image of the
//! event's frame ([`crate::check_image`]), so a quiet check needs no command to
//! decide. Its answer's disposition is its acknowledgement: a turn that
//! acknowledged nothing by command has its event acknowledged from its answer,
//! as the agent in that turn's session, with the answer's `why` as the reason.
//!
//! # One agent per print
//!
//! [`Supervisor::receive_event`] writes an event down and claims its print's
//! turn, or — when a turn is already running for that print — hands the event
//! to that turn through the print's inbox ([`crate::inbox`]), where its next
//! look takes it. [`Supervisor::run_supervision`] runs a claimed turn and then
//! one more, in the same session, for whatever arrived during it that it never
//! took. A print that has ended starts no turn at all, and its inbox is
//! released with whatever was still waiting in it.

use crate::records::{AcknowledgementDisposition, Actor, PrintAction, PrintRecord};
use crate::store::{EventDraft, HistoryQuery, ImageLookup};
use printobserver_printer_api::{JobSnapshot, PrinterState};
use printobserver_supervisor_api::{AgentAssessment, Disposition, SessionPhase};
use printobserver_supervisor_api::{SupervisionSessionOpenedPayload, TurnRequest, TurnSituation};
use printobserver_types::EventId;
use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId, Timestamp};
use printobserver_vision_api::NormalizedAlert;

use crate::check_image::{ImageUse, captured_at_of};
use crate::context::{AgentContext, PrintContext, Since, newer_than};
use crate::error::CoreError;
use crate::inbox::Arrival;
use crate::kinds::{
    AgentAssessmentPayload, AgentStopUnactedPayload, PortFailurePayload, PortFailureSite,
    system_source,
};
use crate::listing::{self, ObservedJob, reached_reason};
use crate::supervisor::Supervisor;
use crate::watch::{concerns_its_end, noticed_of};

/// One event written down, and the turn it claimed, when it claimed one.
#[derive(Debug, Clone, PartialEq)]
pub struct Received {
    /// The event, as the store holds it.
    pub event: EventRecord,
    /// The turn it claimed: absent when it belongs to no print, to a print that
    /// has ended, or was handed to the turn already running for its print.
    pub turn: Option<PendingTurn>,
}

/// What became of one turn.
enum Supervised {
    /// It ran, and the printer was not in a terminal state.
    Ran,
    /// It ran, and the printer reported this terminal state.
    Terminal(PrinterState),
    /// The print had ended by the time the turn held it, so nothing ran.
    Ended,
}

/// A turn one event claimed, to be run by [`Supervisor::run_supervision`].
#[derive(Debug, Clone, PartialEq)]
pub struct PendingTurn {
    /// The print the turn is about.
    print: PrintRecord,
    /// The event that claimed it.
    arrival: Arrival,
    /// What was handed to the print before that event and never taken,
    /// oldest first.
    earlier: Vec<Arrival>,
}

impl PendingTurn {
    /// The turn one arrival claimed, after what was handed over before it.
    pub(crate) const fn new(print: PrintRecord, arrival: Arrival, earlier: Vec<Arrival>) -> Self {
        Self {
            print,
            arrival,
            earlier,
        }
    }
}

/// The print an alert belongs to, and whether resolving it opened one.
enum Resolution {
    /// The alert is about no print.
    NoPrint,
    /// A print this system already held.
    Existing(PrintRecord),
    /// A print opened for it now, which is owed its `print_started`.
    Opened(PrintRecord),
}

impl Resolution {
    /// The print, however it was found.
    const fn print(&self) -> Option<&PrintRecord> {
        match self {
            Self::NoPrint => None,
            Self::Existing(print) | Self::Opened(print) => Some(print),
        }
    }
}

/// The states a print does not carry on from.
///
/// Read off the printer's own reported state rather than inferred from a
/// notification's wording: the machine is the authority on whether it is still
/// printing.
pub const TERMINAL_STATES: [PrinterState; 3] = [
    PrinterState::Operational,
    PrinterState::Error,
    PrinterState::Offline,
];

impl Supervisor {
    /// Handle one normalized event, from the store's own append to the turn.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when the **initial event append** fails,
    /// which is the one failure this loop cannot record anywhere; no other port
    /// is called for that event, and a later event whose append succeeds is
    /// handled to completion. Every other port failure this loop reaches is
    /// recorded against the event rather than answered here — except the
    /// writes that come after the event is already in the history and are
    /// owed the spool ledger: a new print's `print_started`, and what a
    /// filament-change signal the alert relays charges and marks. Those are
    /// answered as the store's own error, the alert itself already written.
    pub async fn handle_event(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
        let received = self.receive_event(alert).await?;
        if let Some(turn) = received.turn {
            self.run_supervision(turn).await?;
        }
        Ok(received.event)
    }

    /// Write one normalized event down, and say whether it needs a turn of
    /// its own.
    ///
    /// The first half of [`Supervisor::handle_event`], for a caller that runs
    /// the turn somewhere else so that the next event can be written down
    /// while this one's turn is still running. An event for a print whose turn
    /// is already running is handed to that turn and answers no turn of its
    /// own: one agent per print, and what arrives reaches the agent already
    /// watching it.
    ///
    /// # Errors
    ///
    /// Exactly as [`Supervisor::handle_event`]'s.
    pub async fn receive_event(&self, alert: NormalizedAlert) -> Result<Received, CoreError> {
        let resolution = self.resolve_print(&alert).await?;
        let draft = EventDraft {
            print_id: resolution.print().map(|record| record.id),
            source: alert.source.clone(),
            received_at: alert.received_at,
            body: alert.body.clone(),
            raw: Some(alert.raw.clone()),
        };
        let event = self
            .stores()
            .events
            .append_event(draft)
            .await
            .map_err(CoreError::Store)?;
        let print = match resolution {
            Resolution::NoPrint => return Ok(Received { event, turn: None }),
            Resolution::Existing(print) => print,
            // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
            Resolution::Opened(print) => {
                self.record_print_started(print.id, print.file_name.clone(), None, None)
                    .await?;
                print
            }
        };
        if alert.detection.is_some() {
            // The detector flagged this print, which its status says from now on.
            self.note_flagged(print.id);
        }
        let (image, frame_captured_at) = self
            .write_image(&print, &event, alert.image_url.clone())
            .await
            .map_or((None, None), |(image, at)| (Some(image), Some(at)));
        if print.ended_at.is_some() {
            return Ok(Received { event, turn: None });
        }
        if let Some(signal) = alert.signal {
            self.handle_signal(&print, signal, alert.kind()).await?;
        }
        let mut carried = event.clone();
        carried.image = image.or(carried.image);
        if let Some(detection) = alert.detection
            && detection.paused_the_print
        {
            self.note_detector_pause(print.id, event.id, detection);
        }
        let arrival = Arrival {
            event: carried,
            detection: alert.detection,
            frame_captured_at,
        };
        let turn = self
            .inboxes()
            .claim_or_hand_over(print.id, arrival.clone())
            .then(|| PendingTurn::new(print, arrival, Vec::new()));
        Ok(Received { event, turn })
    }

    /// Run the turn one received event claimed, and one more for whatever
    /// arrived during it that it never took, until nothing is left.
    ///
    /// The detector's pause the agent adjusted the print under is resumed as
    /// each turn ends, when its grace has not already resumed it.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when a turn's outcome could not be
    /// recorded; a turn that fails is recorded rather than answered.
    pub async fn run_supervision(&self, turn: PendingTurn) -> Result<(), CoreError> {
        let PendingTurn {
            print,
            arrival,
            earlier,
        } = turn;
        let mut next = Some((arrival, earlier));
        while let Some((arrival, earlier)) = next {
            let supervised = self.supervise(&print, &arrival, earlier).await;
            if !matches!(supervised, Ok(Supervised::Ended)) {
                self.resume_adjusted_detector_pause(print.id).await;
            }
            match supervised {
                Ok(Supervised::Ran) => {}
                Ok(Supervised::Ended) => {
                    self.inboxes().release(print.id);
                    self.forget_detector_pause(print.id);
                    return Ok(());
                }
                Ok(Supervised::Terminal(state)) => {
                    self.inboxes().release(print.id);
                    let _turn = self.turns().acquire(print.id).await;
                    return self
                        .close_out_print(print.id, &state, &reached_reason(&state), None)
                        .await
                        .map(drop);
                }
                Err(error) => {
                    self.inboxes().release(print.id);
                    return Err(error);
                }
            }
            next = self
                .inboxes()
                .next_or_release(print.id)
                .and_then(|mut left| left.pop().map(|latest| (latest, left)));
        }
        Ok(())
    }

    /// The print an alert belongs to, opened if this system has not seen it.
    ///
    /// Correlated on the provider's own identifier the alert carries beside its
    /// body, and never on the body by kind: which provider raised the alert is
    /// the adapter's business, and this loop reads nothing an adapter declares.
    ///
    /// In order: the print already carrying that identifier; otherwise the most
    /// recently opened print with no end recorded, no provider identifier, the
    /// alert's own file name and a job the alert's start may be
    /// ([`listing::may_have_started_it`]), which is a job somebody found before
    /// the provider reported on it and which takes the identifier here;
    /// otherwise a print opened for it. The file name is the one key the two
    /// sides share — the provider names the job by the file the printer
    /// reported, and the printer names it by that same file — and the start is
    /// what tells that job from a later one of the same file.
    ///
    /// Nothing here reads the printer: an alert is written down before anything
    /// is asked of a port, and a print a later job replaced is closed by the
    /// next read that finds that job, not by an alert about it.
    ///
    /// Answers whether this opened it, so that the print's `print_started` is
    /// written once the alert itself has been.
    async fn resolve_print(&self, alert: &NormalizedAlert) -> Result<Resolution, CoreError> {
        let Some(provider_print) = &alert.print else {
            return Ok(Resolution::NoPrint);
        };
        let _resolving = self.resolving().await;
        if let Some(found) = self
            .stores()
            .prints
            .print_by_provider_id(provider_print.id)
            .await?
        {
            return Ok(Resolution::Existing(found));
        }
        if let Some(file_name) = &provider_print.file_name {
            let unattached = self
                .stores()
                .prints
                .open_prints()
                .await?
                .into_iter()
                .find(|open| {
                    open.provider_print_id.is_none()
                        && open.file_name.as_ref() == Some(file_name)
                        && listing::may_have_started_it(open, provider_print.started_at)
                });
            if let Some(found) = unattached {
                let attached = self
                    .stores()
                    .prints
                    .attach_obico_print(found.id, provider_print.id)
                    .await?;
                return Ok(Resolution::Existing(attached));
            }
        }
        let opened = self
            .stores()
            .prints
            .open_print(Some(provider_print.id), provider_print.file_name.clone())
            .await?;
        Ok(Resolution::Opened(opened))
    }

    /// Fetch and store the image an alert names, recording either failure.
    async fn write_image(
        &self,
        print: &PrintRecord,
        event: &EventRecord,
        image_url: Option<String>,
    ) -> Option<(ImageRef, Timestamp)> {
        let source_url = image_url?;
        let fetched = match self.vision().fetch_image(source_url.clone()).await {
            Ok(fetched) => fetched,
            Err(error) => {
                self.record_port_failure(
                    print.id,
                    event.id,
                    PortFailureSite::ImageWrite,
                    error.to_string(),
                )
                .await;
                return None;
            }
        };
        let captured_at = fetched.captured_at.unwrap_or_else(|| self.clock().now());
        match self
            .stores()
            .images
            .put_image(
                print.id,
                event.id,
                Some(source_url),
                fetched.content_type,
                fetched.bytes,
            )
            .await
        {
            Ok(record) => Some((
                ImageRef {
                    id: record.id,
                    sha256: record.sha256,
                },
                captured_at,
            )),
            Err(error) => {
                self.record_port_failure(
                    print.id,
                    event.id,
                    PortFailureSite::ImageWrite,
                    error.to_string(),
                )
                .await;
                None
            }
        }
    }

    /// Collect the context, run one turn on it, and persist what it answered.
    ///
    /// `earlier` is what arrived for the print before `arrival` while an
    /// earlier turn was running and that turn never took, oldest first.
    ///
    /// Answers the terminal state the printer reported, when it reported one,
    /// and runs nothing for a print that ended — at a read that found its job
    /// over — before this turn came to hold it.
    async fn supervise(
        &self,
        print: &PrintRecord,
        arrival: &Arrival,
        earlier: Vec<Arrival>,
    ) -> Result<Supervised, CoreError> {
        let event = &arrival.event;
        let guard = self.turns().acquire(print.id).await;
        let Some(held) = self.stores().prints.print(print.id).await? else {
            return Ok(Supervised::Ended);
        };
        let ended = held.ended_at.is_some();
        if ended && !concerns_its_end(event.kind()) {
            return Ok(Supervised::Ended);
        }
        let context = self.gather_context(print, Some(event.id)).await?;
        let printer_state = context
            .printer
            .as_ref()
            .map(|snapshot| snapshot.connection.clone());
        let terminal = printer_state
            .clone()
            .filter(|state| TERMINAL_STATES.contains(state));
        let (image_path, image) = self
            .check_image_for(print, arrival, context.job.as_ref())
            .await;
        let facts = crate::context::turn_facts(&context.for_agent(None));
        let situation = TurnSituation {
            printer_state,
            detector_warned: arrival.detection.map(|detection| detection.warning),
            detector_paused_the_print: arrival
                .detection
                .map(|detection| detection.paused_the_print),
            arrived_while_busy: earlier.into_iter().map(|left| left.event).collect(),
            noticed: noticed_of(event),
            frame_captured_at: arrival.frame_captured_at,
            image,
        };
        // The turn's credentials are bound to it from here, and revoked the
        // moment it returns — whatever it returned — and when this future is
        // abandoned, because dropping what was opened revokes too.
        let opened = self.open_turn(print.id);
        self.forget_acknowledged_by_turn(print.id);
        let running = situation.printer_state == Some(PrinterState::Printing);
        self.forget_stop_asked(print.id);
        let access = std::sync::Arc::new(StopAware {
            inner: opened.access(),
            print_id: print.id,
            stops: std::sync::Arc::clone(&self.stopped_by_turn),
        });
        let turn = self
            .agent()
            .run_turn(
                TurnRequest {
                    print_id: print.id,
                    event: event.clone(),
                    image_path,
                    context_command: self.config().context_command_for(print.id),
                    facts,
                    situation,
                },
                access,
            )
            .await;
        opened.revoke();
        let acknowledged_by_command = self.forget_acknowledged_by_turn(print.id);
        let asked_to_stop = self.forget_stop_asked(print.id);
        drop(guard);
        match turn {
            Ok(outcome) => {
                // An answer of `stop` on a print that was running, from a turn
                // that asked for no pause or cancel, stopped nothing.
                let stop_unacted = (running
                    && !asked_to_stop
                    && outcome.assessment.disposition == Disposition::Stop)
                    .then(|| {
                        (
                            outcome.session.session_name.clone(),
                            outcome.assessment.summary.clone(),
                        )
                    });
                self.record_answered(print.id, event.id, outcome, acknowledged_by_command)
                    .await?;
                if let Some(said) = stop_unacted {
                    self.record_unacted_stop(print.id, event.id, said).await?;
                }
            }
            Err(error) => {
                self.record_port_failure(
                    print.id,
                    event.id,
                    PortFailureSite::SupervisionTurn,
                    error.to_string(),
                )
                .await;
            }
        }
        // A print already over has nothing a terminal state could close: its
        // turn on its end ran, and what was handed to it meanwhile is next.
        Ok(match terminal {
            Some(state) if !ended => Supervised::Terminal(state),
            _ => Supervised::Ran,
        })
    }

    /// Write down what an answered turn said — the session it opened, its
    /// assessment — and acknowledge its event from the answer when the turn
    /// acknowledged nothing by command.
    async fn record_answered(
        &self,
        print_id: PrintId,
        event_id: EventId,
        outcome: printobserver_supervisor_api::TurnOutcome,
        acknowledged_by_command: bool,
    ) -> Result<(), CoreError> {
        if outcome.phase == SessionPhase::Created {
            self.append_system_event(
                print_id,
                EventBody::of(&SupervisionSessionOpenedPayload {
                    session_name: outcome.session.session_name.clone(),
                    harness_identity: outcome.session.harness_identity.clone(),
                })?,
            )
            .await?;
        }
        let session_name = outcome.session.session_name.clone();
        self.stores().sessions.put_session(outcome.session).await?;
        let assessment = outcome.assessment;
        self.append_system_event(
            print_id,
            EventBody::of(&AgentAssessmentPayload {
                session_name: session_name.clone(),
                assessment: assessment.clone(),
            })?,
        )
        .await?;
        if !acknowledged_by_command
            && let Err(error) = self
                .acknowledge_from_answer(print_id, event_id, session_name, &assessment)
                .await
        {
            // The turn answered; an acknowledgement that could not be
            // made is recorded against its event and ends nothing. Only a
            // store failing mid-turn reaches here, which the real store can
            // be made to do only by breaking its database under a running
            // server; the core journey
            // `an_acknowledgement_the_answer_cannot_make_is_recorded_and_supervision_goes_on`
            // proves it over a store that fails its history read instead.
            self.record_port_failure(
                print_id,
                event_id,
                PortFailureSite::SupervisionTurn,
                format!("the answer's acknowledgement could not be made: {error}"),
            )
            .await;
        }
        Ok(())
    }

    /// Write down that the agent answered a running print should stop and
    /// stopped nothing, when the print is still open: its history is where a
    /// refused pause is, which is what the person reading it reads.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when the print or its history could not
    /// be read or written.
    async fn record_unacted_stop(
        &self,
        print_id: PrintId,
        event_id: EventId,
        (session_name, summary): (String, String),
    ) -> Result<(), CoreError> {
        let open = self
            .stores()
            .prints
            .print(print_id)
            .await?
            .is_some_and(|print| print.ended_at.is_none());
        if !open {
            return Ok(());
        }
        self.append_system_event(
            print_id,
            EventBody::of(&AgentStopUnactedPayload {
                event_id,
                session_name,
                summary,
            })?,
        )
        .await?;
        Ok(())
    }

    /// The image a check of one arrival is shown and the line saying what it
    /// is, made where the job stood in the print's own file: none when the
    /// arrival carries no frame.
    async fn check_image_for(
        &self,
        print: &PrintRecord,
        arrival: &Arrival,
        job: Option<&JobSnapshot>,
    ) -> (Option<std::path::PathBuf>, Option<String>) {
        let event = &arrival.event;
        let Some(reference) = &event.image else {
            return (None, None);
        };
        let plan = self.plan_position(print, job).await;
        let captured_at = captured_at_of(event, arrival.frame_captured_at);
        self.shown_image_of(
            reference,
            Some(print.id),
            captured_at,
            ImageUse::Check,
            plan,
        )
        .await
        .map_or((None, None), |shown| (Some(shown.path), shown.note))
    }

    /// Note that the running turn on one print asked to pause or cancel it,
    /// whatever policy makes of the request: what an answer of `stop` is held
    /// to.
    pub(crate) fn note_stop_asked(&self, print_id: PrintId, action: &PrintAction) {
        if action.actor().class() == crate::records::ActorClass::Agent
            && matches!(
                action,
                PrintAction::Pause { .. } | PrintAction::Cancel { .. }
            )
        {
            self.stopped_by_turn
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .insert(print_id);
        }
    }

    /// Forget whether a turn on one print asked to stop it, answering whether
    /// one had.
    fn forget_stop_asked(&self, print_id: PrintId) -> bool {
        self.stopped_by_turn
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(&print_id)
    }

    /// Note that the running turn on one print acknowledged its event by
    /// command.
    pub(crate) fn note_acknowledged_by_turn(&self, print_id: PrintId) {
        self.acknowledged_by_turn
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(print_id);
    }

    /// Forget whether a turn on one print acknowledged by command, answering
    /// whether one had.
    fn forget_acknowledged_by_turn(&self, print_id: PrintId) -> bool {
        self.acknowledged_by_turn
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(&print_id)
    }

    /// Acknowledge the event a turn was about from the turn's answer, as the
    /// agent in the session it answered in: the same request, through the same
    /// policy, as the agent's own command would have made.
    ///
    /// A print that has ended by the time the turn answers is not
    /// acknowledged: its record is closed, and nothing is left to carry on or
    /// stop.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when the request could not be recorded. A
    /// refusal by policy is recorded with the request and is not an error.
    async fn acknowledge_from_answer(
        &self,
        print_id: PrintId,
        event_id: EventId,
        session_name: String,
        assessment: &AgentAssessment,
    ) -> Result<(), CoreError> {
        let open = self
            .stores()
            .prints
            .print(print_id)
            .await?
            .is_some_and(|print| print.ended_at.is_none());
        if !open {
            return Ok(());
        }
        let disposition = match assessment.disposition {
            Disposition::Continue => AcknowledgementDisposition::Continue,
            Disposition::Watch => AcknowledgementDisposition::Watch,
            Disposition::Stop => AcknowledgementDisposition::Stop,
        };
        self.request_action(
            print_id,
            PrintAction::AcknowledgeFailure {
                event_id,
                disposition,
                reason: assessment.why.clone(),
                actor: Actor::Agent { session_name },
            },
        )
        .await?;
        Ok(())
    }

    /// Gather the current context of one print, including while its
    /// supervision turn is running.
    ///
    /// # Errors
    ///
    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
    /// identifier, and the store's own error when the context could not be
    /// read.
    pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
        let print = self
            .stores()
            .prints
            .print(print_id)
            .await?
            .ok_or(CoreError::NoSuchPrint { print_id })?;
        self.gather_context(&print, None).await
    }

    /// What a supervision turn reads of one print's context, carrying only the
    /// events newer than `since` when it names one.
    ///
    /// Every event newer than the one named is carried, however many the
    /// recent window would hold: the window is widened to the history's
    /// largest page when the event is older than it.
    ///
    /// # Errors
    ///
    /// Answers [`CoreError::NoSuchPrint`] and the store's own error as
    /// [`Self::context`] does, and [`StoreError::NotFound`] when `since` names
    /// none of the print's latest [`MAX_HISTORY_LIMIT`] events.
    ///
    /// [`StoreError::NotFound`]: crate::store::StoreError::NotFound
    /// [`MAX_HISTORY_LIMIT`]: crate::store::MAX_HISTORY_LIMIT
    pub async fn agent_context(
        &self,
        print_id: PrintId,
        since: Option<printobserver_types::EventId>,
    ) -> Result<AgentContext, CoreError> {
        let context = self.context(print_id).await?;
        let Some(event) = since else {
            return Ok(context.for_agent(None));
        };
        let wider;
        let newer = if let Some(newer) = newer_than(&context.recent_events, event) {
            newer
        } else {
            wider = self
                .recent_events_of(&context.print, crate::store::MAX_HISTORY_LIMIT)
                .await?;
            newer_than(&wider, event).ok_or_else(|| {
                CoreError::Store(crate::store::StoreError::NotFound {
                    what: format!(
                        "event {event} among print {print_id}'s latest {} events",
                        crate::store::MAX_HISTORY_LIMIT
                    ),
                })
            })?
        };
        let agent = context.for_agent(Some(Since { event, newer }));
        Ok(agent)
    }

    /// Read one print's whole context, recording a printer read that fails.
    ///
    /// A read failure is recorded against the event being handled when there is
    /// one; a context read that no event prompted has nowhere to record it and
    /// carries the absence in the context itself, which is what an absent
    /// `printer` or `job` means.
    ///
    /// The job read settles the open prints exactly as the listing's does
    /// ([`crate::listing`]) before the rest of the context is read: a job found
    /// over closes the print, a later job of its file closes it as replaced,
    /// and a job found to be its own is recorded on it — so the context
    /// answered is the print as it now stands. Within a turn the turn holds the
    /// print, and that turn closes it.
    async fn gather_context(
        &self,
        print: &PrintRecord,
        event_id: Option<printobserver_types::EventId>,
    ) -> Result<PrintContext, CoreError> {
        let printer = match self.read_snapshot().await {
            Ok(snapshot) => Some(snapshot),
            Err(error) => {
                self.record_read_failure(
                    print.id,
                    event_id,
                    PortFailureSite::PrinterSnapshot,
                    error.to_string(),
                )
                .await;
                None
            }
        };
        // The job is read and settled under one hold on resolution, as the
        // listing's is. A start holds it from the read that chooses its print
        // until the printer has been asked to start, so a job read before that
        // hold and settled after it would be the idle machine the start has
        // since moved, and would close the print the start had just opened.
        let resolving = self.resolving().await;
        let job = match self.read_job().await {
            Ok(job) => Some(job),
            Err(error) => {
                self.record_read_failure(
                    print.id,
                    event_id,
                    PortFailureSite::PrinterJob,
                    error.to_string(),
                )
                .await;
                None
            }
        };
        let print = match &job {
            Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
            _ => print.clone(),
        };
        drop(resolving);
        let print = &print;
        let manifest = self.stores().prints.manifest(print.id).await?;
        let bounds = self.bounds_for(Some(print), print.id).await?;
        let interventions = self.stores().actions.active_interventions(print.id).await?;
        let recent_events = self
            .recent_events_of(print, self.config().recent_events)
            .await?;
        let latest_image = recent_events.iter().find_map(|record| record.image.clone());
        let slicer = self
            .slicer_plan(print, job.as_ref(), &interventions)
            .await?;
        Ok(PrintContext {
            print: print.clone(),
            printer,
            job,
            manifest,
            bounds: bounds.effective,
            interventions,
            recent_events,
            latest_image,
            detector: self.detector_health_for(print.id),
            slicer,
        })
    }

    /// One print's most recent events, newest first: its own, and what the
    /// printer watch recorded of the machine since it opened, which is the
    /// printer's and carries no print.
    async fn recent_events_of(
        &self,
        print: &PrintRecord,
        limit: u32,
    ) -> Result<Vec<EventRecord>, CoreError> {
        let mut events = self
            .stores()
            .events
            .history(HistoryQuery {
                print_id: print.id,
                kinds: Vec::new(),
                since: None,
                until: None,
                limit: Some(limit),
            })
            .await?;
        let kinds = crate::watch::PRINTER_WATCH_KINDS
            .iter()
            .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
            .collect();
        let watched = self
            .stores()
            .timeline
            .timeline(crate::store::TimelineQuery {
                kinds,
                since: Some(print.opened_at),
                until: None,
                spool_id: None,
                before: None,
                limit: Some(limit),
            })
            .await?;
        events.extend(watched.into_iter().filter(|event| event.print_id.is_none()));
        events.sort_by_key(|event| core::cmp::Reverse((event.received_at, event.id)));
        events.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
        Ok(events)
    }

    /// Where one image's bytes are, when the store still has them.
    pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
        match self.stores().images.image(image.id).await {
            Ok(ImageLookup::Found { path, .. }) => Some(path),
            _ => None,
        }
    }

    /// Settle the open prints against the job a context read found, and
    /// answer the print the context is about as that left it.
    ///
    /// The caller holds resolution from before it read that job.
    async fn settle_for_context(
        &self,
        print: &PrintRecord,
        job: &JobSnapshot,
    ) -> Result<PrintRecord, CoreError> {
        let observed = ObservedJob {
            job: job.clone(),
            observed_at: self.clock().now(),
        };
        let settled = self.settle_open_prints(&observed).await?;
        match settled.running {
            Some(running) if running.id == print.id => Ok(running),
            _ if settled.closed.contains(&print.id) => Ok(self
                .stores()
                .prints
                .print(print.id)
                .await?
                .unwrap_or_else(|| print.clone())),
            _ => Ok(print.clone()),
        }
    }

    /// End the print, expire what it had running, and close its session.
    ///
    /// The interventions are expired **before** the print is ended, because a
    /// restoration is an action against the print and a print that has already
    /// ended is one no action may be taken against.
    ///
    /// The caller holds the print's turn, so no turn is acting on it while it
    /// closes. Answers whether this closed it: a print already ended — by
    /// another read, or by the turn that held it — is left as it ended.
    ///
    /// The print's filament is settled after its interventions are expired
    /// and before it is ended ([`crate::accounting`]): a crash between the two
    /// leaves a settled, open print, which the next close-out only ends.
    /// `closing_job` is the job read that found the print over, when there
    /// was one; without it the settlement reads the job itself.
    pub(crate) async fn close_out_print(
        &self,
        print_id: PrintId,
        state: &PrinterState,
        reason: &str,
        closing_job: Option<&JobSnapshot>,
    ) -> Result<bool, CoreError> {
        let print = match self.stores().prints.print(print_id).await? {
            Some(print) if print.ended_at.is_none() => print,
            _ => return Ok(false),
        };
        self.forget_detector_pause(print_id);
        self.expire_all_active(print_id).await?;
        self.settle_filament(&print, state, reason, closing_job)
            .await?;
        self.stores()
            .prints
            .end_print(
                print_id,
                state.clone(),
                self.clock().now(),
                reason.to_owned(),
            )
            .await?;
        self.close_session_of(print_id, reason).await?;
        self.drop_gcode_spool(print_id);
        self.follow_up_end(print_id).await;
        Ok(true)
    }

    /// Append one event this system raised itself.
    pub(crate) async fn append_system_event(
        &self,
        print_id: PrintId,
        body: EventBody,
    ) -> Result<EventRecord, CoreError> {
        self.append_system_event_to(Some(print_id), body).await
    }

    /// Append one event the supervisor itself raised, to a print's history or
    /// to the printer's when it names none.
    pub(crate) async fn append_system_event_to(
        &self,
        print_id: Option<PrintId>,
        body: EventBody,
    ) -> Result<EventRecord, CoreError> {
        Ok(self
            .stores()
            .events
            .append_event(EventDraft {
                print_id,
                source: system_source(),
                received_at: self.clock().now(),
                body,
                raw: None,
            })
            .await?)
    }

    /// Record a printer read that failed, when an event prompted the read.
    async fn record_read_failure(
        &self,
        print_id: PrintId,
        event_id: Option<printobserver_types::EventId>,
        site: PortFailureSite,
        detail: String,
    ) {
        if let Some(event_id) = event_id {
            self.record_port_failure(print_id, event_id, site, detail)
                .await;
        }
    }

    /// Record that a port failed while one event was being handled.
    ///
    /// The event is already in the history by the time any of these sites is
    /// reached, which is what gives the failure somewhere to be recorded.
    /// Nothing is answered to the caller: the loop survives this and goes on.
    pub(crate) async fn record_port_failure(
        &self,
        print_id: PrintId,
        event_id: printobserver_types::EventId,
        site: PortFailureSite,
        detail: String,
    ) {
        self.record_port_failure_to(Some(print_id), event_id, site, detail)
            .await;
    }

    /// Record that a port failed while one event was being handled, in the
    /// history that event is in: a print's, or the printer's when it names
    /// none.
    pub(crate) async fn record_port_failure_to(
        &self,
        print_id: Option<PrintId>,
        event_id: printobserver_types::EventId,
        site: PortFailureSite,
        detail: String,
    ) {
        // A record that will not render is dropped exactly as one the store
        // refuses is: the failure it was about has already been answered, and
        // the loop survives not having written it down.
        let Ok(body) = EventBody::of(&PortFailurePayload {
            event_id,
            site,
            detail,
        }) else {
            return;
        };
        let _ = self.append_system_event_to(print_id, body).await;
    }
}

/// One turn's access as its port is handed it, saying too whether the turn
/// has asked for its print to be paused or cancelled.
struct StopAware {
    /// The turn's own issuer.
    inner: std::sync::Arc<dyn printobserver_supervisor_api::TurnAccess>,
    /// The print the turn is about.
    print_id: PrintId,
    /// The prints whose running turn has asked to stop them.
    stops: std::sync::Arc<std::sync::Mutex<std::collections::BTreeSet<PrintId>>>,
}

impl printobserver_supervisor_api::TurnAccess for StopAware {
    fn issue(
        &self,
        session: &printobserver_supervisor_api::TurnSession,
    ) -> Result<printobserver_supervisor_api::TurnPass, printobserver_supervisor_api::SupervisorError>
    {
        self.inner.issue(session)
    }

    fn asked_to_stop(&self) -> bool {
        self.stops
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .contains(&self.print_id)
    }
}