Skip to main content

mur_common/
channel.rs

1//! Pure Channel types — no I/O; store logic lives in the `mur-channel` crate.
2//!
3//! Durable on-disk formats:
4//!   - `~/.mur/channels/<id>/events.jsonl` — append-only event log
5//!   - `~/.mur/channels/<id>/channel.yaml` — manifest (cached view of log state)
6//!
7//! # Schema versioning
8//!
9//! [`CHANNEL_SCHEMA_VERSION`] guards both the event log rows and the manifest.
10//! Bump it ONLY when:
11//!   1. A required field is renamed or removed, OR
12//!   2. A field's semantic meaning changes, OR
13//!   3. A new `EventKind` variant carries semantics that older readers must not
14//!      silently skip (readers skip unknown/unparseable lines for robustness, so
15//!      bump only when a silent skip would corrupt state rather than merely omit
16//!      optional data).
17//!
18//! Adding a new optional field with `#[serde(default)]` does NOT require a bump.
19//!
20//! ## Backward reads
21//! The event log must always remain fold-able from the beginning. When adding new
22//! optional fields, annotate them with `#[serde(default)]` so older rows written
23//! before the field existed still deserialize cleanly. Manifests follow the same
24//! rule: older `channel.yaml` files must load without error.
25
26use chrono::{DateTime, Utc};
27use serde::{Deserialize, Serialize};
28
29/// Schema version for the manifest + event log; breaking changes bump this.
30/// v2: `HitlResponse` events carry approval authority — a reader that silently
31/// skips one could re-apply a gated effect (v3c).
32/// v3: the log may carry a human-signed `owner-key-enrolled` record, the
33/// channel's trust root — a reader that skips it would trust or distrust
34/// human events wrongly (at-mention phase 2).
35pub const CHANNEL_SCHEMA_VERSION: u32 = 3;
36
37/// A2A v0.3 lifecycle vocabulary, serialized on the wire as kebab-case
38/// (`input-required`, `canceled`, etc.).
39///
40/// ## Spelling note
41/// `Canceled` (→ `"canceled"`) intentionally follows the A2A v0.3 spec spelling
42/// and is a DISTINCT type from [`crate::a2a::TaskState`], which spells the
43/// equivalent variant `Cancelled` (two l's). The two enums are bridged by an
44/// explicit boundary mapping — not string equality — so the spelling difference
45/// is deliberate, not a bug.
46#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
47#[serde(rename_all = "kebab-case")]
48pub enum ChannelState {
49    Submitted,
50    Working,
51    InputRequired,
52    Completed,
53    Failed,
54    Canceled,
55    Rejected,
56    /// MUR extension (not in A2A v0.3): the channel has had no activity for an
57    /// extended period and was system-marked stale.
58    Stale,
59}
60
61/// Why a channel exists. Deliberately smaller than the ways a UI may render a
62/// channel: Direct vs Group is derived from participants, and Companion/HITL
63/// are event-derived states — none of them are purposes.
64///
65/// `Option<ChannelPurpose>` on `Channel`: `None` means "written before this
66/// field existed" and MUST NOT be treated as an explicit `Conversation`.
67/// Resolve it for display with `mur_channel::purpose::effective_purpose`;
68/// correct it on disk only with `mur channel backfill-purpose`.
69#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
70#[serde(rename_all = "kebab-case")]
71pub enum ChannelPurpose {
72    Conversation,
73    FleetRun,
74    WorkflowRun,
75}
76
77/// Who produced an event / is a participant. Named `ChannelActor` to avoid
78/// colliding with the pre-existing `mur_common::actor::Actor`.
79#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
80#[serde(tag = "kind", rename_all = "kebab-case")]
81pub enum ChannelActor {
82    Human {
83        name: String,
84        /// The human owner's public key (multibase) when the event is signed
85        /// with it (at-mention phase 2, D-4). Absent on every event written
86        /// before phase 2, and omitted on the wire when `None`, so those
87        /// events serialize — and therefore sign — byte-identically.
88        #[serde(default, skip_serializing_if = "Option::is_none")]
89        key: Option<String>,
90    },
91    Agent {
92        id: String,
93    },
94    System,
95}
96
97impl ChannelActor {
98    /// The local human owner, from `$USER`/`$USERNAME`, falling back to `you`.
99    pub fn local_human() -> Self {
100        let name = std::env::var("USER")
101            .or_else(|_| std::env::var("USERNAME"))
102            .ok()
103            .filter(|s| !s.is_empty())
104            .unwrap_or_else(|| "you".to_string());
105        ChannelActor::Human { name, key: None }
106    }
107
108    /// [`Self::local_human`] carrying the human owner's public key, for an
109    /// event signed with it (at-mention phase 2, D-4).
110    pub fn local_human_with_key(key: impl Into<String>) -> Self {
111        match Self::local_human() {
112            ChannelActor::Human { name, .. } => ChannelActor::Human {
113                name,
114                key: Some(key.into()),
115            },
116            other => other,
117        }
118    }
119}
120
121/// The role a participant plays within a channel's lifecycle.
122#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
123#[serde(rename_all = "lowercase")]
124pub enum ParticipantRole {
125    Owner,
126    Router,
127    Delegate,
128    Observer,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct Participant {
133    pub actor: ChannelActor,
134    pub role: ParticipantRole,
135    pub joined_at: DateTime<Utc>,
136}
137
138/// The intent a channel is working toward, with optional acceptance criteria.
139#[derive(Debug, Clone, Default, Serialize, Deserialize)]
140pub struct Goal {
141    #[serde(default)]
142    pub statement: String,
143    #[serde(default)]
144    pub acceptance_criteria: Vec<String>,
145}
146
147/// The durable manifest (a cache of state derivable from the event log).
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct Channel {
150    pub v: u32,
151    pub id: String,
152    pub title: String,
153    #[serde(default)]
154    pub goal: Goal,
155    pub state: ChannelState,
156    /// Why this channel exists. `None` = legacy manifest; see `ChannelPurpose`.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub purpose: Option<ChannelPurpose>,
159    pub owner: ChannelActor,
160    #[serde(default)]
161    pub participants: Vec<Participant>,
162    pub created_at: DateTime<Utc>,
163    pub updated_at: DateTime<Utc>,
164}
165
166#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
167#[serde(rename_all = "kebab-case")]
168pub enum EventKind {
169    Message,
170    Delegation,
171    Handoff,
172    ToolCall,
173    ToolResult,
174    StateChange,
175    Artifact,
176    HitlRequest,
177    HitlResponse,
178    Note,
179    /// One agent asks another a question (channel consult). Signed by the
180    /// asker; the payload is an [`AskPayload`] and `idempotency_key` equals
181    /// its `nonce`. Not agent progress: readers that count agent output skip it.
182    Ask,
183    /// The answerer's reply to an [`EventKind::Ask`]; the payload is an
184    /// [`AskReplyPayload`]. Not agent progress, a fleet reply, or a final answer.
185    AskReply,
186    /// Withdraws one earlier `Human` `Message` from conversation history; the
187    /// payload is a [`RetractPayload`]. Readers that fold history skip the
188    /// target and this line; audit readers keep both. Not agent progress.
189    Retract,
190    /// Enrolls the human owner's key for this channel; the payload is an
191    /// [`OwnerKeyEnrolledPayload`] (at-mention phase 2, D-5). Not agent
192    /// progress. Nothing writes it until phase 2 PR 2.
193    OwnerKeyEnrolled,
194}
195
196impl EventKind {
197    /// True for the consult kinds, which an agent writes beside its work
198    /// rather than as part of it. Readers that treat any agent-authored event
199    /// as progress, a reply, or a final answer must exclude these.
200    pub fn is_consult(self) -> bool {
201        matches!(self, EventKind::Ask | EventKind::AskReply)
202    }
203}
204
205/// Payload of an [`EventKind::Ask`] event. Every field is inside the signed
206/// input, so the answerer, the deadline and the nonce cannot be rewritten
207/// without breaking the asker's signature.
208#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
209pub struct AskPayload {
210    /// The answering agent's name. Only that agent may answer.
211    pub to: String,
212    /// The question text the answerer sees.
213    pub question: String,
214    /// Unix-epoch milliseconds after which the answerer refuses the `Ask`.
215    pub expires_at_ms: i64,
216    /// Single-use id; the event's `idempotency_key` carries the same value.
217    pub nonce: String,
218}
219
220/// Payload of an [`EventKind::AskReply`] event.
221#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
222pub struct AskReplyPayload {
223    /// The `nonce` of the [`AskPayload`] this answers.
224    pub nonce: String,
225    /// The answer text.
226    pub text: String,
227}
228
229/// The last pre-enrollment line of a channel (at-mention phase 2, D-6):
230/// history up to and including `seq` stays trusted under the router's
231/// signature. `line_hash` is `mur_channel::store::chain::line_hash` of the raw
232/// line at `seq`, because v1-era events carry no `prev_hash` to hash.
233#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
234pub struct HumanCut {
235    pub seq: u64,
236    pub line_hash: String,
237}
238
239/// Payload of an [`EventKind::OwnerKeyEnrolled`] event (at-mention phase 2,
240/// D-5/D-6). Owner state lives only in this signed record, never in the
241/// manifest.
242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
243pub struct OwnerKeyEnrolledPayload {
244    /// The human owner's public key (multibase).
245    pub owner_key: String,
246    pub key_version: u32,
247    /// `None` for a channel created with an owner, so nothing predates it.
248    pub human_cut: Option<HumanCut>,
249}
250
251/// Why a [`EventKind::Retract`] was written. Closed vocabulary.
252#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
253#[serde(rename_all = "kebab-case")]
254pub enum RetractReason {
255    /// The user cancelled the turn before it produced anything.
256    Cancelled,
257}
258
259/// Payload of an [`EventKind::Retract`] event.
260#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
261pub struct RetractPayload {
262    /// `seq` of the withdrawn event.
263    pub target_seq: u64,
264    pub reason: RetractReason,
265}
266
267/// The `idempotency_key` of the retract of `target_seq`, so a retried append
268/// is a no-op.
269pub fn retract_idempotency_key(target_seq: u64) -> String {
270    format!("retract:{target_seq}")
271}
272
273/// Key inside an `Agent` `Note` payload that records the runtime refusing a
274/// retract (the cancelled turn had already run tools, so the model keeps the
275/// message). A `Note`, not a new `EventKind`, so older readers still parse
276/// the line. History readers honour it: the target stays visible, matching
277/// what the model sees.
278pub const RETRACT_REFUSED_PAYLOAD_KEY: &str = "retract_refused";
279
280/// Body of a [`RETRACT_REFUSED_PAYLOAD_KEY`] note.
281#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
282pub struct RetractRefusal {
283    /// `seq` of the message the retract tried to withdraw.
284    pub target_seq: u64,
285}
286
287impl RetractRefusal {
288    /// The note payload; `text` is for tails (`mur channel follow`).
289    pub fn to_payload(self) -> serde_json::Value {
290        serde_json::json!({
291            RETRACT_REFUSED_PAYLOAD_KEY: self,
292            "text": format!(
293                "kept message #{}: the cancelled turn had already run tools",
294                self.target_seq
295            ),
296        })
297    }
298
299    /// `None` = not a refusal note (or a malformed one).
300    pub fn from_payload(payload: &serde_json::Value) -> Option<Self> {
301        serde_json::from_value(payload.get(RETRACT_REFUSED_PAYLOAD_KEY)?.clone()).ok()
302    }
303}
304
305/// The `idempotency_key` of the refusal of `target_seq`'s retract, so a
306/// refusal re-observed on a later turn appends nothing.
307pub fn retract_refused_idempotency_key(target_seq: u64) -> String {
308    format!("retract-refused:{target_seq}")
309}
310
311/// One append-only line in `~/.mur/channels/<id>/events.jsonl`.
312#[derive(Debug, Clone, Serialize, Deserialize)]
313pub struct ChannelEvent {
314    pub seq: u64,
315    pub ts: DateTime<Utc>,
316    pub actor: ChannelActor,
317    pub kind: EventKind,
318    #[serde(default)]
319    pub payload: serde_json::Value,
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    pub idempotency_key: Option<String>,
322    /// Detached Ed25519 signature (multibase) by the channel's WRITER over the
323    /// canonical sign-input `{v, channel_id, actor, kind, payload,
324    /// idempotency_key}` — EXCLUDING the store-assigned `seq`/`ts` (see
325    /// `mur-channel` `sign::sign_input`). `None` for legacy/unsigned events.
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub sig: Option<String>,
328    /// RESERVED — key version for the signing key (v3d).
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub key_version: Option<u32>,
331    /// Hex SHA-256 of the previous raw line in `events.jsonl` (or the genesis
332    /// constant for the first line). Set only on sig-input v2 events, which
333    /// sign over it; `None` for v1 (externally signed) and unsigned events.
334    #[serde(default, skip_serializing_if = "Option::is_none")]
335    pub prev_hash: Option<String>,
336}
337
338impl ChannelEvent {
339    /// True for a human-authored `Message`: something the user typed. Other
340    /// human kinds (`OwnerKeyEnrolled`, `HitlResponse`, `Retract`) are control
341    /// lines, so a history reader that replays or previews human turns takes
342    /// only these (at-mention phase 2, C7).
343    pub fn is_human_message(&self) -> bool {
344        self.kind == EventKind::Message && matches!(self.actor, ChannelActor::Human { .. })
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    #[test]
353    fn human_without_key_serializes_without_key_field() {
354        let a = ChannelActor::Human {
355            name: "david".into(),
356            key: None,
357        };
358        assert_eq!(
359            serde_json::to_string(&a).unwrap(),
360            r#"{"kind":"human","name":"david"}"#
361        );
362        let back: ChannelActor =
363            serde_json::from_str(r#"{"kind":"human","name":"david"}"#).unwrap();
364        assert_eq!(back, a);
365        let keyed = ChannelActor::Human {
366            name: "david".into(),
367            key: Some("zKey".into()),
368        };
369        assert_eq!(
370            serde_json::to_string(&keyed).unwrap(),
371            r#"{"kind":"human","name":"david","key":"zKey"}"#
372        );
373    }
374
375    #[test]
376    fn owner_key_enrolled_wire_spelling_is_kebab() {
377        assert_eq!(
378            serde_json::to_string(&EventKind::OwnerKeyEnrolled).unwrap(),
379            r#""owner-key-enrolled""#
380        );
381        let p = OwnerKeyEnrolledPayload {
382            owner_key: "zKey".into(),
383            key_version: 1,
384            human_cut: Some(HumanCut {
385                seq: 4,
386                line_hash: "ab".into(),
387            }),
388        };
389        let v = serde_json::to_value(&p).unwrap();
390        assert_eq!(v["human_cut"]["seq"], 4);
391        assert_eq!(
392            serde_json::from_value::<OwnerKeyEnrolledPayload>(v).unwrap(),
393            p
394        );
395    }
396
397    #[test]
398    fn local_human_with_key_keeps_the_local_name() {
399        let ChannelActor::Human { name, .. } = ChannelActor::local_human() else {
400            panic!("local_human is Human");
401        };
402        assert_eq!(
403            ChannelActor::local_human_with_key("zKey"),
404            ChannelActor::Human {
405                name,
406                key: Some("zKey".into())
407            }
408        );
409    }
410
411    #[test]
412    fn channel_state_serializes_kebab() {
413        let j = serde_json::to_string(&ChannelState::InputRequired).unwrap();
414        assert_eq!(j, "\"input-required\"");
415    }
416
417    #[test]
418    fn event_round_trips() {
419        let ev = ChannelEvent {
420            seq: 3,
421            ts: Utc::now(),
422            actor: ChannelActor::Agent { id: "qa".into() },
423            kind: EventKind::Message,
424            payload: serde_json::json!({ "text": "hello", "task_id": "t-1" }),
425            idempotency_key: None,
426            sig: None,
427            key_version: None,
428            prev_hash: None,
429        };
430        let line = serde_json::to_string(&ev).unwrap();
431        let back: ChannelEvent = serde_json::from_str(&line).unwrap();
432        assert_eq!(back.seq, 3);
433        assert_eq!(back.actor, ChannelActor::Agent { id: "qa".into() });
434        assert_eq!(back.payload["text"], "hello");
435    }
436
437    #[test]
438    fn consult_kinds_round_trip_in_kebab_case() {
439        for (kind, wire) in [
440            (EventKind::Ask, "\"ask\""),
441            (EventKind::AskReply, "\"ask-reply\""),
442        ] {
443            assert_eq!(serde_json::to_string(&kind).unwrap(), wire);
444            assert_eq!(serde_json::from_str::<EventKind>(wire).unwrap(), kind);
445            assert!(kind.is_consult());
446        }
447        assert!(!EventKind::Message.is_consult());
448    }
449
450    #[test]
451    fn retract_round_trips_with_typed_payload() {
452        assert_eq!(
453            serde_json::to_string(&EventKind::Retract).unwrap(),
454            "\"retract\""
455        );
456        assert!(!EventKind::Retract.is_consult());
457        let p = RetractPayload {
458            target_seq: 41,
459            reason: RetractReason::Cancelled,
460        };
461        let v = serde_json::to_value(&p).unwrap();
462        assert_eq!(
463            v,
464            serde_json::json!({ "target_seq": 41, "reason": "cancelled" })
465        );
466        assert_eq!(serde_json::from_value::<RetractPayload>(v).unwrap(), p);
467        assert_eq!(retract_idempotency_key(41), "retract:41");
468    }
469
470    #[test]
471    fn ask_event_round_trips_with_typed_payload() {
472        let ask = AskPayload {
473            to: "tech-writer".into(),
474            question: "what does R7 cover?".into(),
475            expires_at_ms: 1_700_000_000_000,
476            nonce: "n1".into(),
477        };
478        let ev = ChannelEvent {
479            seq: 4,
480            ts: Utc::now(),
481            actor: ChannelActor::Agent { id: "pm".into() },
482            kind: EventKind::Ask,
483            payload: serde_json::to_value(&ask).unwrap(),
484            idempotency_key: Some(ask.nonce.clone()),
485            sig: None,
486            key_version: None,
487            prev_hash: None,
488        };
489        let back: ChannelEvent =
490            serde_json::from_str(&serde_json::to_string(&ev).unwrap()).unwrap();
491        assert_eq!(back.kind, EventKind::Ask);
492        let got: AskPayload = serde_json::from_value(back.payload).unwrap();
493        assert_eq!(got, ask);
494
495        let reply = AskReplyPayload {
496            nonce: "n1".into(),
497            text: "seq reuse".into(),
498        };
499        let v = serde_json::to_value(&reply).unwrap();
500        assert_eq!(serde_json::from_value::<AskReplyPayload>(v).unwrap(), reply);
501    }
502
503    #[test]
504    fn system_actor_round_trips() {
505        let a = ChannelActor::System;
506        let j = serde_json::to_string(&a).unwrap();
507        assert_eq!(j, "{\"kind\":\"system\"}");
508        let back: ChannelActor = serde_json::from_str(&j).unwrap();
509        assert_eq!(back, ChannelActor::System);
510    }
511
512    #[test]
513    fn event_omits_sig_fields_when_absent_and_reads_old_rows() {
514        // New events with sig=None must omit the field from JSON (no schema churn).
515        let ev = ChannelEvent {
516            seq: 0,
517            ts: Utc::now(),
518            actor: ChannelActor::System,
519            kind: EventKind::Note,
520            payload: serde_json::json!({}),
521            idempotency_key: None,
522            sig: None,
523            key_version: None,
524            prev_hash: None,
525        };
526        let line = serde_json::to_string(&ev).unwrap();
527        assert!(!line.contains("sig"), "sig must be omitted when None");
528        assert!(
529            !line.contains("key_version"),
530            "key_version must be omitted when None"
531        );
532
533        // Old rows without the fields must deserialize cleanly.
534        let old = r#"{"seq":0,"ts":"2026-06-16T00:00:00Z","actor":{"kind":"system"},"kind":"note","payload":{}}"#;
535        let back: ChannelEvent = serde_json::from_str(old).unwrap();
536        assert_eq!(back.sig, None);
537        assert_eq!(back.key_version, None);
538    }
539
540    #[test]
541    fn legacy_manifest_without_purpose_deserializes_as_none() {
542        // A manifest written before this field existed. Must still load.
543        let json = r#"{
544            "v": 2,
545            "id": "019ed0af-5e38-7912-b554-dc335a8fc2db",
546            "title": "chat with mur",
547            "state": "working",
548            "owner": {"kind": "human", "name": "david"},
549            "participants": [],
550            "created_at": "2026-08-01T10:00:00Z",
551            "updated_at": "2026-08-01T10:00:00Z"
552        }"#;
553        let ch: Channel = serde_json::from_str(json).expect("legacy manifest must deserialize");
554        assert_eq!(
555            ch.purpose, None,
556            "absent purpose must be None, not a default"
557        );
558    }
559
560    #[test]
561    fn purpose_round_trips_in_kebab_case() {
562        let json = r#"{
563            "v": 2,
564            "id": "x",
565            "title": "t",
566            "state": "working",
567            "owner": {"kind": "system"},
568            "participants": [],
569            "purpose": "fleet-run",
570            "created_at": "2026-08-01T10:00:00Z",
571            "updated_at": "2026-08-01T10:00:00Z"
572        }"#;
573        let ch: Channel = serde_json::from_str(json).unwrap();
574        assert_eq!(ch.purpose, Some(ChannelPurpose::FleetRun));
575
576        let back = serde_json::to_string(&ch).unwrap();
577        assert!(back.contains(r#""purpose":"fleet-run""#), "got: {back}");
578    }
579
580    #[test]
581    fn purpose_is_omitted_when_none() {
582        let json = r#"{
583            "v": 2, "id": "x", "title": "t", "state": "working",
584            "owner": {"kind": "system"}, "participants": [],
585            "created_at": "2026-08-01T10:00:00Z",
586            "updated_at": "2026-08-01T10:00:00Z"
587        }"#;
588        let ch: Channel = serde_json::from_str(json).unwrap();
589        let back = serde_json::to_string(&ch).unwrap();
590        assert!(
591            !back.contains("purpose"),
592            "a None purpose must not be written back as null: {back}"
593        );
594    }
595}