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).
32pub const CHANNEL_SCHEMA_VERSION: u32 = 2;
33
34/// A2A v0.3 lifecycle vocabulary, serialized on the wire as kebab-case
35/// (`input-required`, `canceled`, etc.).
36///
37/// ## Spelling note
38/// `Canceled` (→ `"canceled"`) intentionally follows the A2A v0.3 spec spelling
39/// and is a DISTINCT type from [`crate::a2a::TaskState`], which spells the
40/// equivalent variant `Cancelled` (two l's). The two enums are bridged by an
41/// explicit boundary mapping — not string equality — so the spelling difference
42/// is deliberate, not a bug.
43#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
44#[serde(rename_all = "kebab-case")]
45pub enum ChannelState {
46    Submitted,
47    Working,
48    InputRequired,
49    Completed,
50    Failed,
51    Canceled,
52    Rejected,
53    /// MUR extension (not in A2A v0.3): the channel has had no activity for an
54    /// extended period and was system-marked stale.
55    Stale,
56}
57
58/// Why a channel exists. Deliberately smaller than the ways a UI may render a
59/// channel: Direct vs Group is derived from participants, and Companion/HITL
60/// are event-derived states — none of them are purposes.
61///
62/// `Option<ChannelPurpose>` on `Channel`: `None` means "written before this
63/// field existed" and MUST NOT be treated as an explicit `Conversation`.
64/// Resolve it for display with `mur_channel::purpose::effective_purpose`;
65/// correct it on disk only with `mur channel backfill-purpose`.
66#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
67#[serde(rename_all = "kebab-case")]
68pub enum ChannelPurpose {
69    Conversation,
70    FleetRun,
71    WorkflowRun,
72}
73
74/// Who produced an event / is a participant. Named `ChannelActor` to avoid
75/// colliding with the pre-existing `mur_common::actor::Actor`.
76#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
77#[serde(tag = "kind", rename_all = "kebab-case")]
78pub enum ChannelActor {
79    Human { name: String },
80    Agent { id: String },
81    System,
82}
83
84impl ChannelActor {
85    /// The local human owner, from `$USER`/`$USERNAME`, falling back to `you`.
86    pub fn local_human() -> Self {
87        let name = std::env::var("USER")
88            .or_else(|_| std::env::var("USERNAME"))
89            .ok()
90            .filter(|s| !s.is_empty())
91            .unwrap_or_else(|| "you".to_string());
92        ChannelActor::Human { name }
93    }
94}
95
96/// The role a participant plays within a channel's lifecycle.
97#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
98#[serde(rename_all = "lowercase")]
99pub enum ParticipantRole {
100    Owner,
101    Router,
102    Delegate,
103    Observer,
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct Participant {
108    pub actor: ChannelActor,
109    pub role: ParticipantRole,
110    pub joined_at: DateTime<Utc>,
111}
112
113/// The intent a channel is working toward, with optional acceptance criteria.
114#[derive(Debug, Clone, Default, Serialize, Deserialize)]
115pub struct Goal {
116    #[serde(default)]
117    pub statement: String,
118    #[serde(default)]
119    pub acceptance_criteria: Vec<String>,
120}
121
122/// The durable manifest (a cache of state derivable from the event log).
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct Channel {
125    pub v: u32,
126    pub id: String,
127    pub title: String,
128    #[serde(default)]
129    pub goal: Goal,
130    pub state: ChannelState,
131    /// Why this channel exists. `None` = legacy manifest; see `ChannelPurpose`.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub purpose: Option<ChannelPurpose>,
134    pub owner: ChannelActor,
135    #[serde(default)]
136    pub participants: Vec<Participant>,
137    pub created_at: DateTime<Utc>,
138    pub updated_at: DateTime<Utc>,
139}
140
141#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
142#[serde(rename_all = "kebab-case")]
143pub enum EventKind {
144    Message,
145    Delegation,
146    Handoff,
147    ToolCall,
148    ToolResult,
149    StateChange,
150    Artifact,
151    HitlRequest,
152    HitlResponse,
153    Note,
154    /// One agent asks another a question (channel consult). Signed by the
155    /// asker; the payload is an [`AskPayload`] and `idempotency_key` equals
156    /// its `nonce`. Not agent progress: readers that count agent output skip it.
157    Ask,
158    /// The answerer's reply to an [`EventKind::Ask`]; the payload is an
159    /// [`AskReplyPayload`]. Not agent progress, a fleet reply, or a final answer.
160    AskReply,
161}
162
163impl EventKind {
164    /// True for the consult kinds, which an agent writes beside its work
165    /// rather than as part of it. Readers that treat any agent-authored event
166    /// as progress, a reply, or a final answer must exclude these.
167    pub fn is_consult(self) -> bool {
168        matches!(self, EventKind::Ask | EventKind::AskReply)
169    }
170}
171
172/// Payload of an [`EventKind::Ask`] event. Every field is inside the signed
173/// input, so the answerer, the deadline and the nonce cannot be rewritten
174/// without breaking the asker's signature.
175#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
176pub struct AskPayload {
177    /// The answering agent's name. Only that agent may answer.
178    pub to: String,
179    /// The question text the answerer sees.
180    pub question: String,
181    /// Unix-epoch milliseconds after which the answerer refuses the `Ask`.
182    pub expires_at_ms: i64,
183    /// Single-use id; the event's `idempotency_key` carries the same value.
184    pub nonce: String,
185}
186
187/// Payload of an [`EventKind::AskReply`] event.
188#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
189pub struct AskReplyPayload {
190    /// The `nonce` of the [`AskPayload`] this answers.
191    pub nonce: String,
192    /// The answer text.
193    pub text: String,
194}
195
196/// One append-only line in `~/.mur/channels/<id>/events.jsonl`.
197#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct ChannelEvent {
199    pub seq: u64,
200    pub ts: DateTime<Utc>,
201    pub actor: ChannelActor,
202    pub kind: EventKind,
203    #[serde(default)]
204    pub payload: serde_json::Value,
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub idempotency_key: Option<String>,
207    /// Detached Ed25519 signature (multibase) by the channel's WRITER over the
208    /// canonical sign-input `{v, channel_id, actor, kind, payload,
209    /// idempotency_key}` — EXCLUDING the store-assigned `seq`/`ts` (see
210    /// `mur-channel` `sign::sign_input`). `None` for legacy/unsigned events.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub sig: Option<String>,
213    /// RESERVED — key version for the signing key (v3d).
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub key_version: Option<u32>,
216    /// Hex SHA-256 of the previous raw line in `events.jsonl` (or the genesis
217    /// constant for the first line). Set only on sig-input v2 events, which
218    /// sign over it; `None` for v1 (externally signed) and unsigned events.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub prev_hash: Option<String>,
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn channel_state_serializes_kebab() {
229        let j = serde_json::to_string(&ChannelState::InputRequired).unwrap();
230        assert_eq!(j, "\"input-required\"");
231    }
232
233    #[test]
234    fn event_round_trips() {
235        let ev = ChannelEvent {
236            seq: 3,
237            ts: Utc::now(),
238            actor: ChannelActor::Agent { id: "qa".into() },
239            kind: EventKind::Message,
240            payload: serde_json::json!({ "text": "hello", "task_id": "t-1" }),
241            idempotency_key: None,
242            sig: None,
243            key_version: None,
244            prev_hash: None,
245        };
246        let line = serde_json::to_string(&ev).unwrap();
247        let back: ChannelEvent = serde_json::from_str(&line).unwrap();
248        assert_eq!(back.seq, 3);
249        assert_eq!(back.actor, ChannelActor::Agent { id: "qa".into() });
250        assert_eq!(back.payload["text"], "hello");
251    }
252
253    #[test]
254    fn consult_kinds_round_trip_in_kebab_case() {
255        for (kind, wire) in [
256            (EventKind::Ask, "\"ask\""),
257            (EventKind::AskReply, "\"ask-reply\""),
258        ] {
259            assert_eq!(serde_json::to_string(&kind).unwrap(), wire);
260            assert_eq!(serde_json::from_str::<EventKind>(wire).unwrap(), kind);
261            assert!(kind.is_consult());
262        }
263        assert!(!EventKind::Message.is_consult());
264    }
265
266    #[test]
267    fn ask_event_round_trips_with_typed_payload() {
268        let ask = AskPayload {
269            to: "tech-writer".into(),
270            question: "what does R7 cover?".into(),
271            expires_at_ms: 1_700_000_000_000,
272            nonce: "n1".into(),
273        };
274        let ev = ChannelEvent {
275            seq: 4,
276            ts: Utc::now(),
277            actor: ChannelActor::Agent { id: "pm".into() },
278            kind: EventKind::Ask,
279            payload: serde_json::to_value(&ask).unwrap(),
280            idempotency_key: Some(ask.nonce.clone()),
281            sig: None,
282            key_version: None,
283            prev_hash: None,
284        };
285        let back: ChannelEvent =
286            serde_json::from_str(&serde_json::to_string(&ev).unwrap()).unwrap();
287        assert_eq!(back.kind, EventKind::Ask);
288        let got: AskPayload = serde_json::from_value(back.payload).unwrap();
289        assert_eq!(got, ask);
290
291        let reply = AskReplyPayload {
292            nonce: "n1".into(),
293            text: "seq reuse".into(),
294        };
295        let v = serde_json::to_value(&reply).unwrap();
296        assert_eq!(serde_json::from_value::<AskReplyPayload>(v).unwrap(), reply);
297    }
298
299    #[test]
300    fn system_actor_round_trips() {
301        let a = ChannelActor::System;
302        let j = serde_json::to_string(&a).unwrap();
303        assert_eq!(j, "{\"kind\":\"system\"}");
304        let back: ChannelActor = serde_json::from_str(&j).unwrap();
305        assert_eq!(back, ChannelActor::System);
306    }
307
308    #[test]
309    fn event_omits_sig_fields_when_absent_and_reads_old_rows() {
310        // New events with sig=None must omit the field from JSON (no schema churn).
311        let ev = ChannelEvent {
312            seq: 0,
313            ts: Utc::now(),
314            actor: ChannelActor::System,
315            kind: EventKind::Note,
316            payload: serde_json::json!({}),
317            idempotency_key: None,
318            sig: None,
319            key_version: None,
320            prev_hash: None,
321        };
322        let line = serde_json::to_string(&ev).unwrap();
323        assert!(!line.contains("sig"), "sig must be omitted when None");
324        assert!(
325            !line.contains("key_version"),
326            "key_version must be omitted when None"
327        );
328
329        // Old rows without the fields must deserialize cleanly.
330        let old = r#"{"seq":0,"ts":"2026-06-16T00:00:00Z","actor":{"kind":"system"},"kind":"note","payload":{}}"#;
331        let back: ChannelEvent = serde_json::from_str(old).unwrap();
332        assert_eq!(back.sig, None);
333        assert_eq!(back.key_version, None);
334    }
335
336    #[test]
337    fn legacy_manifest_without_purpose_deserializes_as_none() {
338        // A manifest written before this field existed. Must still load.
339        let json = r#"{
340            "v": 2,
341            "id": "019ed0af-5e38-7912-b554-dc335a8fc2db",
342            "title": "chat with mur",
343            "state": "working",
344            "owner": {"kind": "human", "name": "david"},
345            "participants": [],
346            "created_at": "2026-08-01T10:00:00Z",
347            "updated_at": "2026-08-01T10:00:00Z"
348        }"#;
349        let ch: Channel = serde_json::from_str(json).expect("legacy manifest must deserialize");
350        assert_eq!(
351            ch.purpose, None,
352            "absent purpose must be None, not a default"
353        );
354    }
355
356    #[test]
357    fn purpose_round_trips_in_kebab_case() {
358        let json = r#"{
359            "v": 2,
360            "id": "x",
361            "title": "t",
362            "state": "working",
363            "owner": {"kind": "system"},
364            "participants": [],
365            "purpose": "fleet-run",
366            "created_at": "2026-08-01T10:00:00Z",
367            "updated_at": "2026-08-01T10:00:00Z"
368        }"#;
369        let ch: Channel = serde_json::from_str(json).unwrap();
370        assert_eq!(ch.purpose, Some(ChannelPurpose::FleetRun));
371
372        let back = serde_json::to_string(&ch).unwrap();
373        assert!(back.contains(r#""purpose":"fleet-run""#), "got: {back}");
374    }
375
376    #[test]
377    fn purpose_is_omitted_when_none() {
378        let json = r#"{
379            "v": 2, "id": "x", "title": "t", "state": "working",
380            "owner": {"kind": "system"}, "participants": [],
381            "created_at": "2026-08-01T10:00:00Z",
382            "updated_at": "2026-08-01T10:00:00Z"
383        }"#;
384        let ch: Channel = serde_json::from_str(json).unwrap();
385        let back = serde_json::to_string(&ch).unwrap();
386        assert!(
387            !back.contains("purpose"),
388            "a None purpose must not be written back as null: {back}"
389        );
390    }
391}