Skip to main content

mur_common/
signal.rs

1//! Signal wire format for cross-process memory sync events.
2//!
3//! Flows:
4//! - commander writes → `~/.mur/commander/outbox/*.yaml` → POST /v1/signals/batch → mur-server
5//! - mur CLI `mur fetch` ← GET /v1/signals/pending ← mur-server → `~/.mur/inbox/*.yaml`
6//!
7//! Schema version is bumped on breaking wire changes. Additive changes (new fields)
8//! are serde-default and backward compatible within the same major version.
9
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13
14use crate::skill::manifest::SkillManifest;
15use crate::{Actor, Scope};
16
17// ─── FROZEN SCHEMA — v1 ──────────────────────────────────────────────────
18// This module is the canonical wire format between commander and mur.
19// SCHEMA FREEZE DATE: 2026-05-18
20// Spec: docs/superpowers/specs/2026-05-18-commander-feedback-wire-protocol-design.md
21//
22// Changes to Signal, SignalKind, SignalTarget, Actor, ActorSource, or
23// SIGNAL_SCHEMA_VERSION require:
24//   1. Bumping SIGNAL_SCHEMA_VERSION to 2
25//   2. Coordinated update in the commander repo (closed-source)
26//   3. Adding a v2 HTTP endpoint at /v2/signals/...
27//   4. Migration plan in a new design spec
28//
29// Additive changes (new fields with #[serde(default)]) are allowed within v1.
30// ─────────────────────────────────────────────────────────────────────────
31
32/// Current schema version of the Signal wire format. FROZEN at v1 — see
33/// module-level comment for change rules.
34pub const SIGNAL_SCHEMA_VERSION: u32 = 1;
35
36/// A single event envelope: who produced what kind of event about which target,
37/// with provenance. Carried verbatim through outbox → server → inbox.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct Signal {
40    pub id: Uuid,
41    pub emitted_at: DateTime<Utc>,
42    pub actor: Actor,
43    pub target: SignalTarget,
44    pub kind: SignalKind,
45    pub scope: Scope,
46    /// Confidence weight in [0.0, 1.0] applied server-side during aggregation.
47    /// Default 1.0 (full weight).
48    #[serde(default = "default_confidence")]
49    pub confidence: f64,
50    /// Wire-format version of this signal. Server-side rejects signals with
51    /// unsupported major versions; additive fields with `#[serde(default)]`
52    /// keep signals within the same major forward-compatible.
53    #[serde(default = "current_schema_version")]
54    pub schema_version: u32,
55    /// Multibase (Base58Btc) Ed25519 signature over [`sign_input`] — federation
56    /// P2c-2, following the v3d `ChannelEvent` precedent. `None` = legacy
57    /// unsigned signal (tolerated on ingest unless `MUR_SIGNAL_REQUIRE_SIG`).
58    /// Additive `#[serde(default)]` field — allowed within frozen schema v1.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub sig: Option<String>,
61    /// Key-rotation version; 0 = initial identity key.
62    #[serde(default, skip_serializing_if = "is_zero")]
63    pub key_version: u32,
64}
65
66fn default_confidence() -> f64 {
67    1.0
68}
69fn current_schema_version() -> u32 {
70    SIGNAL_SCHEMA_VERSION
71}
72pub(crate) fn is_zero(v: &u32) -> bool {
73    *v == 0
74}
75
76/// Canonicalization version — bump if the sign-input shape changes so an old
77/// signature is never silently checked against a new canonicalization.
78pub const SIGNAL_SIG_INPUT_VERSION: u32 = 1;
79
80/// Canonical signed bytes for a [`Signal`]: every semantic field, `sig`
81/// excluded. Keys are sorted by [`crate::canonical::canonical_json`], so this
82/// is deterministic whatever `serde_json` features the build unifies. The `domain` tag prevents a signature
83/// minted here from verifying in any other MUR signing context.
84fn sign_input(s: &Signal) -> Vec<u8> {
85    let canon = serde_json::json!({
86        "domain": "mur-signal",
87        "v": SIGNAL_SIG_INPUT_VERSION,
88        "id": s.id,
89        "emitted_at": s.emitted_at,
90        "actor": s.actor,
91        "target": s.target,
92        "kind": s.kind,
93        "scope": s.scope,
94        "confidence": s.confidence,
95        "schema_version": s.schema_version,
96        "key_version": s.key_version,
97    });
98    crate::canonical::canonical_json(&canon)
99}
100
101/// Parse `MUR_SIGNAL_REQUIRE_SIG`: only explicit truthy values enable
102/// signature enforcement (`=0` / `=false`, or unset, must NOT turn it on) —
103/// default-off is migration safety AND the commander wire (frozen v1, signals
104/// arrive bearer-token-authed but unsigned). One parser for every reader,
105/// mirroring `MUR_CHANNEL_REQUIRE_SIG`.
106pub fn require_sig_from_env() -> bool {
107    std::env::var("MUR_SIGNAL_REQUIRE_SIG")
108        .map(|v| matches!(v.as_str(), "1" | "true" | "TRUE" | "yes"))
109        .unwrap_or(false)
110}
111
112impl Signal {
113    /// Sign this signal in place with the emitting agent's identity key.
114    /// The signature covers every field except `sig` itself.
115    pub fn sign(&mut self, identity: &crate::identity::AgentIdentity) {
116        self.sig = Some(identity.sign_multibase(&sign_input(self)));
117    }
118
119    /// Fail-closed signature check against `pubkey`. An unsigned signal
120    /// never verifies — callers decide whether unsigned is tolerated.
121    pub fn verify(&self, pubkey: &[u8; 32]) -> bool {
122        match &self.sig {
123            Some(sig) => crate::identity::verify_bytes(pubkey, &sign_input(self), sig),
124            None => false,
125        }
126    }
127}
128
129/// HTTP batch wrapper for `POST /v1/signals/batch`.
130///
131/// Carries 1–N signals in a single request. `batch_id` enables at-most-once
132/// retry semantics: the server deduplicates on `batch_id` (HTTP layer) and on
133/// individual `Signal.id` (inbox layer).
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct SignalBatch {
136    pub batch_id: Uuid,
137    /// Must equal `SIGNAL_SCHEMA_VERSION` (1). Server rejects mismatches.
138    #[serde(default = "current_schema_version")]
139    pub schema_version: u32,
140    pub signals: Vec<Signal>,
141}
142
143/// Response body for `POST /v1/signals/batch`.
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct SignalBatchResponse {
146    pub accepted: usize,
147    pub deduplicated: usize,
148}
149
150/// What the signal refers to.
151#[derive(Debug, Clone, Serialize, Deserialize)]
152#[serde(tag = "kind", rename_all = "snake_case")]
153pub enum SignalTarget {
154    /// Refers to a legacy pattern by name within a scope. The local Pattern
155    /// store was retired (Tier C3); receivers skip this target. The variant
156    /// stays so frozen-v1 signals from older peers still parse.
157    Pattern { name: String, scope: Scope },
158    /// Legacy draft-pattern proposal (Channel 2/3). The payload used to be a
159    /// typed `Pattern`; it is now carried opaquely so the wire shape is
160    /// byte-for-byte unchanged while nothing on this side can consume it.
161    /// Boxed to keep the enum variant sizes comparable.
162    NewDraftPattern { payload: Box<serde_json::Value> },
163    /// Refers to an installed skill by name.
164    Skill { name: String, scope: Scope },
165    /// Carries a fully-formed SkillManifest as a draft proposal.
166    NewDraftSkill { payload: Box<SkillManifest> },
167}
168
169/// What happened to the target.
170#[derive(Debug, Clone, Serialize, Deserialize)]
171#[serde(tag = "type", rename_all = "snake_case")]
172pub enum SignalKind {
173    /// Workflow/step using this pattern completed successfully. (Channel 1)
174    ExecutionSuccess,
175    /// Workflow/step using this pattern failed. (Channel 1)
176    ExecutionFailure { error: String },
177    /// User rejected a breakpoint while this pattern was active. (Channel 1, 3x weight)
178    UserOverrideAtBreakpoint { reason: Option<String> },
179    /// AutoFix ran on a step that used this pattern. (Channel 1, signals pattern inadequacy)
180    AutoFixApplied { step: String },
181    /// Proposal to add a new pattern. (Channel 2 — chat extraction, Channel 3 — procedural)
182    NewPatternProposal { origin_context: String },
183    /// Skill execution succeeded. (Channel 1)
184    SkillExecutionSuccess,
185    /// Skill execution failed. (Channel 1)
186    SkillExecutionFailure { error: String },
187    /// Proposal to add a new skill. (Channel 2 / Channel 3)
188    NewDraftSkill {
189        payload: Box<SkillManifest>,
190        origin_context: String,
191    },
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197    use crate::ActorSource;
198
199    fn sample_actor() -> Actor {
200        Actor {
201            source: ActorSource::CommanderDaemon,
202            native_id: "svc-1".into(),
203            display_name: None,
204            resolved_user_id: None,
205        }
206    }
207
208    fn sample_signal() -> Signal {
209        Signal {
210            id: Uuid::new_v4(),
211            emitted_at: Utc::now(),
212            actor: sample_actor(),
213            target: SignalTarget::Pattern {
214                name: "rust-err-handling".into(),
215                scope: Scope::Personal,
216            },
217            kind: SignalKind::ExecutionSuccess,
218            scope: Scope::Personal,
219            confidence: 0.9,
220            schema_version: SIGNAL_SCHEMA_VERSION,
221            sig: None,
222            key_version: 0,
223        }
224    }
225
226    #[test]
227    fn signal_roundtrip_execution_success() {
228        let s = sample_signal();
229        let y = serde_yaml::to_string(&s).unwrap();
230        let back: Signal = serde_yaml::from_str(&y).unwrap();
231        assert_eq!(back.id, s.id);
232        assert!(matches!(back.kind, SignalKind::ExecutionSuccess));
233        assert!((back.confidence - 0.9).abs() < 1e-9);
234    }
235
236    #[test]
237    fn signal_confidence_defaults_to_one() {
238        let y = r#"
239id: 00000000-0000-0000-0000-000000000001
240emitted_at: 2026-04-18T10:00:00Z
241actor: { source: commander_daemon, native_id: x }
242target: { kind: pattern, name: foo, scope: { kind: personal } }
243kind: { type: execution_success }
244scope: { kind: personal }
245"#;
246        let s: Signal = serde_yaml::from_str(y).unwrap();
247        assert!((s.confidence - 1.0).abs() < 1e-9);
248        assert_eq!(s.schema_version, 1);
249    }
250
251    #[test]
252    fn signal_kind_execution_failure_carries_error() {
253        let s = Signal {
254            kind: SignalKind::ExecutionFailure {
255                error: "db timeout".into(),
256            },
257            ..sample_signal()
258        };
259        let y = serde_yaml::to_string(&s).unwrap();
260        let back: Signal = serde_yaml::from_str(&y).unwrap();
261        match back.kind {
262            SignalKind::ExecutionFailure { error } => assert_eq!(error, "db timeout"),
263            _ => panic!("wrong variant"),
264        }
265    }
266
267    #[test]
268    fn signal_kind_override_with_reason() {
269        let y = r#"
270id: 00000000-0000-0000-0000-000000000002
271emitted_at: 2026-04-18T10:00:00Z
272actor: { source: slack, native_id: U999 }
273target: { kind: pattern, name: x, scope: { kind: personal } }
274kind: { type: user_override_at_breakpoint, reason: "wrong step" }
275scope: { kind: personal }
276"#;
277        let s: Signal = serde_yaml::from_str(y).unwrap();
278        match s.kind {
279            SignalKind::UserOverrideAtBreakpoint { reason } => {
280                assert_eq!(reason.as_deref(), Some("wrong step"));
281            }
282            _ => panic!("wrong variant"),
283        }
284    }
285
286    #[test]
287    fn signal_kind_override_without_reason() {
288        let y = r#"
289id: 00000000-0000-0000-0000-000000000003
290emitted_at: 2026-04-18T10:00:00Z
291actor: { source: slack, native_id: U999 }
292target: { kind: pattern, name: x, scope: { kind: personal } }
293kind: { type: user_override_at_breakpoint }
294scope: { kind: personal }
295"#;
296        let s: Signal = serde_yaml::from_str(y).unwrap();
297        assert!(matches!(
298            s.kind,
299            SignalKind::UserOverrideAtBreakpoint { reason: None }
300        ));
301    }
302
303    #[test]
304    fn signal_kind_autofix() {
305        let s = Signal {
306            kind: SignalKind::AutoFixApplied {
307                step: "run-tests".into(),
308            },
309            ..sample_signal()
310        };
311        let y = serde_yaml::to_string(&s).unwrap();
312        let back: Signal = serde_yaml::from_str(&y).unwrap();
313        match back.kind {
314            SignalKind::AutoFixApplied { step } => assert_eq!(step, "run-tests"),
315            _ => panic!("wrong variant"),
316        }
317    }
318
319    #[test]
320    fn signal_kind_new_pattern_proposal() {
321        let s = Signal {
322            kind: SignalKind::NewPatternProposal {
323                origin_context: "slack DM from alice: use pnpm".into(),
324            },
325            ..sample_signal()
326        };
327        let y = serde_yaml::to_string(&s).unwrap();
328        let back: Signal = serde_yaml::from_str(&y).unwrap();
329        match back.kind {
330            SignalKind::NewPatternProposal { origin_context } => {
331                assert!(origin_context.contains("alice"));
332            }
333            _ => panic!("wrong variant"),
334        }
335    }
336
337    #[test]
338    fn signal_target_pattern_roundtrip() {
339        let p = SignalTarget::Pattern {
340            name: "foo".into(),
341            scope: Scope::Team {
342                team_id: "ops".into(),
343            },
344        };
345        let y = serde_yaml::to_string(&p).unwrap();
346        assert!(y.contains("kind: pattern"));
347        let back: SignalTarget = serde_yaml::from_str(&y).unwrap();
348        assert!(matches!(back, SignalTarget::Pattern { .. }));
349    }
350
351    #[test]
352    fn signal_with_new_draft_pattern_roundtrip() {
353        // The Pattern type is gone, but frozen-v1 peers still emit
354        // `new_draft_pattern` with a full pattern body. It must parse and
355        // re-serialize with the payload intact (opaque), so the wire is
356        // byte-for-byte unchanged.
357        let payload = serde_json::json!({
358            "schema": 2,
359            "name": "draft-pat",
360            "description": "chat-extracted draft",
361            "content": "use pnpm not npm",
362            "tier": "session"
363        });
364
365        let sig = Signal {
366            id: Uuid::new_v4(),
367            emitted_at: Utc::now(),
368            actor: sample_actor(),
369            target: SignalTarget::NewDraftPattern {
370                payload: Box::new(payload.clone()),
371            },
372            kind: SignalKind::NewPatternProposal {
373                origin_context: "slack DM".into(),
374            },
375            scope: Scope::Personal,
376            confidence: 0.75,
377            schema_version: SIGNAL_SCHEMA_VERSION,
378            sig: None,
379            key_version: 0,
380        };
381        let y = serde_yaml::to_string(&sig).unwrap();
382        assert!(y.contains("kind: new_draft_pattern"));
383        assert!(y.contains("name: draft-pat"));
384        let back: Signal = serde_yaml::from_str(&y).unwrap();
385        match back.target {
386            SignalTarget::NewDraftPattern {
387                payload: back_payload,
388            } => {
389                assert_eq!(*back_payload, payload);
390            }
391            _ => panic!("expected NewDraftPattern variant"),
392        }
393    }
394
395    #[test]
396    fn schema_version_constant() {
397        assert_eq!(SIGNAL_SCHEMA_VERSION, 1);
398    }
399
400    #[test]
401    fn sign_verify_roundtrip_and_yaml_preserves_sig() {
402        let id = crate::identity::AgentIdentity::generate();
403        let mut s = sample_signal();
404        s.sign(&id);
405        assert!(s.verify(&id.verifying_key_bytes()));
406
407        let yaml = serde_yaml::to_string(&s).unwrap();
408        let back: Signal = serde_yaml::from_str(&yaml).unwrap();
409        assert!(back.verify(&id.verifying_key_bytes()));
410    }
411
412    #[test]
413    fn tampered_field_fails_verification() {
414        let id = crate::identity::AgentIdentity::generate();
415        let mut s = sample_signal();
416        s.sign(&id);
417        s.scope = Scope::Team {
418            team_id: "ops".into(),
419        }; // scope-escalation attempt after signing
420        assert!(!s.verify(&id.verifying_key_bytes()));
421    }
422
423    #[test]
424    fn wrong_key_and_unsigned_fail_verification() {
425        let id = crate::identity::AgentIdentity::generate();
426        let other = crate::identity::AgentIdentity::generate();
427        let mut s = sample_signal();
428        assert!(
429            !s.verify(&id.verifying_key_bytes()),
430            "unsigned never verifies"
431        );
432        s.sign(&id);
433        assert!(!s.verify(&other.verifying_key_bytes()));
434    }
435
436    #[test]
437    fn legacy_unsigned_yaml_deserializes_with_defaults() {
438        // Pre-P2c-2 signal yaml — no sig/key_version fields.
439        let y = r#"
440id: 00000000-0000-0000-0000-000000000009
441emitted_at: 2026-04-18T10:00:00Z
442actor: { source: commander_daemon, native_id: x }
443target: { kind: pattern, name: foo, scope: { kind: personal } }
444kind: { type: execution_success }
445scope: { kind: personal }
446"#;
447        let s: Signal = serde_yaml::from_str(y).unwrap();
448        assert!(s.sig.is_none());
449        assert_eq!(s.key_version, 0);
450        // And an unsigned signal serializes WITHOUT the new keys (wire-stable).
451        let out = serde_yaml::to_string(&s).unwrap();
452        assert!(!out.contains("sig:"));
453        assert!(!out.contains("key_version:"));
454    }
455
456    #[test]
457    fn signal_target_skill_roundtrips() {
458        let t = SignalTarget::Skill {
459            name: "my-skill".into(),
460            scope: Scope::Personal,
461        };
462        let s = serde_json::to_string(&t).unwrap();
463        assert!(s.contains("\"kind\":\"skill\""), "got: {s}");
464        let back: SignalTarget = serde_json::from_str(&s).unwrap();
465        assert!(matches!(back, SignalTarget::Skill { .. }));
466    }
467
468    #[test]
469    fn signal_kind_new_draft_skill_roundtrips() {
470        let k = SignalKind::NewDraftSkill {
471            payload: Box::new(
472                serde_json::from_str::<SkillManifest>(
473                    r#"{"name":"x","version":"1","publisher":"human:t","description":"d","category":"context","content":{"abstract":"a"}}"#,
474                )
475                .unwrap(),
476            ),
477            origin_context: "test".into(),
478        };
479        let s = serde_json::to_string(&k).unwrap();
480        let back: SignalKind = serde_json::from_str(&s).unwrap();
481        assert!(matches!(back, SignalKind::NewDraftSkill { .. }));
482    }
483}