Skip to main content

printobserver_core/
context.rs

1//! The one aggregate a caller and the agent both read.
2//!
3//! [`PrintContext`] is the supervision domain's own view of one print: the
4//! record, the printer and job as the printer port last reported them, the
5//! manifest and the bounds in force, the interventions still active, the
6//! events most recently written down — the print's own, and what the printer
7//! watch recorded of the machine since the print opened — the failure
8//! detector's health, and what the slicer planned at the job's current file
9//! position ([`crate::gcode_index`]). The loop collects it when it handles an
10//! event, holds it for the turn that event prompts, and answers it to the
11//! `context` operation, so what the agent reasons about is the state the event
12//! was handled at rather than whatever the machine has drifted to since.
13//!
14//! It is declared here rather than centrally because every field of it is
15//! this domain's to collect: a domain that adds a fact a turn should see edits
16//! this crate and regenerates the clients, and nothing central.
17
18use crate::gcode_index::{
19    BedArea, PlanFact, PlanMismatch, PlannedChange, PlannedChangeKind, Rise, SetValue, SlicerPlan,
20};
21use crate::records::{EffectiveBounds, Intervention, JobManifest, PrintRecord};
22use crate::watch::{DetectorHealth, DetectorHealthStatus};
23use printobserver_printer_api::{
24    HeaterSnapshot, JobError, JobSnapshot, PrinterSnapshot, PrinterState,
25};
26use printobserver_types::EventPayload;
27use printobserver_types::contract::Sample;
28use printobserver_types::schemars::JsonSchema;
29use printobserver_types::serde::{Deserialize, Serialize};
30use printobserver_types::serde_json::Value;
31use printobserver_types::{
32    EventId, EventKind, EventRecord, ImageRef, PrintId, Reported, Timestamp,
33};
34
35/// Everything a supervision turn is given about one print.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
37#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
38#[schemars(crate = "printobserver_types::schemars")]
39pub struct PrintContext {
40    /// The print itself.
41    pub print: PrintRecord,
42    /// The printer, when a snapshot could be taken.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub printer: Option<PrinterSnapshot>,
45    /// The job, when a snapshot could be taken.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub job: Option<JobSnapshot>,
48    /// The manifest, when the print has one.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub manifest: Option<JobManifest>,
51    /// The limits in force, so that the agent can see them before it asks.
52    pub bounds: EffectiveBounds,
53    /// The interventions still active.
54    pub interventions: Vec<Intervention>,
55    /// A bounded list of this print's events, newest first.
56    pub recent_events: Vec<EventRecord>,
57    /// The most recent image, when there is one.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub latest_image: Option<ImageRef>,
60    /// The failure detector's health, and since when it has been so.
61    #[serde(default)]
62    pub detector: DetectorHealth,
63    /// What the slicer planned at the job's current file position, read from
64    /// the print's own G-code: absent when the file could not be read, or the
65    /// job is not this print's.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub slicer: Option<SlicerPlan>,
68}
69
70impl Sample for PrintContext {
71    fn sample_full() -> Self {
72        Self {
73            print: PrintRecord::sample_full(),
74            printer: Some(PrinterSnapshot::sample_full()),
75            job: Some(JobSnapshot::sample_full()),
76            manifest: Some(JobManifest::sample_full()),
77            bounds: EffectiveBounds::sample_full(),
78            interventions: vec![Intervention::sample_full()],
79            recent_events: vec![EventRecord::sample_full()],
80            latest_image: Some(ImageRef::sample_full()),
81            detector: DetectorHealth::sample_full(),
82            slicer: Some(SlicerPlan::sample_full()),
83        }
84    }
85
86    fn sample_minimal() -> Self {
87        Self {
88            print: PrintRecord::sample_minimal(),
89            printer: None,
90            job: None,
91            manifest: None,
92            bounds: EffectiveBounds::sample_full(),
93            interventions: vec![],
94            recent_events: vec![],
95            latest_image: None,
96            detector: DetectorHealth::sample_minimal(),
97            slicer: None,
98        }
99    }
100}
101
102/// The payload fields a context's recent events leave out: the printer and job
103/// snapshots an observation took, which the context states once as they are
104/// now; the agent's own assessment, which its conversation already holds; and
105/// the bookkeeping no supervision decision reads.
106const UNREAD_PAYLOAD_FIELDS: [&str; 8] = [
107    "printer",
108    "job",
109    "assessment",
110    "interval_s",
111    "session_name",
112    "harness_identity",
113    "delivered",
114    "waited_s",
115];
116
117/// The kinds of event a supervision turn is not shown among the print's
118/// events: the server's camera and file-index bookkeeping. What each decides
119/// for a check, the turn's situation states once as the image it was handed
120/// and why, so read again they would only cost every turn their hashes,
121/// landmarks and matrices. The operator's own reads keep every one.
122///
123/// The camera's four are declared by the server, which this crate does not
124/// depend on; the server's own test holds this list to their kinds.
125pub const UNREAD_EVENT_KINDS: [&str; 5] = [
126    "camera_view_judged",
127    "camera_view_refit",
128    "check_image_changed",
129    "first_layer_alignment_judged",
130    <crate::kinds::GcodeIndexedPayload as EventPayload>::KIND,
131];
132
133/// What a supervision turn reads about one print: [`PrintContext`] with each
134/// fact stated once, as it is now, and nothing no supervision decision reads.
135///
136/// Left out of it, each because no step of the skill, no check and no recorded
137/// case decides anything by it: the print's file, provider and times; the
138/// printer's and the job's own states (the print states it once); every heater's
139/// offset, the chamber and the time they were read; the printer's reported
140/// feedrate, flowrate and fan (the slicer's plan states the flow and fan in
141/// force, and no step reads the feedrate); the job's file, size, progress, time
142/// and position (the plan states where the print is); the manifest (its limits
143/// are the bounds); and the detector's health beyond its status — since when,
144/// and why — which only the status read carries.
145///
146/// The printer and the job are stated here and nowhere in the events; each
147/// event is what happened, when, and what it changed; and asked `since` an
148/// event, only the events newer than it are carried, so a turn that has read
149/// the rest is not handed them again. `newest_event` is what the next read
150/// asks `since`.
151#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
152#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
153#[schemars(crate = "printobserver_types::schemars")]
154pub struct AgentContext {
155    /// The print.
156    pub print: AgentPrint,
157    /// The printer's heaters now, when they could be read.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub printer: Option<AgentPrinter>,
160    /// The error the job stopped on, when it stopped on one.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub job_error: Option<JobError>,
163    /// The limits in force, so that the agent can see them before it asks.
164    pub bounds: EffectiveBounds,
165    /// The interventions still active.
166    pub interventions: Vec<Intervention>,
167    /// What the failure detector's status is for this print: whether it is
168    /// scoring the print and has flagged it, or what it is otherwise.
169    pub detector: DetectorHealthStatus,
170    /// This print's events newer than the one asked `since`, or its recent
171    /// ones when none was named, newest first.
172    pub recent_events: Vec<AgentEvent>,
173    /// The most recent image, whose path is answered beside the context and
174    /// whose record states its digest.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub latest_image: Option<ImageRef>,
177    /// The newest event of this print's, which a later read asks `since`:
178    /// absent only when the print has none.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub newest_event: Option<EventId>,
181    /// What the slicer planned at the job's current file position.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub slicer: Option<AgentSlicerPlan>,
184}
185
186/// One stop the print's own G-code plans, as a turn reads it: [`PlannedChange`]
187/// numbered the way a person counts a print's changes, the first being 1.
188///
189/// The record a change is kept under counts from 0, as the file's own order
190/// does; a turn is never handed that count, so that the number it reads and the
191/// number it says are the ones the operator says.
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
193#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
194#[schemars(
195    crate = "printobserver_types::schemars",
196    transform = crate::gcode_index::null_is_sent
197)]
198pub struct AgentPlannedChange {
199    /// Its number among the file's changes, counting from 1 in file order.
200    #[schemars(range(min = 1))]
201    pub number: u32,
202    /// What it stops the print for.
203    pub kind: PlannedChangeKind,
204    /// The byte offset of the first byte of its `M600` or `M601` line.
205    pub offset_bytes: u64,
206    /// The first layer printed after it, counting the first as 1: the layer
207    /// whose `;Z:` is the change's height.
208    pub layer: u32,
209    /// That layer's height, in millimetres.
210    pub z_mm: f64,
211    /// The colour loaded at it, as `#RRGGBB` in upper case; null for an
212    /// `M601`, and for an `M600` whose file names no colour.
213    pub color: Option<String>,
214}
215
216impl From<&PlannedChange> for AgentPlannedChange {
217    fn from(change: &PlannedChange) -> Self {
218        Self {
219            number: change.index.saturating_add(1),
220            kind: change.kind,
221            offset_bytes: change.offset_bytes,
222            layer: change.layer,
223            z_mm: change.z_mm,
224            color: change.color.clone(),
225        }
226    }
227}
228
229/// What the slicer planned at the job's current file position, as a turn reads
230/// it: [`SlicerPlan`] with each planned change an [`AgentPlannedChange`].
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
232#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
233#[schemars(crate = "printobserver_types::schemars")]
234pub struct AgentSlicerPlan {
235    /// The colour the print should be laying at the current position, as
236    /// `#RRGGBB`; absent when the file plans no change or names no colour
237    /// there.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub expected_color: Option<String>,
240    /// The next change the file plans after the current position; absent when
241    /// it plans none there.
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub next_change: Option<AgentPlannedChange>,
244    /// The slicer's own count of the minutes to that change, from the latest
245    /// `M73 C` the position has reached; absent when there is no next change
246    /// or no count.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub minutes_to_next_change: Option<i64>,
249    /// The planned change the printer is waiting at now, for a person to
250    /// finish; absent when it is waiting at none.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub change_waiting: Option<AgentPlannedChange>,
253    /// The layer the print is in, counting the first as 1; absent before the
254    /// first.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub layer: Option<usize>,
257    /// The current layer's height, in millimetres.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub z_mm: Option<f64>,
260    /// The final layer's height, in millimetres.
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub final_z_mm: Option<f64>,
263    /// What the current layer lays material as, in the order the file first
264    /// names each: `Perimeter`, `Support material`, `Bridge infill`.
265    #[serde(default, skip_serializing_if = "Vec::is_empty")]
266    pub types: Vec<String>,
267    /// The slicer's own estimate of the minutes left, at the current position.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub minutes_left: Option<i64>,
270    /// The flow factor, one meaning one hundred percent.
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub flow_factor: Option<SetValue>,
273    /// The part-cooling fan speed, in percent.
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub fan_percent: Option<SetValue>,
276    /// How many objects the file lays down; absent when it labels none.
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub object_count: Option<usize>,
279    /// The bed area each object the file lays down covers, unnamed, as
280    /// `[x_min, y_min, x_max, y_max]` in whole millimetres, in the order of
281    /// the file's object numbers.
282    #[serde(default, skip_serializing_if = "Vec::is_empty")]
283    pub objects: Vec<BedArea>,
284    /// How far the plan has risen since an earlier frame; absent before any
285    /// frame is half an hour old.
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub rise: Option<Rise>,
288    /// Each setting in force the plan at this height says is wrong.
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub at_odds: Vec<PlanMismatch>,
291    /// The facts the file does not state, which are therefore unknown rather
292    /// than absent.
293    #[serde(default, skip_serializing_if = "Vec::is_empty")]
294    pub unknown: Vec<PlanFact>,
295}
296
297impl From<&SlicerPlan> for AgentSlicerPlan {
298    fn from(plan: &SlicerPlan) -> Self {
299        Self {
300            expected_color: plan.expected_color.clone(),
301            next_change: plan.next_change.as_ref().map(AgentPlannedChange::from),
302            minutes_to_next_change: plan.minutes_to_next_change,
303            change_waiting: plan.change_waiting.as_ref().map(AgentPlannedChange::from),
304            layer: plan.layer,
305            z_mm: plan.z_mm,
306            final_z_mm: plan.final_z_mm,
307            types: plan.types.clone(),
308            minutes_left: plan.minutes_left,
309            flow_factor: plan.flow_factor.clone(),
310            fan_percent: plan.fan_percent.clone(),
311            object_count: plan.object_count,
312            objects: plan.objects.clone(),
313            rise: plan.rise.clone(),
314            at_odds: plan.at_odds.clone(),
315            unknown: plan.unknown.clone(),
316        }
317    }
318}
319
320/// The print a context is about.
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
322#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
323#[schemars(crate = "printobserver_types::schemars")]
324pub struct AgentPrint {
325    /// Its identifier.
326    pub id: PrintId,
327    /// What the printer was last found doing with it, or the state it ended in.
328    pub state: PrinterState,
329    /// Why it ended, once it has.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub end_reason: Option<String>,
332}
333
334/// The printer's heaters as they are now.
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
336#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
337#[schemars(crate = "printobserver_types::schemars")]
338pub struct AgentPrinter {
339    /// Each tool's heater, in order.
340    #[serde(default, skip_serializing_if = "Vec::is_empty")]
341    pub tools: Vec<AgentHeater>,
342    /// The bed's heater, when it has one.
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub bed: Option<AgentHeater>,
345}
346
347/// One heater, in degrees Celsius: each reading absent when the printer did not
348/// report it, or reported one outside what a heater can read.
349#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
350#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
351#[schemars(crate = "printobserver_types::schemars")]
352pub struct AgentHeater {
353    /// The temperature it is at.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub actual_c: Option<f64>,
356    /// The temperature it is driving towards.
357    #[serde(default, skip_serializing_if = "Option::is_none")]
358    pub target_c: Option<f64>,
359}
360
361/// One event of the print's, as a turn reads it: what happened, when, and the
362/// facts it changed.
363#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
364#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
365#[schemars(crate = "printobserver_types::schemars")]
366pub struct AgentEvent {
367    /// Its identifier, which a later read asks `since`.
368    pub id: EventId,
369    /// What kind of event it is.
370    pub kind: EventKind,
371    /// When it was received.
372    pub received_at: Timestamp,
373    /// What it carried, less the snapshots the context states once, the
374    /// agent's own assessment and the bookkeeping no decision reads.
375    #[serde(default, skip_serializing_if = "is_empty_payload")]
376    pub payload: Value,
377}
378
379/// Whether a payload says nothing.
380fn is_empty_payload(payload: &Value) -> bool {
381    match payload {
382        Value::Null => true,
383        Value::Object(fields) => fields.is_empty(),
384        _ => false,
385    }
386}
387
388/// The events a context read asked `since` one carries: that event, and the
389/// print's events newer than it, newest first.
390#[derive(Debug, Clone, Copy)]
391pub struct Since<'events> {
392    /// The event named.
393    pub event: EventId,
394    /// Every event of the print's newer than it, newest first.
395    pub newer: &'events [EventRecord],
396}
397
398impl PrintContext {
399    /// What a supervision turn reads of this context: its recent events, or
400    /// those `since` names when it names any.
401    #[must_use]
402    pub fn for_agent(&self, since: Option<Since<'_>>) -> AgentContext {
403        let heater = |heater: &HeaterSnapshot| AgentHeater {
404            actual_c: in_range(heater.actual_c.as_ref()),
405            target_c: in_range(heater.target_c.as_ref()),
406        };
407        let (events, newest_event) = match since {
408            Some(since) => (
409                since.newer,
410                Some(since.newer.first().map_or(since.event, |newest| newest.id)),
411            ),
412            None => (
413                self.recent_events.as_slice(),
414                self.recent_events.first().map(|newest| newest.id),
415            ),
416        };
417        AgentContext {
418            print: AgentPrint {
419                id: self.print.id,
420                state: self.print.state.clone(),
421                end_reason: self.print.end_reason.clone(),
422            },
423            printer: self.printer.as_ref().map(|printer| AgentPrinter {
424                tools: printer.tools.iter().map(heater).collect(),
425                bed: printer.bed.as_ref().map(heater),
426            }),
427            job_error: self.job.as_ref().and_then(|job| job.error.clone()),
428            bounds: self.bounds.clone(),
429            interventions: self.interventions.clone(),
430            detector: self.detector.status(),
431            recent_events: events
432                .iter()
433                .filter(|event| !UNREAD_EVENT_KINDS.contains(&event.kind().as_str()))
434                .map(agent_event)
435                .collect(),
436            latest_image: self.latest_image.clone(),
437            newest_event,
438            slicer: self.slicer.as_ref().map(AgentSlicerPlan::from),
439        }
440    }
441}
442
443/// The facts a supervision turn is handed up front: the context read as the
444/// turn began, as [`AgentContext`] answers it — and no field that answer does
445/// not carry — with its events cut to [`unseen_events`]: what happened that the
446/// agent has not been shown, which its own conversation does not hold.
447///
448/// What the turn is handed beside its facts is not stated in them again: its
449/// own event, `shown`, which it is handed whole, is left out of the events, and
450/// out of `newest_event` when it is the newest; and `latest_image` is left out,
451/// the turn being handed its image and none of its commands reading that
452/// record.
453#[must_use]
454pub fn turn_facts(
455    context: &AgentContext,
456    shown: EventId,
457) -> Option<printobserver_types::serde_json::Map<String, Value>> {
458    let mut facts = context.clone();
459    facts.recent_events = unseen_events(&context.recent_events);
460    facts.recent_events.retain(|event| event.id != shown);
461    facts.newest_event = facts.newest_event.filter(|newest| *newest != shown);
462    facts.latest_image = None;
463    match printobserver_types::serde_json::to_value(facts) {
464        Ok(Value::Object(fields)) => Some(fields),
465        _ => None,
466    }
467}
468
469/// Of a print's events, newest first, those the agent has not been shown:
470/// every event newer than its last answer, and every one that arrived while
471/// the turn behind that answer ran — after the event that turn answered, which
472/// its acknowledgement names — and was not that turn's own doing: a person's
473/// resume taken as the agent answered, or the printer's own report. The turn's
474/// own requests, their outcomes and what it recorded of itself are left out, and
475/// so is the acknowledgement written from that answer after the turn ended, with
476/// its outcome: the conversation already holds the answer it was written from. A
477/// print the agent has not answered on keeps every event; one whose answered
478/// event cannot be found keeps every event back to the answer before, its
479/// own aside, because one shown twice costs less than one never shown.
480#[must_use]
481pub fn unseen_events(events: &[AgentEvent]) -> Vec<AgentEvent> {
482    let is_answer = |event: &AgentEvent| {
483        event.kind.as_str() == <crate::kinds::AgentAssessmentPayload as EventPayload>::KIND
484    };
485    let Some(answered) = events.iter().position(is_answer) else {
486        return events.to_vec();
487    };
488    let (newer, older) = events.split_at(answered);
489    let older = &older[1..];
490    let turn = &older[..older.iter().position(is_answer).unwrap_or(older.len())];
491    let during = events
492        .iter()
493        .find_map(agents_acknowledged_event)
494        .and_then(|answered_event| turn.iter().position(|event| event.id == answered_event))
495        .map_or(turn, |at| &turn[..at]);
496    let own: Vec<&Value> = during
497        .iter()
498        .filter(|event| is_agents_request(event))
499        .filter_map(|event| event.payload.get("action_id"))
500        .collect();
501    let acknowledged: Vec<&Value> = newer
502        .iter()
503        .filter(|event| agents_acknowledged_event(event).is_some())
504        .filter_map(|event| event.payload.get("action_id"))
505        .collect();
506    let mut unseen: Vec<AgentEvent> = newer
507        .iter()
508        .filter(|event| {
509            !event
510                .payload
511                .get("action_id")
512                .is_some_and(|action| acknowledged.contains(&action))
513        })
514        .cloned()
515        .collect();
516    unseen.extend(
517        during
518            .iter()
519            .filter(|event| {
520                !TURNS_OWN_KINDS.contains(&event.kind.as_str())
521                    && !event
522                        .payload
523                        .get("action_id")
524                        .is_some_and(|action| own.contains(&action))
525            })
526            .cloned(),
527    );
528    unseen
529}
530
531/// What a turn records of itself as it runs: the looks it took and the session
532/// it opened, which it already saw or has no use for.
533const TURNS_OWN_KINDS: [&str; 2] = [
534    <crate::kinds::CameraLookPayload as EventPayload>::KIND,
535    <printobserver_supervisor_api::SupervisionSessionOpenedPayload as EventPayload>::KIND,
536];
537
538/// Whether an event is a request the agent made.
539fn is_agents_request(event: &AgentEvent) -> bool {
540    event.kind.as_str() == <crate::kinds::ActionRequestedPayload as EventPayload>::KIND
541        && event
542            .payload
543            .get("actor")
544            .is_some_and(|actor| actor.get("agent").is_some())
545}
546
547/// The event an acknowledgement the agent asked for names, when this is one.
548fn agents_acknowledged_event(event: &AgentEvent) -> Option<EventId> {
549    if !is_agents_request(event) {
550        return None;
551    }
552    let action = event.payload.get("action")?;
553    if action.get("action")?.as_str()? != "acknowledge_failure" {
554        return None;
555    }
556    printobserver_types::serde_json::from_value(action.get("event_id")?.clone()).ok()
557}
558
559/// The events newer than `since`, newest first, when `events` — newest first —
560/// holds it.
561#[must_use]
562pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
563    events
564        .iter()
565        .position(|event| event.id == since)
566        .map(|at| &events[..at])
567}
568
569/// A reading in range, as its value alone.
570fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
571    reported
572        .filter(|reported| !reported.out_of_range())
573        .map(Reported::value)
574}
575
576/// One event, as a turn reads it.
577fn agent_event(event: &EventRecord) -> AgentEvent {
578    let mut payload = event.body.payload.clone();
579    if let Value::Object(fields) = &mut payload {
580        for unread in UNREAD_PAYLOAD_FIELDS {
581            fields.remove(unread);
582        }
583    }
584    number_planned_changes(&mut payload);
585    AgentEvent {
586        id: event.id,
587        kind: event.kind().clone(),
588        received_at: event.received_at,
589        payload,
590    }
591}
592
593/// One event as a turn is shown it, whether as its trigger or among those that
594/// arrived while another turn ran: the event itself, each planned change its
595/// payload names numbered from 1 ([`number_planned_changes`]).
596#[must_use]
597pub(crate) fn as_a_turn_reads(event: &EventRecord) -> EventRecord {
598    let mut shown = event.clone();
599    number_planned_changes(&mut shown.body.payload);
600    shown
601}
602
603/// The count-from-0 fields a payload may name a planned change by, each with
604/// the count-from-1 field a turn reads in its place.
605const PLANNED_CHANGE_INDICES: [(&str, &str); 2] = [
606    ("change_index", "change_number"),
607    ("planned_change", "planned_change_number"),
608];
609
610/// Number every planned change a payload names from 1, as a turn reads one.
611///
612/// A [`PlannedChange`] a payload carries — the change a print reached or
613/// carried on from — is written as an [`AgentPlannedChange`]; a refusal's
614/// `change_index` and a filament change signal's `planned_change` are written
615/// as `change_number` and `planned_change_number`, one more. Nothing else is
616/// touched, so a turn is never handed a planned change counted from 0.
617fn number_planned_changes(value: &mut Value) {
618    match value {
619        Value::Object(fields) => {
620            for (index, number) in PLANNED_CHANGE_INDICES {
621                if let Some(counted) = fields.get(index).and_then(Value::as_u64) {
622                    fields.remove(index);
623                    fields.insert(number.to_owned(), Value::from(counted.saturating_add(1)));
624                }
625            }
626            if let Some(change) = fields.get_mut("change") {
627                let numbered =
628                    printobserver_types::serde_json::from_value::<PlannedChange>(change.clone())
629                        .ok()
630                        .and_then(|planned| {
631                            printobserver_types::serde_json::to_value(AgentPlannedChange::from(
632                                &planned,
633                            ))
634                            .ok()
635                        });
636                if let Some(numbered) = numbered {
637                    *change = numbered;
638                }
639            }
640            fields.values_mut().for_each(number_planned_changes);
641        }
642        Value::Array(items) => items.iter_mut().for_each(number_planned_changes),
643        _ => {}
644    }
645}
646
647impl Sample for AgentContext {
648    fn sample_full() -> Self {
649        PrintContext::sample_full().for_agent(None)
650    }
651
652    fn sample_minimal() -> Self {
653        PrintContext::sample_minimal().for_agent(None)
654    }
655}