Skip to main content

mur_common/agent/
mod.rs

1//! Agent profile, Agent Card, and LockFile types shared between
2//! mur-agent-runtime and mur-core.
3
4use crate::companion::{Formality, Relationship};
5use crate::deps::ProgramDep;
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8
9mod companion;
10mod entitlements;
11mod lifecycle;
12mod mcp;
13mod mcp_status;
14mod reload;
15mod reload_mcp;
16mod transport;
17
18pub use companion::*;
19pub use entitlements::*;
20pub use lifecycle::*;
21pub use mcp::*;
22pub use mcp_status::{MCP_STATUS_FILE, McpServerStatus, McpStatus};
23pub use reload::{HOT_PATHS, RELOAD_STATE_FILE, ReloadDiff, ReloadState};
24pub use transport::*;
25
26/// Skill metadata broadcast in the Agent Card (Layer 1 + Layer 2).
27///
28/// Populated by `mur skill install` (registry or agent:// URL). Distinct from
29/// `AgentProfile.skills`, which is the legacy per-agent-path list managed by
30/// `mur agent skill add`.
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
32pub struct SkillCardEntry {
33    pub name: String,
34    #[serde(default, skip_serializing_if = "String::is_empty")]
35    pub version: String,
36    #[serde(default, skip_serializing_if = "String::is_empty")]
37    pub publisher: String,
38    #[serde(default, skip_serializing_if = "String::is_empty")]
39    pub description: String,
40    #[serde(default, skip_serializing_if = "String::is_empty")]
41    pub category: String,
42    #[serde(default, skip_serializing_if = "Vec::is_empty")]
43    pub tags: Vec<String>,
44    #[serde(default, skip_serializing_if = "Vec::is_empty")]
45    pub triggers: Vec<SkillCardTrigger>,
46    /// Layer 2 abstract — injected at session start (~200 tokens).
47    /// On-disk YAML key is `abstract` (a Rust reserved word).
48    #[serde(default, skip_serializing_if = "String::is_empty", rename = "abstract")]
49    pub abstract_text: String,
50    /// Provenance chain copied from the installed manifest. Empty for
51    /// registry-installed skills.
52    #[serde(default, skip_serializing_if = "Vec::is_empty")]
53    pub transfer_chain: Vec<String>,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
57pub struct SkillCardTrigger {
58    #[serde(rename = "type")]
59    pub kind: String,
60    #[serde(default, skip_serializing_if = "String::is_empty")]
61    pub pattern: String,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
65pub struct AgentProfile {
66    pub schema: u32,
67    pub id: String, // UUIDv7
68    pub name: String,
69    pub display_name: String,
70    /// Coarse human-facing role for grouping/filtering (e.g. "Engineer").
71    /// A free label, not a registry — bundled defaults are UI suggestions and
72    /// users can type their own. Also the SOFT signal in the dispatch index
73    /// (`agent_facts`), where it explains and ranks candidates but never
74    /// filters them: what an agent may actually do is decided by
75    /// `entitlements`, which the kernel enforces and a stale label cannot
76    /// overstate.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub role: Option<String>,
79    /// How hard this agent's model should work per turn
80    /// (`low`/`medium`/`high`/`xhigh`/`max`). `None` leaves the field off,
81    /// which is the API default (`high`) — not "no effort".
82    ///
83    /// Set it where the agent's JOB is known: a single-purpose build
84    /// specialist earns `xhigh`, a fan-out research worker `medium`, a
85    /// classifier `low`. Narrowed to what the resolved model accepts at the
86    /// client boundary, so an agent pinned to an older model degrades rather
87    /// than 400s.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub effort: Option<crate::llm::Effort>,
90    pub version: String,
91    pub persona: Persona,
92    pub sys_prompt_file: String,
93    pub model: ModelConfig,
94    /// Optional pointer into ~/.mur/models.yaml. When set, the runtime
95    /// prefers the registry entry over the inline `model:` block.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub model_ref: Option<String>,
98    /// Per-agent fallback chain (ordered model_refs). Overrides the global
99    /// `models.fallback_chain` when non-empty. See the model-switch spec.
100    #[serde(default, skip_serializing_if = "Vec::is_empty")]
101    pub fallback_chain: Vec<String>,
102    /// Per-agent difficulty-routing override. Absent fields inherit the global
103    /// `models.routing`.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub routing: Option<crate::config::RoutingOverride>,
106    /// Per-agent Smart background-routing override. Absent fields inherit the
107    /// global `models.smart`; `None` means "follow the global setting".
108    /// Promoted out of `routing` — nesting it there meant overriding Smart
109    /// silently rewrote this agent's difficulty routing as a side effect.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub smart: Option<crate::config::SmartOverride>,
112    #[serde(default)]
113    pub mcp_servers: Vec<McpServerEntry>,
114    #[serde(default)]
115    pub skills: Vec<String>,
116    /// Skills installed via `mur skill install`. Distinct from `skills`
117    /// (which holds legacy per-agent paths from `mur agent skill add`).
118    /// Broadcast in the Agent Card alongside `skills`.
119    #[serde(default, skip_serializing_if = "Vec::is_empty")]
120    pub installed_skills: Vec<SkillCardEntry>,
121    /// Per-agent skill denylist (add-on Phase 1). Skill names that are
122    /// installed/visible to this agent but suppressed from injection.
123    /// Non-destructive: the skill's files/stats are untouched. Empty = all
124    /// visible skills enabled (back-compat: absent in old profiles).
125    #[serde(default, skip_serializing_if = "Vec::is_empty")]
126    pub disabled_skills: Vec<String>,
127
128    /// Per-agent MCP denylist (add-on Phase 1). `McpServerEntry` names not
129    /// spawned for this agent. Non-destructive: the entry + its pin stay in
130    /// the profile. Empty = all configured servers enabled.
131    #[serde(default, skip_serializing_if = "Vec::is_empty")]
132    pub disabled_mcp: Vec<String>,
133
134    /// Names of per-agent secrets the user handed this agent (murmur
135    /// `/secret`, `mur agent secret set`). NAMES ONLY — the values live in the
136    /// keychain under `mur-agent/<name>/<NAME>`. The list exists because the
137    /// keychain cannot be enumerated: the supervisor reads it pre-seal to know
138    /// which accounts to load. Empty = nothing to load (back-compat).
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    pub secrets: Vec<String>,
141    /// Plugin-groups imported by this agent (add-on Phase 2). Each is
142    /// self-contained (members installed per-agent). Absent/empty in
143    /// legacy profiles (back-compat).
144    #[serde(default, skip_serializing_if = "Vec::is_empty")]
145    pub addons: Vec<AddonRef>,
146    pub transport: TransportConfig,
147    pub communication: CommunicationConfig,
148    #[serde(default)]
149    pub capabilities: Vec<String>,
150    pub entitlements: Entitlements,
151    #[serde(default)]
152    pub notifications: NotificationsConfig,
153    pub retry: RetryConfig,
154    pub lifecycle: LifecycleConfig,
155    /// Cryptographic identity for cross-host A2A (P0a.5+). Default = empty
156    /// (legacy P0a profiles continue to load without this block).
157    #[serde(default)]
158    pub identity: IdentityConfig,
159    #[serde(default)]
160    pub file_transfer: FileTransferConfig,
161    #[serde(default)]
162    pub deployment: DeploymentConfig,
163    /// Companion subsystem (Phase 1.1+). Default = disabled (legacy profiles
164    /// continue to load without this block).
165    #[serde(default)]
166    pub companion: CompanionConfig,
167    /// Human-in-the-loop configuration (Phase 2). Default = disabled.
168    #[serde(default)]
169    pub hitl: HitlConfig,
170    /// Execution limits for this agent's own tasks (spec 2026-09-12 §3.1).
171    /// Absent → inherit. Replaces `hitl.max_iterations` / `hitl.max_tokens`,
172    /// which stay readable for the migration warning until the runtime
173    /// switch (step 4) stops applying them.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub limits: Option<crate::limits::Limits>,
176    /// Voice I/O configuration (D1). Default = disabled.
177    #[serde(default)]
178    pub voice: VoiceConfig,
179    /// A1: config-driven handler picker. Absent block = all defaults.
180    #[serde(default)]
181    pub hooks: crate::HooksConfig,
182    /// Pubkeys of bridges (and other LLM-less peers) this agent will accept
183    /// signed envelopes from. Empty = accept no bridge traffic. Default = empty.
184    #[serde(default)]
185    pub trusted_peers: Vec<crate::bridge::peer::TrustedPeer>,
186    pub created_at: String,
187    pub updated_at: String,
188    /// Hub companion visual identity (M-h3). Default = default-blob / Normal / Pending.
189    #[serde(default)]
190    pub appearance: AgentAppearance,
191    /// E6: Pattern federation — snapshot filter + outbox config.
192    #[serde(default)]
193    pub federation: FederationConfig,
194
195    /// A1: declarative UI action list — file_actions rendered as action
196    /// buttons in the pending-item selection UI. New top-level key; NOT
197    /// nested under `capabilities:`.
198    #[serde(default)]
199    pub file_actions: Vec<crate::action::FileAction>,
200
201    /// A2 + A3: action pipeline configuration (deletion safety + queue limits).
202    #[serde(default)]
203    pub action_pipeline: crate::action::ActionPipelineConfig,
204
205    /// External programs this artifact needs at runtime (portable-deps spec).
206    /// Absent → empty; resolved by `mur agent/fleet doctor` + `install-deps`.
207    #[serde(default, skip_serializing_if = "Vec::is_empty")]
208    pub requires_programs: Vec<ProgramDep>,
209
210    /// Capability refs installed into this agent (Pack S3). Absent → empty;
211    /// resolved against the local capability registry / bundle store.
212    #[serde(default, skip_serializing_if = "Vec::is_empty")]
213    pub requires_capabilities: Vec<String>,
214
215    /// Keys this build does not know (written by a newer `mur`). Kept so a
216    /// rewrite by an older binary round-trips them instead of dropping them
217    /// (#1713). Never read by logic; empty for every profile this build wrote.
218    #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
219    pub extra: BTreeMap<String, serde_yaml_ng::Value>,
220}
221
222fn default_algorithm() -> String {
223    "ed25519".into()
224}
225
226/// Algorithms the runtime can generate + verify.
227pub const SUPPORTED_ALGORITHMS: &[&str] = &["ed25519"];
228
229#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
230pub struct IdentityConfig {
231    /// Multibase-encoded Ed25519 public key (base58btc, `z` prefix).
232    /// Empty string for legacy P0a profiles; filled on P0a.5 `mur agent create`.
233    #[serde(default)]
234    pub pubkey: String,
235    /// Free-form owner identity (email / SSO sub). None for legacy profiles.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub owner: Option<String>,
238
239    // P0a.6 rekey extensions (all #[serde(default)] — back-compat)
240    /// Cryptographic algorithm for this key. Defaults to "ed25519".
241    #[serde(default = "default_algorithm")]
242    pub algorithm: String,
243    /// Monotonic version counter; 0 = initial create, increments on each rotation.
244    #[serde(default)]
245    pub key_version: u32,
246    /// RFC3339 timestamp of when this key was created.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub created_at_key: Option<String>,
249    /// Previous public key (before most recent rotation). None if not rotated yet.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub previous_pubkey: Option<String>,
252    /// Version of the previous key. None if not rotated yet.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub previous_key_version: Option<u32>,
255    /// RFC3339 timestamp when grace period expires and old key is fully retired.
256    /// Only set during rotation; cleared once grace period ends.
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub grace_expires_at: Option<String>,
259    /// RFC3339 timestamp of the most recent key rotation (normal, not emergency).
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub rotated_at: Option<String>,
262    /// RFC3339 timestamp of emergency key rotation (set only if emergency rekey occurred).
263    #[serde(default, skip_serializing_if = "Option::is_none")]
264    pub emergency_rekey_at: Option<String>,
265}
266
267impl Default for IdentityConfig {
268    fn default() -> Self {
269        Self {
270            pubkey: String::new(),
271            owner: None,
272            algorithm: default_algorithm(),
273            key_version: 0,
274            created_at_key: None,
275            previous_pubkey: None,
276            previous_key_version: None,
277            grace_expires_at: None,
278            rotated_at: None,
279            emergency_rekey_at: None,
280        }
281    }
282}
283
284#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
285pub struct Persona {
286    pub category: PersonaCategory,
287    pub description: String,
288    pub traits: PersonaTraits,
289}
290
291#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
292#[serde(rename_all = "lowercase")]
293pub enum PersonaCategory {
294    Research,
295    Automation,
296    Monitor,
297    Notify,
298    Commerce,
299    Custom,
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
303pub struct PersonaTraits {
304    pub tone: String,
305    pub risk: String,
306    pub verbosity: String,
307}
308
309#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
310pub struct ModelConfig {
311    pub provider: String,
312    pub name: String,
313    #[serde(default)]
314    pub params: BTreeMap<String, serde_yaml_ng::Value>,
315}
316
317fn default_true() -> bool {
318    true
319}
320
321impl AgentProfile {
322    /// Minimal valid profile for tests — no voice, no MCP, no skills.
323    ///
324    /// Available in all compilation modes so integration tests in
325    /// dependent crates can call it (unlike `#[cfg(test)]` items which
326    /// are invisible to downstream test binaries).
327    #[doc(hidden)]
328    pub fn default_for_tests() -> Self {
329        serde_yaml_ng::from_str(include_str!("../../tests/fixtures/minimal_profile.yaml"))
330            .expect("minimal profile fixture")
331    }
332
333    /// This agent's Smart override, wherever it lives: the promoted `smart`
334    /// field, else the legacy `routing.smart` nesting that older profiles and
335    /// exported `.muragent` bundles still carry. `None` = follow the global
336    /// setting.
337    ///
338    /// Every reader goes through here. A surface that checked only the
339    /// promoted field would report "follows global" for an agent whose legacy
340    /// override is actually in force — one fact, two answers.
341    pub fn smart_override(&self) -> Option<&crate::config::SmartOverride> {
342        self.smart
343            .as_ref()
344            .or_else(|| self.routing.as_ref().and_then(|r| r.smart.as_ref()))
345    }
346
347    /// This agent's effective Smart config: the global values with the agent's
348    /// override layered on.
349    pub fn effective_smart(
350        &self,
351        cfg: &crate::config::ModelSwitchConfig,
352    ) -> crate::config::SmartConfig {
353        cfg.smart.merged(self.smart_override())
354    }
355
356    /// This agent's effective difficulty-routing config.
357    pub fn effective_routing(
358        &self,
359        cfg: &crate::config::ModelSwitchConfig,
360    ) -> crate::config::RoutingConfig {
361        cfg.routing.merged(self.routing.as_ref())
362    }
363
364    /// Load an agent's profile from `<mur_home>/agents/<name>/profile.yaml`.
365    ///
366    /// Canonical read-path counterpart to the atomic-write path used by
367    /// `mur agent create`/`mur agent mcp add` (`write_atomic` in
368    /// `mur-core::cmd::agent`) — callers that already have `mur_home` in
369    /// hand (e.g. provisioning flows, tests) can load a profile without
370    /// going through the `MUR_HOME`-env-var-based `resolve_mur_home`.
371    pub fn load(mur_home: &std::path::Path, name: &str) -> anyhow::Result<Self> {
372        let path = mur_home.join("agents").join(name).join("profile.yaml");
373        let yaml = std::fs::read_to_string(&path)
374            .map_err(|e| anyhow::anyhow!("read {}: {e}", path.display()))?;
375        serde_yaml_ng::from_str(&yaml).map_err(|e| anyhow::anyhow!("parse {}: {e}", path.display()))
376    }
377
378    /// The imported add-on group a skill/mcp/command name belongs to.
379    pub fn group_of(&self, name: &str) -> Option<&AddonRef> {
380        self.addons.iter().find(|g| {
381            g.skills.iter().any(|n| n == name)
382                || g.mcp.iter().any(|n| n == name)
383                || g.commands.iter().any(|n| n == name)
384        })
385    }
386
387    /// Whether `skill_name` is enabled (§3.3): not denied AND, if it
388    /// belongs to an imported group, that group is enabled.
389    pub fn skill_enabled(&self, skill_name: &str) -> bool {
390        name_enabled(&self.disabled_skills, skill_name)
391            && self.group_of(skill_name).is_none_or(|g| g.enabled)
392    }
393
394    /// Whether MCP server `server_id` is enabled (§3.3).
395    pub fn mcp_enabled(&self, server_id: &str) -> bool {
396        name_enabled(&self.disabled_mcp, server_id)
397            && self.group_of(server_id).is_none_or(|g| g.enabled)
398    }
399
400    /// Toggle a skill for this agent without uninstalling it.
401    pub fn set_skill_enabled(&mut self, skill_name: &str, enabled: bool) {
402        set_denylist(&mut self.disabled_skills, skill_name, enabled);
403    }
404
405    /// Toggle an MCP server for this agent without removing it.
406    pub fn set_mcp_enabled(&mut self, server_id: &str, enabled: bool) {
407        set_denylist(&mut self.disabled_mcp, server_id, enabled);
408    }
409
410    /// Toggle an imported plugin-group as a unit. Returns false if no
411    /// add-on has that id.
412    pub fn set_addon_enabled(&mut self, addon_id: &str, enabled: bool) -> bool {
413        match self.addons.iter_mut().find(|g| g.id == addon_id) {
414            Some(g) => {
415                g.enabled = enabled;
416                true
417            }
418            None => false,
419        }
420    }
421
422    /// Emergency kill-switch (§7): clears every add-on group's `enabled` flag.
423    /// Members are already forced off by the group AND-gate in `skill_enabled` /
424    /// `mcp_enabled`, so no denylist push is needed — and avoiding it means
425    /// `set_addon_enabled(id, true)` fully restores the group without leftover
426    /// per-member denials.
427    pub fn disable_all_addons(&mut self) {
428        for g in &mut self.addons {
429            g.enabled = false;
430        }
431    }
432
433    /// This agent's MCP servers minus any disabled for it.
434    pub fn enabled_mcp_servers(&self) -> Vec<McpServerEntry> {
435        self.mcp_servers
436            .iter()
437            .filter(|m| self.mcp_enabled(&m.name))
438            .cloned()
439            .collect()
440    }
441}
442
443#[cfg(test)]
444mod model_ref_tests {
445    use super::*;
446
447    #[test]
448    fn legacy_profile_without_model_ref_still_parses() {
449        let yaml = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
450        let p: AgentProfile = serde_yaml_ng::from_str(yaml).unwrap();
451        assert!(
452            p.model_ref.is_none(),
453            "legacy profile must not have model_ref"
454        );
455    }
456
457    #[test]
458    fn round_trip_with_model_ref_preserves_field() {
459        let yaml = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
460        let mut p: AgentProfile = serde_yaml_ng::from_str(yaml).unwrap();
461        p.model_ref = Some("anthropic_opus_4_7".into());
462        let s = serde_yaml_ng::to_string(&p).unwrap();
463        assert!(s.contains("model_ref: anthropic_opus_4_7"), "yaml: {s}");
464        let p2: AgentProfile = serde_yaml_ng::from_str(&s).unwrap();
465        assert_eq!(p2.model_ref.as_deref(), Some("anthropic_opus_4_7"));
466    }
467
468    #[test]
469    fn per_agent_fallback_and_routing_optional_and_legacy_safe() {
470        // Load fixture (no fallback_chain / routing) — legacy safe.
471        let yaml = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
472        let p: AgentProfile = serde_yaml_ng::from_str(yaml).unwrap();
473        assert!(
474            p.fallback_chain.is_empty(),
475            "legacy profile must have empty fallback_chain"
476        );
477        assert!(
478            p.routing.is_none(),
479            "legacy profile must have no routing override"
480        );
481
482        // Round-trip with fallback_chain and routing.
483        let mut p = p.clone();
484        p.fallback_chain = vec!["claude_opus".into(), "claude_sonnet".into()];
485        p.routing = Some(crate::config::RoutingOverride {
486            enabled: Some(true),
487            ..Default::default()
488        });
489        let s = serde_yaml_ng::to_string(&p).unwrap();
490        assert!(
491            s.contains("fallback_chain:"),
492            "yaml must contain fallback_chain"
493        );
494        assert!(s.contains("routing:"), "yaml must contain routing");
495        let p2: AgentProfile = serde_yaml_ng::from_str(&s).unwrap();
496        assert_eq!(
497            p2.fallback_chain,
498            vec!["claude_opus", "claude_sonnet"],
499            "fallback_chain must round-trip"
500        );
501        assert_eq!(
502            p2.routing.as_ref().unwrap().enabled,
503            Some(true),
504            "routing.enabled must round-trip"
505        );
506    }
507
508    #[test]
509    fn effective_smart_prefers_the_promoted_field_then_the_legacy_nesting() {
510        use crate::config::{ModelSwitchConfig, SmartConfig, SmartOverride};
511        let cfg = ModelSwitchConfig {
512            smart: SmartConfig {
513                enabled: false,
514                cheap: Some("g".into()),
515                max_escalations: 2,
516            },
517            ..Default::default()
518        };
519        // No override at all → the global values, untouched.
520        let p = AgentProfile::default_for_tests();
521        assert_eq!(p.effective_smart(&cfg), cfg.smart);
522
523        // Legacy profiles carry the override nested under `routing`.
524        let mut legacy = AgentProfile::default_for_tests();
525        legacy.routing = Some(crate::config::RoutingOverride {
526            smart: Some(SmartOverride {
527                enabled: Some(true),
528                ..Default::default()
529            }),
530            ..Default::default()
531        });
532        assert!(
533            legacy.effective_smart(&cfg).enabled,
534            "legacy nesting is read"
535        );
536        assert_eq!(
537            legacy.effective_smart(&cfg).cheap.as_deref(),
538            Some("g"),
539            "unset fields still inherit"
540        );
541
542        // The promoted field wins when both are present.
543        let mut both = legacy.clone();
544        both.smart = Some(SmartOverride {
545            enabled: Some(false),
546            ..Default::default()
547        });
548        assert!(!both.effective_smart(&cfg).enabled);
549    }
550}
551
552#[cfg(test)]
553mod skill_card_tests {
554    use super::*;
555
556    #[test]
557    fn installed_skills_default_to_empty_when_absent() {
558        let yaml = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
559        let p: AgentProfile = serde_yaml_ng::from_str(yaml).unwrap();
560        assert!(p.installed_skills.is_empty());
561    }
562
563    #[test]
564    fn installed_skills_roundtrip_preserves_entries() {
565        let base = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
566        let yaml = format!(
567            "{base}installed_skills:\n  - name: s1\n    version: 1.0.0\n    publisher: human:d\n    description: desc\n    category: workflow\n    tags: [web]\n    triggers:\n      - type: command\n        pattern: /find\n    abstract: does things\n    transfer_chain:\n      - agent://alice\n"
568        );
569        let p: AgentProfile = serde_yaml_ng::from_str(&yaml).unwrap();
570        assert_eq!(p.installed_skills.len(), 1);
571        assert_eq!(p.installed_skills[0].name, "s1");
572        assert_eq!(p.installed_skills[0].abstract_text, "does things");
573        assert_eq!(p.installed_skills[0].transfer_chain, vec!["agent://alice"]);
574
575        let out = serde_yaml_ng::to_string(&p).unwrap();
576        assert!(out.contains("abstract: does things"));
577        assert!(out.contains("pattern: /find"));
578
579        let back: AgentProfile = serde_yaml_ng::from_str(&out).unwrap();
580        assert_eq!(p.installed_skills, back.installed_skills);
581    }
582
583    #[test]
584    fn installed_skills_minimal_entry_serializes_compactly() {
585        // A name-only entry must NOT emit empty string fields.
586        let entry = SkillCardEntry {
587            name: "minimal".into(),
588            ..Default::default()
589        };
590        let yaml = serde_yaml_ng::to_string(&entry).unwrap();
591        assert!(yaml.contains("name: minimal"));
592        assert!(
593            !yaml.contains("version:"),
594            "empty version must be skipped: {yaml}"
595        );
596        assert!(
597            !yaml.contains("publisher:"),
598            "empty publisher must be skipped: {yaml}"
599        );
600        assert!(
601            !yaml.contains("abstract:"),
602            "empty abstract must be skipped: {yaml}"
603        );
604    }
605}
606
607#[cfg(test)]
608mod secrets_field_tests {
609    /// The list is NAMES only and must stay absent from the YAML when empty:
610    /// every existing profile on disk is rewritten by unrelated edits, and a
611    /// new always-present key would churn all of them.
612    #[test]
613    fn secrets_names_round_trip_and_are_absent_when_empty() {
614        let mut p = crate::agent::AgentProfile::default_for_tests();
615        let yaml = serde_yaml::to_string(&p).unwrap();
616        assert!(
617            !yaml.contains("secrets:"),
618            "empty list must not be written: {yaml}"
619        );
620        p.secrets = vec!["GITEA_TOKEN".into()];
621        let yaml = serde_yaml::to_string(&p).unwrap();
622        let back: crate::agent::AgentProfile = serde_yaml::from_str(&yaml).unwrap();
623        assert_eq!(back.secrets, vec!["GITEA_TOKEN".to_string()]);
624    }
625}