printobserver-core 0.19.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
//! The one aggregate a caller and the agent both read.
//!
//! [`PrintContext`] is the supervision domain's own view of one print: the
//! record, the printer and job as the printer port last reported them, the
//! manifest and the bounds in force, the interventions still active, the
//! events most recently written down — the print's own, and what the printer
//! watch recorded of the machine since the print opened — the failure
//! detector's health, and what the slicer planned at the job's current file
//! position ([`crate::gcode_index`]). The loop collects it when it handles an
//! event, holds it for the turn that event prompts, and answers it to the
//! `context` operation, so what the agent reasons about is the state the event
//! was handled at rather than whatever the machine has drifted to since.
//!
//! It is declared here rather than centrally because every field of it is
//! this domain's to collect: a domain that adds a fact a turn should see edits
//! this crate and regenerates the clients, and nothing central.

use crate::gcode_index::{
    BedArea, PlanFact, PlanMismatch, PlannedChange, PlannedChangeKind, Rise, SetValue, SlicerPlan,
};
use crate::records::{EffectiveBounds, Intervention, JobManifest, PrintRecord};
use crate::watch::{DetectorHealth, DetectorHealthStatus};
use printobserver_printer_api::{
    HeaterSnapshot, JobError, JobSnapshot, PrinterSnapshot, PrinterState,
};
use printobserver_types::EventPayload;
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::serde_json::Value;
use printobserver_types::{
    EventId, EventKind, EventRecord, ImageRef, PrintId, Reported, Timestamp,
};

/// Everything a supervision turn is given about one print.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PrintContext {
    /// The print itself.
    pub print: PrintRecord,
    /// The printer, when a snapshot could be taken.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printer: Option<PrinterSnapshot>,
    /// The job, when a snapshot could be taken.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job: Option<JobSnapshot>,
    /// The manifest, when the print has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manifest: Option<JobManifest>,
    /// The limits in force, so that the agent can see them before it asks.
    pub bounds: EffectiveBounds,
    /// The interventions still active.
    pub interventions: Vec<Intervention>,
    /// A bounded list of this print's events, newest first.
    pub recent_events: Vec<EventRecord>,
    /// The most recent image, when there is one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_image: Option<ImageRef>,
    /// The failure detector's health, and since when it has been so.
    #[serde(default)]
    pub detector: DetectorHealth,
    /// What the slicer planned at the job's current file position, read from
    /// the print's own G-code: absent when the file could not be read, or the
    /// job is not this print's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slicer: Option<SlicerPlan>,
}

impl Sample for PrintContext {
    fn sample_full() -> Self {
        Self {
            print: PrintRecord::sample_full(),
            printer: Some(PrinterSnapshot::sample_full()),
            job: Some(JobSnapshot::sample_full()),
            manifest: Some(JobManifest::sample_full()),
            bounds: EffectiveBounds::sample_full(),
            interventions: vec![Intervention::sample_full()],
            recent_events: vec![EventRecord::sample_full()],
            latest_image: Some(ImageRef::sample_full()),
            detector: DetectorHealth::sample_full(),
            slicer: Some(SlicerPlan::sample_full()),
        }
    }

    fn sample_minimal() -> Self {
        Self {
            print: PrintRecord::sample_minimal(),
            printer: None,
            job: None,
            manifest: None,
            bounds: EffectiveBounds::sample_full(),
            interventions: vec![],
            recent_events: vec![],
            latest_image: None,
            detector: DetectorHealth::sample_minimal(),
            slicer: None,
        }
    }
}

/// The payload fields a context's recent events leave out: the printer and job
/// snapshots an observation took, which the context states once as they are
/// now; the agent's own assessment, which its conversation already holds; and
/// the bookkeeping no supervision decision reads.
const UNREAD_PAYLOAD_FIELDS: [&str; 8] = [
    "printer",
    "job",
    "assessment",
    "interval_s",
    "session_name",
    "harness_identity",
    "delivered",
    "waited_s",
];

/// The kinds of event a supervision turn is not shown among the print's
/// events: the server's camera and file-index bookkeeping. What each decides
/// for a check, the turn's situation states once as the image it was handed
/// and why, so read again they would only cost every turn their hashes,
/// landmarks and matrices. The operator's own reads keep every one.
///
/// The camera's four are declared by the server, which this crate does not
/// depend on; the server's own test holds this list to their kinds.
pub const UNREAD_EVENT_KINDS: [&str; 5] = [
    "camera_view_judged",
    "camera_view_refit",
    "check_image_changed",
    "first_layer_alignment_judged",
    <crate::kinds::GcodeIndexedPayload as EventPayload>::KIND,
];

/// What a supervision turn reads about one print: [`PrintContext`] with each
/// fact stated once, as it is now, and nothing no supervision decision reads.
///
/// Left out of it, each because no step of the skill, no check and no recorded
/// case decides anything by it: the print's file, provider and times; the
/// printer's and the job's own states (the print states it once); every heater's
/// offset, the chamber and the time they were read; the printer's reported
/// feedrate, flowrate and fan (the slicer's plan states the flow and fan in
/// force, and no step reads the feedrate); the job's file, size, progress, time
/// and position (the plan states where the print is); the manifest (its limits
/// are the bounds); and the detector's health beyond its status — since when,
/// and why — which only the status read carries.
///
/// The printer and the job are stated here and nowhere in the events; each
/// event is what happened, when, and what it changed; and asked `since` an
/// event, only the events newer than it are carried, so a turn that has read
/// the rest is not handed them again. `newest_event` is what the next read
/// asks `since`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentContext {
    /// The print.
    pub print: AgentPrint,
    /// The printer's heaters now, when they could be read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printer: Option<AgentPrinter>,
    /// The error the job stopped on, when it stopped on one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job_error: Option<JobError>,
    /// The limits in force, so that the agent can see them before it asks.
    pub bounds: EffectiveBounds,
    /// The interventions still active.
    pub interventions: Vec<Intervention>,
    /// What the failure detector's status is for this print: whether it is
    /// scoring the print and has flagged it, or what it is otherwise.
    pub detector: DetectorHealthStatus,
    /// This print's events newer than the one asked `since`, or its recent
    /// ones when none was named, newest first.
    pub recent_events: Vec<AgentEvent>,
    /// The most recent image, whose path is answered beside the context and
    /// whose record states its digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_image: Option<ImageRef>,
    /// The newest event of this print's, which a later read asks `since`:
    /// absent only when the print has none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub newest_event: Option<EventId>,
    /// What the slicer planned at the job's current file position.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slicer: Option<AgentSlicerPlan>,
}

/// One stop the print's own G-code plans, as a turn reads it: [`PlannedChange`]
/// numbered the way a person counts a print's changes, the first being 1.
///
/// The record a change is kept under counts from 0, as the file's own order
/// does; a turn is never handed that count, so that the number it reads and the
/// number it says are the ones the operator says.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(
    crate = "printobserver_types::schemars",
    transform = crate::gcode_index::null_is_sent
)]
pub struct AgentPlannedChange {
    /// Its number among the file's changes, counting from 1 in file order.
    #[schemars(range(min = 1))]
    pub number: u32,
    /// What it stops the print for.
    pub kind: PlannedChangeKind,
    /// The byte offset of the first byte of its `M600` or `M601` line.
    pub offset_bytes: u64,
    /// The first layer printed after it, counting the first as 1: the layer
    /// whose `;Z:` is the change's height.
    pub layer: u32,
    /// That layer's height, in millimetres.
    pub z_mm: f64,
    /// The colour loaded at it, as `#RRGGBB` in upper case; null for an
    /// `M601`, and for an `M600` whose file names no colour.
    pub color: Option<String>,
}

impl From<&PlannedChange> for AgentPlannedChange {
    fn from(change: &PlannedChange) -> Self {
        Self {
            number: change.index.saturating_add(1),
            kind: change.kind,
            offset_bytes: change.offset_bytes,
            layer: change.layer,
            z_mm: change.z_mm,
            color: change.color.clone(),
        }
    }
}

/// What the slicer planned at the job's current file position, as a turn reads
/// it: [`SlicerPlan`] with each planned change an [`AgentPlannedChange`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentSlicerPlan {
    /// The colour the print should be laying at the current position, as
    /// `#RRGGBB`; absent when the file plans no change or names no colour
    /// there.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_color: Option<String>,
    /// The next change the file plans after the current position; absent when
    /// it plans none there.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_change: Option<AgentPlannedChange>,
    /// The slicer's own count of the minutes to that change, from the latest
    /// `M73 C` the position has reached; absent when there is no next change
    /// or no count.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub minutes_to_next_change: Option<i64>,
    /// The planned change the printer is waiting at now, for a person to
    /// finish; absent when it is waiting at none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub change_waiting: Option<AgentPlannedChange>,
    /// The layer the print is in, counting the first as 1; absent before the
    /// first.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layer: Option<usize>,
    /// The current layer's height, in millimetres.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub z_mm: Option<f64>,
    /// The final layer's height, in millimetres.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_z_mm: Option<f64>,
    /// What the current layer lays material as, in the order the file first
    /// names each: `Perimeter`, `Support material`, `Bridge infill`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub types: Vec<String>,
    /// The slicer's own estimate of the minutes left, at the current position.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub minutes_left: Option<i64>,
    /// The flow factor, one meaning one hundred percent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flow_factor: Option<SetValue>,
    /// The part-cooling fan speed, in percent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fan_percent: Option<SetValue>,
    /// How many objects the file lays down; absent when it labels none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub object_count: Option<usize>,
    /// The bed area each object the file lays down covers, unnamed, as
    /// `[x_min, y_min, x_max, y_max]` in whole millimetres, in the order of
    /// the file's object numbers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub objects: Vec<BedArea>,
    /// How far the plan has risen since an earlier frame; absent before any
    /// frame is half an hour old.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rise: Option<Rise>,
    /// Each setting in force the plan at this height says is wrong.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub at_odds: Vec<PlanMismatch>,
    /// The facts the file does not state, which are therefore unknown rather
    /// than absent.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unknown: Vec<PlanFact>,
}

impl From<&SlicerPlan> for AgentSlicerPlan {
    fn from(plan: &SlicerPlan) -> Self {
        Self {
            expected_color: plan.expected_color.clone(),
            next_change: plan.next_change.as_ref().map(AgentPlannedChange::from),
            minutes_to_next_change: plan.minutes_to_next_change,
            change_waiting: plan.change_waiting.as_ref().map(AgentPlannedChange::from),
            layer: plan.layer,
            z_mm: plan.z_mm,
            final_z_mm: plan.final_z_mm,
            types: plan.types.clone(),
            minutes_left: plan.minutes_left,
            flow_factor: plan.flow_factor.clone(),
            fan_percent: plan.fan_percent.clone(),
            object_count: plan.object_count,
            objects: plan.objects.clone(),
            rise: plan.rise.clone(),
            at_odds: plan.at_odds.clone(),
            unknown: plan.unknown.clone(),
        }
    }
}

/// The print a context is about.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentPrint {
    /// Its identifier.
    pub id: PrintId,
    /// What the printer was last found doing with it, or the state it ended in.
    pub state: PrinterState,
    /// Why it ended, once it has.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_reason: Option<String>,
}

/// The printer's heaters as they are now.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentPrinter {
    /// Each tool's heater, in order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<AgentHeater>,
    /// The bed's heater, when it has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bed: Option<AgentHeater>,
}

/// One heater, in degrees Celsius: each reading absent when the printer did not
/// report it, or reported one outside what a heater can read.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentHeater {
    /// The temperature it is at.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actual_c: Option<f64>,
    /// The temperature it is driving towards.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_c: Option<f64>,
}

/// One event of the print's, as a turn reads it: what happened, when, and the
/// facts it changed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentEvent {
    /// Its identifier, which a later read asks `since`.
    pub id: EventId,
    /// What kind of event it is.
    pub kind: EventKind,
    /// When it was received.
    pub received_at: Timestamp,
    /// What it carried, less the snapshots the context states once, the
    /// agent's own assessment and the bookkeeping no decision reads.
    #[serde(default, skip_serializing_if = "is_empty_payload")]
    pub payload: Value,
}

/// Whether a payload says nothing.
fn is_empty_payload(payload: &Value) -> bool {
    match payload {
        Value::Null => true,
        Value::Object(fields) => fields.is_empty(),
        _ => false,
    }
}

/// The events a context read asked `since` one carries: that event, and the
/// print's events newer than it, newest first.
#[derive(Debug, Clone, Copy)]
pub struct Since<'events> {
    /// The event named.
    pub event: EventId,
    /// Every event of the print's newer than it, newest first.
    pub newer: &'events [EventRecord],
}

impl PrintContext {
    /// What a supervision turn reads of this context: its recent events, or
    /// those `since` names when it names any.
    #[must_use]
    pub fn for_agent(&self, since: Option<Since<'_>>) -> AgentContext {
        let heater = |heater: &HeaterSnapshot| AgentHeater {
            actual_c: in_range(heater.actual_c.as_ref()),
            target_c: in_range(heater.target_c.as_ref()),
        };
        let (events, newest_event) = match since {
            Some(since) => (
                since.newer,
                Some(since.newer.first().map_or(since.event, |newest| newest.id)),
            ),
            None => (
                self.recent_events.as_slice(),
                self.recent_events.first().map(|newest| newest.id),
            ),
        };
        AgentContext {
            print: AgentPrint {
                id: self.print.id,
                state: self.print.state.clone(),
                end_reason: self.print.end_reason.clone(),
            },
            printer: self.printer.as_ref().map(|printer| AgentPrinter {
                tools: printer.tools.iter().map(heater).collect(),
                bed: printer.bed.as_ref().map(heater),
            }),
            job_error: self.job.as_ref().and_then(|job| job.error.clone()),
            bounds: self.bounds.clone(),
            interventions: self.interventions.clone(),
            detector: self.detector.status(),
            recent_events: events
                .iter()
                .filter(|event| !UNREAD_EVENT_KINDS.contains(&event.kind().as_str()))
                .map(agent_event)
                .collect(),
            latest_image: self.latest_image.clone(),
            newest_event,
            slicer: self.slicer.as_ref().map(AgentSlicerPlan::from),
        }
    }
}

/// The facts a supervision turn is handed up front: the context read as the
/// turn began, as [`AgentContext`] answers it — and no field that answer does
/// not carry — with its events cut to [`unseen_events`]: what happened that the
/// agent has not been shown, which its own conversation does not hold.
///
/// What the turn is handed beside its facts is not stated in them again: its
/// own event, `shown`, which it is handed whole, is left out of the events, and
/// out of `newest_event` when it is the newest; and `latest_image` is left out,
/// the turn being handed its image and none of its commands reading that
/// record.
#[must_use]
pub fn turn_facts(
    context: &AgentContext,
    shown: EventId,
) -> Option<printobserver_types::serde_json::Map<String, Value>> {
    let mut facts = context.clone();
    facts.recent_events = unseen_events(&context.recent_events);
    facts.recent_events.retain(|event| event.id != shown);
    facts.newest_event = facts.newest_event.filter(|newest| *newest != shown);
    facts.latest_image = None;
    match printobserver_types::serde_json::to_value(facts) {
        Ok(Value::Object(fields)) => Some(fields),
        _ => None,
    }
}

/// Of a print's events, newest first, those the agent has not been shown:
/// every event newer than its last answer, and every one that arrived while
/// the turn behind that answer ran — after the event that turn answered, which
/// its acknowledgement names — and was not that turn's own doing: a person's
/// resume taken as the agent answered, or the printer's own report. The turn's
/// own requests, their outcomes and what it recorded of itself are left out, and
/// so is the acknowledgement written from that answer after the turn ended, with
/// its outcome: the conversation already holds the answer it was written from. A
/// print the agent has not answered on keeps every event; one whose answered
/// event cannot be found keeps every event back to the answer before, its
/// own aside, because one shown twice costs less than one never shown.
#[must_use]
pub fn unseen_events(events: &[AgentEvent]) -> Vec<AgentEvent> {
    let is_answer = |event: &AgentEvent| {
        event.kind.as_str() == <crate::kinds::AgentAssessmentPayload as EventPayload>::KIND
    };
    let Some(answered) = events.iter().position(is_answer) else {
        return events.to_vec();
    };
    let (newer, older) = events.split_at(answered);
    let older = &older[1..];
    let turn = &older[..older.iter().position(is_answer).unwrap_or(older.len())];
    let during = events
        .iter()
        .find_map(agents_acknowledged_event)
        .and_then(|answered_event| turn.iter().position(|event| event.id == answered_event))
        .map_or(turn, |at| &turn[..at]);
    let own: Vec<&Value> = during
        .iter()
        .filter(|event| is_agents_request(event))
        .filter_map(|event| event.payload.get("action_id"))
        .collect();
    let acknowledged: Vec<&Value> = newer
        .iter()
        .filter(|event| agents_acknowledged_event(event).is_some())
        .filter_map(|event| event.payload.get("action_id"))
        .collect();
    let mut unseen: Vec<AgentEvent> = newer
        .iter()
        .filter(|event| {
            !event
                .payload
                .get("action_id")
                .is_some_and(|action| acknowledged.contains(&action))
        })
        .cloned()
        .collect();
    unseen.extend(
        during
            .iter()
            .filter(|event| {
                !TURNS_OWN_KINDS.contains(&event.kind.as_str())
                    && !event
                        .payload
                        .get("action_id")
                        .is_some_and(|action| own.contains(&action))
            })
            .cloned(),
    );
    unseen
}

/// What a turn records of itself as it runs: the looks it took and the session
/// it opened, which it already saw or has no use for.
const TURNS_OWN_KINDS: [&str; 2] = [
    <crate::kinds::CameraLookPayload as EventPayload>::KIND,
    <printobserver_supervisor_api::SupervisionSessionOpenedPayload as EventPayload>::KIND,
];

/// Whether an event is a request the agent made.
fn is_agents_request(event: &AgentEvent) -> bool {
    event.kind.as_str() == <crate::kinds::ActionRequestedPayload as EventPayload>::KIND
        && event
            .payload
            .get("actor")
            .is_some_and(|actor| actor.get("agent").is_some())
}

/// The event an acknowledgement the agent asked for names, when this is one.
fn agents_acknowledged_event(event: &AgentEvent) -> Option<EventId> {
    if !is_agents_request(event) {
        return None;
    }
    let action = event.payload.get("action")?;
    if action.get("action")?.as_str()? != "acknowledge_failure" {
        return None;
    }
    printobserver_types::serde_json::from_value(action.get("event_id")?.clone()).ok()
}

/// The events newer than `since`, newest first, when `events` — newest first —
/// holds it.
#[must_use]
pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
    events
        .iter()
        .position(|event| event.id == since)
        .map(|at| &events[..at])
}

/// A reading in range, as its value alone.
fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
    reported
        .filter(|reported| !reported.out_of_range())
        .map(Reported::value)
}

/// One event, as a turn reads it.
fn agent_event(event: &EventRecord) -> AgentEvent {
    let mut payload = event.body.payload.clone();
    if let Value::Object(fields) = &mut payload {
        for unread in UNREAD_PAYLOAD_FIELDS {
            fields.remove(unread);
        }
    }
    number_planned_changes(&mut payload);
    AgentEvent {
        id: event.id,
        kind: event.kind().clone(),
        received_at: event.received_at,
        payload,
    }
}

/// One event as a turn is shown it, whether as its trigger or among those that
/// arrived while another turn ran: the event itself, each planned change its
/// payload names numbered from 1 ([`number_planned_changes`]).
#[must_use]
pub(crate) fn as_a_turn_reads(event: &EventRecord) -> EventRecord {
    let mut shown = event.clone();
    number_planned_changes(&mut shown.body.payload);
    shown
}

/// The count-from-0 fields a payload may name a planned change by, each with
/// the count-from-1 field a turn reads in its place.
const PLANNED_CHANGE_INDICES: [(&str, &str); 2] = [
    ("change_index", "change_number"),
    ("planned_change", "planned_change_number"),
];

/// Number every planned change a payload names from 1, as a turn reads one.
///
/// A [`PlannedChange`] a payload carries — the change a print reached or
/// carried on from — is written as an [`AgentPlannedChange`]; a refusal's
/// `change_index` and a filament change signal's `planned_change` are written
/// as `change_number` and `planned_change_number`, one more. Nothing else is
/// touched, so a turn is never handed a planned change counted from 0.
fn number_planned_changes(value: &mut Value) {
    match value {
        Value::Object(fields) => {
            for (index, number) in PLANNED_CHANGE_INDICES {
                if let Some(counted) = fields.get(index).and_then(Value::as_u64) {
                    fields.remove(index);
                    fields.insert(number.to_owned(), Value::from(counted.saturating_add(1)));
                }
            }
            if let Some(change) = fields.get_mut("change") {
                let numbered =
                    printobserver_types::serde_json::from_value::<PlannedChange>(change.clone())
                        .ok()
                        .and_then(|planned| {
                            printobserver_types::serde_json::to_value(AgentPlannedChange::from(
                                &planned,
                            ))
                            .ok()
                        });
                if let Some(numbered) = numbered {
                    *change = numbered;
                }
            }
            fields.values_mut().for_each(number_planned_changes);
        }
        Value::Array(items) => items.iter_mut().for_each(number_planned_changes),
        _ => {}
    }
}

impl Sample for AgentContext {
    fn sample_full() -> Self {
        PrintContext::sample_full().for_agent(None)
    }

    fn sample_minimal() -> Self {
        PrintContext::sample_minimal().for_agent(None)
    }
}