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