mur-common 2.103.0

Shared types and traits for the MUR ecosystem
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
//! Pure Channel types — no I/O; store logic lives in the `mur-channel` crate.
//!
//! Durable on-disk formats:
//!   - `~/.mur/channels/<id>/events.jsonl` — append-only event log
//!   - `~/.mur/channels/<id>/channel.yaml` — manifest (cached view of log state)
//!
//! # Schema versioning
//!
//! [`CHANNEL_SCHEMA_VERSION`] guards both the event log rows and the manifest.
//! Bump it ONLY when:
//!   1. A required field is renamed or removed, OR
//!   2. A field's semantic meaning changes, OR
//!   3. A new `EventKind` variant carries semantics that older readers must not
//!      silently skip (readers skip unknown/unparseable lines for robustness, so
//!      bump only when a silent skip would corrupt state rather than merely omit
//!      optional data).
//!
//! Adding a new optional field with `#[serde(default)]` does NOT require a bump.
//!
//! ## Backward reads
//! The event log must always remain fold-able from the beginning. When adding new
//! optional fields, annotate them with `#[serde(default)]` so older rows written
//! before the field existed still deserialize cleanly. Manifests follow the same
//! rule: older `channel.yaml` files must load without error.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Schema version for the manifest + event log; breaking changes bump this.
/// v2: `HitlResponse` events carry approval authority — a reader that silently
/// skips one could re-apply a gated effect (v3c).
/// v3: the log may carry a human-signed `owner-key-enrolled` record, the
/// channel's trust root — a reader that skips it would trust or distrust
/// human events wrongly (at-mention phase 2).
pub const CHANNEL_SCHEMA_VERSION: u32 = 3;

/// A2A v0.3 lifecycle vocabulary, serialized on the wire as kebab-case
/// (`input-required`, `canceled`, etc.).
///
/// ## Spelling note
/// `Canceled` (→ `"canceled"`) intentionally follows the A2A v0.3 spec spelling
/// and is a DISTINCT type from [`crate::a2a::TaskState`], which spells the
/// equivalent variant `Cancelled` (two l's). The two enums are bridged by an
/// explicit boundary mapping — not string equality — so the spelling difference
/// is deliberate, not a bug.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ChannelState {
    Submitted,
    Working,
    InputRequired,
    Completed,
    Failed,
    Canceled,
    Rejected,
    /// MUR extension (not in A2A v0.3): the channel has had no activity for an
    /// extended period and was system-marked stale.
    Stale,
}

/// Why a channel exists. Deliberately smaller than the ways a UI may render a
/// channel: Direct vs Group is derived from participants, and Companion/HITL
/// are event-derived states — none of them are purposes.
///
/// `Option<ChannelPurpose>` on `Channel`: `None` means "written before this
/// field existed" and MUST NOT be treated as an explicit `Conversation`.
/// Resolve it for display with `mur_channel::purpose::effective_purpose`;
/// correct it on disk only with `mur channel backfill-purpose`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ChannelPurpose {
    Conversation,
    FleetRun,
    WorkflowRun,
}

/// Who produced an event / is a participant. Named `ChannelActor` to avoid
/// colliding with the pre-existing `mur_common::actor::Actor`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ChannelActor {
    Human {
        name: String,
        /// The human owner's public key (multibase) when the event is signed
        /// with it (at-mention phase 2, D-4). Absent on every event written
        /// before phase 2, and omitted on the wire when `None`, so those
        /// events serialize — and therefore sign — byte-identically.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        key: Option<String>,
    },
    Agent {
        id: String,
    },
    System,
}

impl ChannelActor {
    /// The local human owner, from `$USER`/`$USERNAME`, falling back to `you`.
    pub fn local_human() -> Self {
        let name = std::env::var("USER")
            .or_else(|_| std::env::var("USERNAME"))
            .ok()
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "you".to_string());
        ChannelActor::Human { name, key: None }
    }

    /// [`Self::local_human`] carrying the human owner's public key, for an
    /// event signed with it (at-mention phase 2, D-4).
    pub fn local_human_with_key(key: impl Into<String>) -> Self {
        match Self::local_human() {
            ChannelActor::Human { name, .. } => ChannelActor::Human {
                name,
                key: Some(key.into()),
            },
            other => other,
        }
    }
}

/// The role a participant plays within a channel's lifecycle.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ParticipantRole {
    Owner,
    Router,
    Delegate,
    Observer,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Participant {
    pub actor: ChannelActor,
    pub role: ParticipantRole,
    pub joined_at: DateTime<Utc>,
}

/// The intent a channel is working toward, with optional acceptance criteria.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Goal {
    #[serde(default)]
    pub statement: String,
    #[serde(default)]
    pub acceptance_criteria: Vec<String>,
}

/// The durable manifest (a cache of state derivable from the event log).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Channel {
    pub v: u32,
    pub id: String,
    pub title: String,
    #[serde(default)]
    pub goal: Goal,
    pub state: ChannelState,
    /// Why this channel exists. `None` = legacy manifest; see `ChannelPurpose`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purpose: Option<ChannelPurpose>,
    pub owner: ChannelActor,
    #[serde(default)]
    pub participants: Vec<Participant>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum EventKind {
    Message,
    Delegation,
    Handoff,
    ToolCall,
    ToolResult,
    StateChange,
    Artifact,
    HitlRequest,
    HitlResponse,
    Note,
    /// One agent asks another a question (channel consult). Signed by the
    /// asker; the payload is an [`AskPayload`] and `idempotency_key` equals
    /// its `nonce`. Not agent progress: readers that count agent output skip it.
    Ask,
    /// The answerer's reply to an [`EventKind::Ask`]; the payload is an
    /// [`AskReplyPayload`]. Not agent progress, a fleet reply, or a final answer.
    AskReply,
    /// Withdraws one earlier `Human` `Message` from conversation history; the
    /// payload is a [`RetractPayload`]. Readers that fold history skip the
    /// target and this line; audit readers keep both. Not agent progress.
    Retract,
    /// Enrolls the human owner's key for this channel; the payload is an
    /// [`OwnerKeyEnrolledPayload`] (at-mention phase 2, D-5). Not agent
    /// progress. Nothing writes it until phase 2 PR 2.
    OwnerKeyEnrolled,
}

impl EventKind {
    /// True for the consult kinds, which an agent writes beside its work
    /// rather than as part of it. Readers that treat any agent-authored event
    /// as progress, a reply, or a final answer must exclude these.
    pub fn is_consult(self) -> bool {
        matches!(self, EventKind::Ask | EventKind::AskReply)
    }
}

/// Payload of an [`EventKind::Ask`] event. Every field is inside the signed
/// input, so the answerer, the deadline and the nonce cannot be rewritten
/// without breaking the asker's signature.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AskPayload {
    /// The answering agent's name. Only that agent may answer.
    pub to: String,
    /// The question text the answerer sees.
    pub question: String,
    /// Unix-epoch milliseconds after which the answerer refuses the `Ask`.
    pub expires_at_ms: i64,
    /// Single-use id; the event's `idempotency_key` carries the same value.
    pub nonce: String,
}

/// Payload of an [`EventKind::AskReply`] event.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AskReplyPayload {
    /// The `nonce` of the [`AskPayload`] this answers.
    pub nonce: String,
    /// The answer text.
    pub text: String,
}

/// The last pre-enrollment line of a channel (at-mention phase 2, D-6):
/// history up to and including `seq` stays trusted under the router's
/// signature. `line_hash` is `mur_channel::store::chain::line_hash` of the raw
/// line at `seq`, because v1-era events carry no `prev_hash` to hash.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HumanCut {
    pub seq: u64,
    pub line_hash: String,
}

/// Payload of an [`EventKind::OwnerKeyEnrolled`] event (at-mention phase 2,
/// D-5/D-6). Owner state lives only in this signed record, never in the
/// manifest.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct OwnerKeyEnrolledPayload {
    /// The human owner's public key (multibase).
    pub owner_key: String,
    pub key_version: u32,
    /// `None` for a channel created with an owner, so nothing predates it.
    pub human_cut: Option<HumanCut>,
}

/// Why a [`EventKind::Retract`] was written. Closed vocabulary.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum RetractReason {
    /// The user cancelled the turn before it produced anything.
    Cancelled,
}

/// Payload of an [`EventKind::Retract`] event.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RetractPayload {
    /// `seq` of the withdrawn event.
    pub target_seq: u64,
    pub reason: RetractReason,
}

/// The `idempotency_key` of the retract of `target_seq`, so a retried append
/// is a no-op.
pub fn retract_idempotency_key(target_seq: u64) -> String {
    format!("retract:{target_seq}")
}

/// Key inside an `Agent` `Note` payload that records the runtime refusing a
/// retract (the cancelled turn had already run tools, so the model keeps the
/// message). A `Note`, not a new `EventKind`, so older readers still parse
/// the line. History readers honour it: the target stays visible, matching
/// what the model sees.
pub const RETRACT_REFUSED_PAYLOAD_KEY: &str = "retract_refused";

/// Body of a [`RETRACT_REFUSED_PAYLOAD_KEY`] note.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct RetractRefusal {
    /// `seq` of the message the retract tried to withdraw.
    pub target_seq: u64,
}

impl RetractRefusal {
    /// The note payload; `text` is for tails (`mur channel follow`).
    pub fn to_payload(self) -> serde_json::Value {
        serde_json::json!({
            RETRACT_REFUSED_PAYLOAD_KEY: self,
            "text": format!(
                "kept message #{}: the cancelled turn had already run tools",
                self.target_seq
            ),
        })
    }

    /// `None` = not a refusal note (or a malformed one).
    pub fn from_payload(payload: &serde_json::Value) -> Option<Self> {
        serde_json::from_value(payload.get(RETRACT_REFUSED_PAYLOAD_KEY)?.clone()).ok()
    }
}

/// The `idempotency_key` of the refusal of `target_seq`'s retract, so a
/// refusal re-observed on a later turn appends nothing.
pub fn retract_refused_idempotency_key(target_seq: u64) -> String {
    format!("retract-refused:{target_seq}")
}

/// One append-only line in `~/.mur/channels/<id>/events.jsonl`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelEvent {
    pub seq: u64,
    pub ts: DateTime<Utc>,
    pub actor: ChannelActor,
    pub kind: EventKind,
    #[serde(default)]
    pub payload: serde_json::Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
    /// Detached Ed25519 signature (multibase) by the channel's WRITER over the
    /// canonical sign-input `{v, channel_id, actor, kind, payload,
    /// idempotency_key}` — EXCLUDING the store-assigned `seq`/`ts` (see
    /// `mur-channel` `sign::sign_input`). `None` for legacy/unsigned events.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sig: Option<String>,
    /// RESERVED — key version for the signing key (v3d).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key_version: Option<u32>,
    /// Hex SHA-256 of the previous raw line in `events.jsonl` (or the genesis
    /// constant for the first line). Set only on sig-input v2 events, which
    /// sign over it; `None` for v1 (externally signed) and unsigned events.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prev_hash: Option<String>,
}

impl ChannelEvent {
    /// True for a human-authored `Message`: something the user typed. Other
    /// human kinds (`OwnerKeyEnrolled`, `HitlResponse`, `Retract`) are control
    /// lines, so a history reader that replays or previews human turns takes
    /// only these (at-mention phase 2, C7).
    pub fn is_human_message(&self) -> bool {
        self.kind == EventKind::Message && matches!(self.actor, ChannelActor::Human { .. })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn human_without_key_serializes_without_key_field() {
        let a = ChannelActor::Human {
            name: "david".into(),
            key: None,
        };
        assert_eq!(
            serde_json::to_string(&a).unwrap(),
            r#"{"kind":"human","name":"david"}"#
        );
        let back: ChannelActor =
            serde_json::from_str(r#"{"kind":"human","name":"david"}"#).unwrap();
        assert_eq!(back, a);
        let keyed = ChannelActor::Human {
            name: "david".into(),
            key: Some("zKey".into()),
        };
        assert_eq!(
            serde_json::to_string(&keyed).unwrap(),
            r#"{"kind":"human","name":"david","key":"zKey"}"#
        );
    }

    #[test]
    fn owner_key_enrolled_wire_spelling_is_kebab() {
        assert_eq!(
            serde_json::to_string(&EventKind::OwnerKeyEnrolled).unwrap(),
            r#""owner-key-enrolled""#
        );
        let p = OwnerKeyEnrolledPayload {
            owner_key: "zKey".into(),
            key_version: 1,
            human_cut: Some(HumanCut {
                seq: 4,
                line_hash: "ab".into(),
            }),
        };
        let v = serde_json::to_value(&p).unwrap();
        assert_eq!(v["human_cut"]["seq"], 4);
        assert_eq!(
            serde_json::from_value::<OwnerKeyEnrolledPayload>(v).unwrap(),
            p
        );
    }

    #[test]
    fn local_human_with_key_keeps_the_local_name() {
        let ChannelActor::Human { name, .. } = ChannelActor::local_human() else {
            panic!("local_human is Human");
        };
        assert_eq!(
            ChannelActor::local_human_with_key("zKey"),
            ChannelActor::Human {
                name,
                key: Some("zKey".into())
            }
        );
    }

    #[test]
    fn channel_state_serializes_kebab() {
        let j = serde_json::to_string(&ChannelState::InputRequired).unwrap();
        assert_eq!(j, "\"input-required\"");
    }

    #[test]
    fn event_round_trips() {
        let ev = ChannelEvent {
            seq: 3,
            ts: Utc::now(),
            actor: ChannelActor::Agent { id: "qa".into() },
            kind: EventKind::Message,
            payload: serde_json::json!({ "text": "hello", "task_id": "t-1" }),
            idempotency_key: None,
            sig: None,
            key_version: None,
            prev_hash: None,
        };
        let line = serde_json::to_string(&ev).unwrap();
        let back: ChannelEvent = serde_json::from_str(&line).unwrap();
        assert_eq!(back.seq, 3);
        assert_eq!(back.actor, ChannelActor::Agent { id: "qa".into() });
        assert_eq!(back.payload["text"], "hello");
    }

    #[test]
    fn consult_kinds_round_trip_in_kebab_case() {
        for (kind, wire) in [
            (EventKind::Ask, "\"ask\""),
            (EventKind::AskReply, "\"ask-reply\""),
        ] {
            assert_eq!(serde_json::to_string(&kind).unwrap(), wire);
            assert_eq!(serde_json::from_str::<EventKind>(wire).unwrap(), kind);
            assert!(kind.is_consult());
        }
        assert!(!EventKind::Message.is_consult());
    }

    #[test]
    fn retract_round_trips_with_typed_payload() {
        assert_eq!(
            serde_json::to_string(&EventKind::Retract).unwrap(),
            "\"retract\""
        );
        assert!(!EventKind::Retract.is_consult());
        let p = RetractPayload {
            target_seq: 41,
            reason: RetractReason::Cancelled,
        };
        let v = serde_json::to_value(&p).unwrap();
        assert_eq!(
            v,
            serde_json::json!({ "target_seq": 41, "reason": "cancelled" })
        );
        assert_eq!(serde_json::from_value::<RetractPayload>(v).unwrap(), p);
        assert_eq!(retract_idempotency_key(41), "retract:41");
    }

    #[test]
    fn ask_event_round_trips_with_typed_payload() {
        let ask = AskPayload {
            to: "tech-writer".into(),
            question: "what does R7 cover?".into(),
            expires_at_ms: 1_700_000_000_000,
            nonce: "n1".into(),
        };
        let ev = ChannelEvent {
            seq: 4,
            ts: Utc::now(),
            actor: ChannelActor::Agent { id: "pm".into() },
            kind: EventKind::Ask,
            payload: serde_json::to_value(&ask).unwrap(),
            idempotency_key: Some(ask.nonce.clone()),
            sig: None,
            key_version: None,
            prev_hash: None,
        };
        let back: ChannelEvent =
            serde_json::from_str(&serde_json::to_string(&ev).unwrap()).unwrap();
        assert_eq!(back.kind, EventKind::Ask);
        let got: AskPayload = serde_json::from_value(back.payload).unwrap();
        assert_eq!(got, ask);

        let reply = AskReplyPayload {
            nonce: "n1".into(),
            text: "seq reuse".into(),
        };
        let v = serde_json::to_value(&reply).unwrap();
        assert_eq!(serde_json::from_value::<AskReplyPayload>(v).unwrap(), reply);
    }

    #[test]
    fn system_actor_round_trips() {
        let a = ChannelActor::System;
        let j = serde_json::to_string(&a).unwrap();
        assert_eq!(j, "{\"kind\":\"system\"}");
        let back: ChannelActor = serde_json::from_str(&j).unwrap();
        assert_eq!(back, ChannelActor::System);
    }

    #[test]
    fn event_omits_sig_fields_when_absent_and_reads_old_rows() {
        // New events with sig=None must omit the field from JSON (no schema churn).
        let ev = ChannelEvent {
            seq: 0,
            ts: Utc::now(),
            actor: ChannelActor::System,
            kind: EventKind::Note,
            payload: serde_json::json!({}),
            idempotency_key: None,
            sig: None,
            key_version: None,
            prev_hash: None,
        };
        let line = serde_json::to_string(&ev).unwrap();
        assert!(!line.contains("sig"), "sig must be omitted when None");
        assert!(
            !line.contains("key_version"),
            "key_version must be omitted when None"
        );

        // Old rows without the fields must deserialize cleanly.
        let old = r#"{"seq":0,"ts":"2026-06-16T00:00:00Z","actor":{"kind":"system"},"kind":"note","payload":{}}"#;
        let back: ChannelEvent = serde_json::from_str(old).unwrap();
        assert_eq!(back.sig, None);
        assert_eq!(back.key_version, None);
    }

    #[test]
    fn legacy_manifest_without_purpose_deserializes_as_none() {
        // A manifest written before this field existed. Must still load.
        let json = r#"{
            "v": 2,
            "id": "019ed0af-5e38-7912-b554-dc335a8fc2db",
            "title": "chat with mur",
            "state": "working",
            "owner": {"kind": "human", "name": "david"},
            "participants": [],
            "created_at": "2026-08-01T10:00:00Z",
            "updated_at": "2026-08-01T10:00:00Z"
        }"#;
        let ch: Channel = serde_json::from_str(json).expect("legacy manifest must deserialize");
        assert_eq!(
            ch.purpose, None,
            "absent purpose must be None, not a default"
        );
    }

    #[test]
    fn purpose_round_trips_in_kebab_case() {
        let json = r#"{
            "v": 2,
            "id": "x",
            "title": "t",
            "state": "working",
            "owner": {"kind": "system"},
            "participants": [],
            "purpose": "fleet-run",
            "created_at": "2026-08-01T10:00:00Z",
            "updated_at": "2026-08-01T10:00:00Z"
        }"#;
        let ch: Channel = serde_json::from_str(json).unwrap();
        assert_eq!(ch.purpose, Some(ChannelPurpose::FleetRun));

        let back = serde_json::to_string(&ch).unwrap();
        assert!(back.contains(r#""purpose":"fleet-run""#), "got: {back}");
    }

    #[test]
    fn purpose_is_omitted_when_none() {
        let json = r#"{
            "v": 2, "id": "x", "title": "t", "state": "working",
            "owner": {"kind": "system"}, "participants": [],
            "created_at": "2026-08-01T10:00:00Z",
            "updated_at": "2026-08-01T10:00:00Z"
        }"#;
        let ch: Channel = serde_json::from_str(json).unwrap();
        let back = serde_json::to_string(&ch).unwrap();
        assert!(
            !back.contains("purpose"),
            "a None purpose must not be written back as null: {back}"
        );
    }
}