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