mur-common 2.20.7

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
//! Install a validated `.muragent` archive onto the local host.
//!
//! Single source of truth for the `.muragent` install flow, shared by every
//! surface (CLI, Hub, Commander). The flow is:
//!
//! 1. Run the full 11-step validation pipeline (`validator::validate`).
//! 2. Validate the agent slug shape — prevents `agents/../../etc`.
//! 3. Check the trust store: a key change without a rotation manifest is a
//!    hard refuse (§7.1.1).
//! 4. Detect collision vs update by matching `agent.original_uuid` against
//!    any existing agent at the same slug. Same UUID → update (preserves
//!    `data/`); different UUID → error.
//! 5. Extract the payload to `<mur_home>/agents/<slug>/`.
//! 6. Upsert the trust store entry, marking surface and timestamps.
//!
//! UI/print decisions belong to the caller; this module returns a structured
//! `InstallOutcome` describing what happened.

use std::fs;
use std::path::{Path, PathBuf};

use base64::{Engine, engine::general_purpose::STANDARD as B64};

use crate::AgentProfile;
use crate::muragent::MuragentError;
use crate::muragent::manifest::MuragentManifest;
use crate::muragent::reader::MuragentArchive;
use crate::muragent::validator::{self, ValidationResult};
use crate::trust::rotation::RotationManifest;
use crate::trust::{self, TrustEntry, TrustLevel, TrustStore};

/// Files in the .muragent that belong to the package envelope (not payload).
const ENVELOPE_FILES: &[&str] = &["manifest.yaml", "manifest.signed.json", "signatures.json"];

/// Result of a successful install or update.
#[derive(Debug)]
pub struct InstallOutcome {
    pub manifest: MuragentManifest,
    pub trust_level: TrustLevel,
    pub fingerprint_hex: String,
    pub fingerprint_words: String,
    /// `false` when extracting into a freshly-created agent dir; `true` when
    /// the agent already existed at the slug with matching UUID and the
    /// payload was replaced in place (preserving `data/`).
    pub was_update: bool,
}

/// Install or update a `.muragent` archive. See module docs for the flow.
///
/// `mur_home` is the root for agent dirs (`<mur_home>/agents/<slug>/`). The
/// trust store is read and written via [`TrustStore::load`] / `save`, which
/// honour `$MUR_HOME` independently — callers should either pass the same
/// path the trust store would resolve, or set `MUR_HOME` consistently.
///
/// `surface` is recorded in the trust entry's `last_seen_surface` field.
/// Conventional values: `"cli"`, `"hub"`, `"commander"`.
pub fn install(
    archive: &MuragentArchive,
    mur_home: &Path,
    surface: &str,
) -> Result<InstallOutcome, MuragentError> {
    // Step 1: validation pipeline — fatal on any failure per §7.5
    let result = validator::validate(archive)?;

    // Step 2: slug shape
    let slug = result.manifest.agent.slug.clone();
    let display_name = result.manifest.agent.display_name.clone();
    crate::validate_agent_name(&slug).map_err(|e| {
        MuragentError::Other(format!("invalid agent slug '{slug}' in manifest: {e}"))
    })?;

    // Step 3: trust store key-change check
    let mut trust_store = TrustStore::load()?;
    let author_pubkey_b64 = B64.encode(result.author_pubkey);
    let existing_by_pubkey = trust_store.find_by_pubkey(&author_pubkey_b64).cloned();

    if existing_by_pubkey.is_none() {
        let by_name = trust_store.find_by_display_name(&display_name);
        if !by_name.is_empty() {
            // Key change detected — look for a rotation manifest before refusing.
            let old_entry = by_name
                .into_iter()
                .find(|e| e.trust_level != TrustLevel::Superseded)
                .cloned();
            match try_apply_rotation(
                &mut trust_store,
                old_entry.as_ref(),
                &author_pubkey_b64,
                &display_name,
                mur_home,
            ) {
                Ok(()) => {} // rotation accepted; trust store updated in-place
                Err(reason) => {
                    return Err(MuragentError::TrustRefused(format!(
                        "agent '{}' has a new signing key but no valid rotation manifest: {}",
                        display_name, reason
                    )));
                }
            }
        }
    }

    // Step 4-5: detect update vs collision; extract payload
    let agent_dir = mur_home.join("agents").join(&slug);
    let was_update = if agent_dir.exists() {
        let existing_profile = agent_dir.join("profile.yaml");
        let mut is_same_agent = false;
        if existing_profile.exists() {
            let existing_yaml = fs::read_to_string(&existing_profile).map_err(MuragentError::Io)?;
            if let Ok(existing) = serde_yaml_ng::from_str::<AgentProfile>(&existing_yaml)
                && existing.id == result.manifest.agent.original_uuid
            {
                is_same_agent = true;
            }
        }
        if !is_same_agent {
            return Err(MuragentError::Other(format!(
                "agent '{slug}' already exists at {} with a different UUID",
                agent_dir.display()
            )));
        }
        // Same UUID — clear everything except data/, then extract
        clear_except_data(&agent_dir)?;
        true
    } else {
        fs::create_dir_all(&agent_dir).map_err(MuragentError::Io)?;
        false
    };

    extract_payload(archive, &agent_dir)?;

    // Step 6: trust upsert
    let fingerprint_hex = trust::short_fingerprint(&result.author_pubkey);
    let fingerprint_words = trust::word_list_fingerprint(&result.author_pubkey);
    let (trust_level, _) = upsert_trust(
        &mut trust_store,
        &result,
        &author_pubkey_b64,
        &existing_by_pubkey,
        surface,
    )?;
    trust_store.save()?;

    Ok(InstallOutcome {
        manifest: result.manifest,
        trust_level,
        fingerprint_hex,
        fingerprint_words,
        was_update,
    })
}

/// Convert a display name to a filesystem-safe slug for rotation manifest lookup.
fn display_name_slug(name: &str) -> String {
    name.to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

fn rotation_manifest_path(mur_home: &Path, display_name: &str) -> PathBuf {
    mur_home
        .join("trust")
        .join("rotations")
        .join(format!("{}.yaml", display_name_slug(display_name)))
}

/// Try to load and apply a key rotation manifest. Returns Ok(()) if the
/// rotation is valid and the trust store has been updated in-place. Returns
/// Err(reason) if the manifest is missing, invalid, or replayed.
fn try_apply_rotation(
    trust_store: &mut TrustStore,
    old_entry: Option<&TrustEntry>,
    new_pubkey_b64: &str,
    display_name: &str,
    mur_home: &Path,
) -> Result<(), String> {
    let manifest_path = rotation_manifest_path(mur_home, display_name);
    if !manifest_path.exists() {
        return Err(
            "no rotation manifest is present (possible impersonation; place \
             <display_name>.yaml in ~/.mur/trust/rotations/ if intentional)"
                .into(),
        );
    }

    let yaml =
        fs::read_to_string(&manifest_path).map_err(|e| format!("read rotation manifest: {e}"))?;
    let manifest: RotationManifest =
        serde_yaml_ng::from_str(&yaml).map_err(|e| format!("parse rotation manifest: {e}"))?;

    // Cross-check: manifest must reference the known old key and the incoming new key.
    if let Some(entry) = old_entry
        && manifest.old_pubkey != entry.public_key
    {
        return Err("rotation manifest old_pubkey does not match the known trust entry".into());
    }
    if manifest.new_pubkey != new_pubkey_b64 {
        return Err("rotation manifest new_pubkey does not match the package's signing key".into());
    }

    // Cryptographic verification (old key signs, new key countersigns).
    manifest.verify()?;

    // Replay prevention: issued_at must be strictly newer than last_rotation_at.
    if let Some(entry) = old_entry
        && let Some(last_at) = &entry.last_rotation_at
        && manifest.issued_at <= *last_at
    {
        return Err(format!(
            "rotation manifest issued_at ({}) is not newer than last_rotation_at ({})",
            manifest.issued_at, last_at
        ));
    }

    // Apply: mark old entry Superseded, insert new entry.
    let now = chrono::Utc::now().to_rfc3339();
    if let Some(entry) = old_entry.cloned() {
        trust_store.upsert(TrustEntry {
            trust_level: TrustLevel::Superseded,
            superseded_at: Some(manifest.issued_at.clone()),
            last_rotation_at: Some(manifest.issued_at.clone()),
            ..entry
        });
    }
    trust_store.upsert(TrustEntry {
        public_key: new_pubkey_b64.to_string(),
        display_name_seen: display_name.to_string(),
        first_seen: now.clone(),
        last_seen: now,
        last_seen_surface: String::new(), // filled by caller during upsert_trust
        trust_level: TrustLevel::Pending,
        fingerprint: String::new(), // filled by caller
        word_list: String::new(),   // filled by caller
        rotated_from: old_entry.map(|e| e.public_key.clone()),
        superseded_at: None,
        last_rotation_at: Some(manifest.issued_at.clone()),
    });

    Ok(())
}

/// Remove every entry in `dir` except `data/`. Used by the update path.
fn clear_except_data(dir: &Path) -> Result<(), MuragentError> {
    for entry in fs::read_dir(dir).map_err(MuragentError::Io)? {
        let entry = entry.map_err(MuragentError::Io)?;
        if entry.file_name() == "data" {
            continue;
        }
        let path = entry.path();
        if path.is_dir() {
            fs::remove_dir_all(&path).map_err(MuragentError::Io)?;
        } else {
            fs::remove_file(&path).map_err(MuragentError::Io)?;
        }
    }
    Ok(())
}

fn extract_payload(archive: &MuragentArchive, agent_dir: &Path) -> Result<(), MuragentError> {
    for (path, data) in &archive.files {
        if ENVELOPE_FILES.contains(&path.as_str()) {
            continue;
        }
        let dest = agent_dir.join(path);
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent).map_err(MuragentError::Io)?;
        }
        fs::write(&dest, data).map_err(MuragentError::Io)?;
    }
    Ok(())
}

fn upsert_trust(
    trust_store: &mut TrustStore,
    result: &ValidationResult,
    author_pubkey_b64: &str,
    existing: &Option<TrustEntry>,
    surface: &str,
) -> Result<(TrustLevel, PathBuf), MuragentError> {
    let now = chrono::Utc::now().to_rfc3339();
    let first_seen = existing
        .as_ref()
        .map(|e| e.first_seen.clone())
        .unwrap_or_else(|| now.clone());
    // Promotion to Known is a UI decision, not an install-flow decision.
    // First-time-seen authors land at Pending and stay there until the
    // surface explicitly promotes them.
    let level = existing
        .as_ref()
        .map(|e| e.trust_level.clone())
        .unwrap_or(TrustLevel::Pending);

    trust_store.upsert(TrustEntry {
        public_key: author_pubkey_b64.to_string(),
        display_name_seen: result.manifest.agent.display_name.clone(),
        first_seen,
        last_seen: now,
        last_seen_surface: surface.to_string(),
        trust_level: level.clone(),
        fingerprint: trust::short_fingerprint(&result.author_pubkey),
        word_list: trust::word_list_fingerprint(&result.author_pubkey),
        rotated_from: existing.as_ref().and_then(|e| e.rotated_from.clone()),
        superseded_at: existing.as_ref().and_then(|e| e.superseded_at.clone()),
        last_rotation_at: existing.as_ref().and_then(|e| e.last_rotation_at.clone()),
    });

    Ok((level, PathBuf::new()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::identity::AgentIdentity;
    use crate::muragent::writer::{MuragentWriter, build_manifest_from_profile};
    use tempfile::TempDir;

    fn make_test_package(tmp: &TempDir) -> std::path::PathBuf {
        let out = tmp.path().join("test.muragent");
        let profile = AgentProfile::default_for_tests();
        let identity = AgentIdentity::generate();
        let manifest = build_manifest_from_profile(&profile, "2.13.0");
        let profile_yaml = serde_yaml_ng::to_string(&profile).unwrap();
        let mut writer = MuragentWriter::new(manifest, profile_yaml, identity);
        writer.add_icon("icon-512.png", b"fake-png".to_vec());
        writer.write(&out).unwrap();
        out
    }

    fn make_test_package_with_identity(
        tmp: &TempDir,
        identity: &AgentIdentity,
    ) -> std::path::PathBuf {
        let out = tmp
            .path()
            .join(format!("{}.muragent", &identity.pubkey_text()[..8]));
        let profile = AgentProfile::default_for_tests();
        let manifest = build_manifest_from_profile(&profile, "2.13.0");
        let profile_yaml = serde_yaml_ng::to_string(&profile).unwrap();
        let mut writer = MuragentWriter::new(manifest, profile_yaml, identity.clone());
        writer.add_icon("icon-512.png", b"fake-png".to_vec());
        writer.write(&out).unwrap();
        out
    }

    #[test]
    fn rotation_manifest_missing_still_refuses() {
        let _guard = crate::trust::test_env_lock::MUR_HOME_LOCK.lock().unwrap();
        let tmp = TempDir::new().unwrap();
        let mur_home = tmp.path().join("mur");
        let prev = std::env::var_os("MUR_HOME");
        unsafe { std::env::set_var("MUR_HOME", &mur_home) };

        let old_identity = AgentIdentity::generate();
        let pkg_old = make_test_package_with_identity(&tmp, &old_identity);
        let archive = MuragentArchive::read(&pkg_old).unwrap();
        let outcome = install(&archive, &mur_home, "test").unwrap();
        let slug = outcome.manifest.agent.slug.clone();

        let new_identity = AgentIdentity::generate();
        let profile = AgentProfile::default_for_tests();
        let out2 = tmp.path().join("new2.muragent");
        let manifest2 = build_manifest_from_profile(&profile, "2.14.0");
        let profile_yaml2 = serde_yaml_ng::to_string(&profile).unwrap();
        let mut writer2 = MuragentWriter::new(manifest2, profile_yaml2, new_identity);
        writer2.add_icon("icon-512.png", b"fake-png".to_vec());
        writer2.write(&out2).unwrap();
        let archive2 = MuragentArchive::read(&out2).unwrap();
        let agent_dir = mur_home.join("agents").join(&slug);
        fs::remove_dir_all(&agent_dir).unwrap();

        let err = install(&archive2, &mur_home, "test").unwrap_err();
        assert!(
            matches!(err, MuragentError::TrustRefused(_)),
            "expected TrustRefused, got: {:?}",
            err
        );

        unsafe {
            if let Some(p) = prev {
                std::env::set_var("MUR_HOME", p);
            } else {
                std::env::remove_var("MUR_HOME");
            }
        }
    }

    #[test]
    fn display_name_slug_roundtrip() {
        assert_eq!(display_name_slug("My Agent"), "my-agent");
        assert_eq!(display_name_slug("Coach (Beta)"), "coach-beta");
        assert_eq!(display_name_slug("test"), "test");
    }

    #[test]
    fn install_then_update_preserves_data() {
        let _guard = crate::trust::test_env_lock::MUR_HOME_LOCK.lock().unwrap();
        let tmp = TempDir::new().unwrap();
        let mur_home = tmp.path().join("mur");
        let prev = std::env::var_os("MUR_HOME");
        unsafe { std::env::set_var("MUR_HOME", &mur_home) };

        let pkg = make_test_package(&tmp);
        let archive = MuragentArchive::read(&pkg).unwrap();
        let outcome = install(&archive, &mur_home, "test").unwrap();
        assert!(!outcome.was_update);
        let slug = outcome.manifest.agent.slug.clone();
        let agent_dir = mur_home.join("agents").join(&slug);
        assert!(agent_dir.join("profile.yaml").exists());

        // Caller writes some data — the update path must preserve it.
        let data_dir = agent_dir.join("data");
        fs::create_dir_all(&data_dir).unwrap();
        fs::write(data_dir.join("history.jsonl"), b"important").unwrap();

        // Re-install (same archive, same UUID) — should preserve data/
        let outcome2 = install(&archive, &mur_home, "test").unwrap();
        assert!(outcome2.was_update);
        let preserved = fs::read(data_dir.join("history.jsonl")).unwrap();
        assert_eq!(preserved, b"important");

        // Cleanup
        unsafe {
            if let Some(p) = prev {
                std::env::set_var("MUR_HOME", p);
            } else {
                std::env::remove_var("MUR_HOME");
            }
        }
    }
}