Skip to main content

mur_common/agent/
lifecycle.rs

1use super::*;
2
3#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
4pub struct NotificationsConfig {
5    #[serde(default)]
6    pub on_task_complete: Vec<NotificationTarget>,
7    #[serde(default)]
8    pub on_error: Vec<NotificationTarget>,
9    #[serde(default)]
10    pub on_shutdown: Vec<NotificationTarget>,
11}
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
14#[serde(tag = "target", rename_all = "lowercase")]
15pub enum NotificationTarget {
16    Agent {
17        name: String,
18    },
19    Commander,
20    Email {
21        address: String,
22        #[serde(default)]
23        smtp_config_file: Option<String>,
24    },
25    Slack {
26        #[serde(default)]
27        channel: Option<String>,
28        #[serde(default)]
29        webhook_url_env: Option<String>,
30    },
31    Webpush {
32        url: String,
33    },
34    Webhook {
35        url: String,
36        #[serde(default = "default_post")]
37        method: String,
38        #[serde(default)]
39        auth: Option<String>,
40    },
41}
42fn default_post() -> String {
43    "POST".to_string()
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
47pub struct RetryConfig {
48    pub llm: RetryPolicy,
49    pub tool: RetryPolicy,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
53pub struct RetryPolicy {
54    pub max_retries: u32,
55    pub backoff: BackoffStrategy,
56    pub initial_delay_ms: u64,
57    #[serde(default)]
58    pub max_delay_ms: Option<u64>,
59    #[serde(default)]
60    pub retry_on: Vec<String>,
61}
62
63#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
64#[serde(rename_all = "lowercase")]
65pub enum BackoffStrategy {
66    Linear,
67    Exponential,
68    Fixed,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
72pub struct LifecycleConfig {
73    pub restart: RestartPolicy,
74    #[serde(default = "default_max_restarts")]
75    pub max_restarts: u32,
76    #[serde(default = "default_window")]
77    pub restart_window_secs: u64,
78    #[serde(default = "default_stop_timeout")]
79    pub stop_timeout_secs: u64,
80    #[serde(default = "default_mcp_required")]
81    pub mcp_required: bool,
82    #[serde(default)]
83    pub execution: ExecutionMode,
84    #[serde(default)]
85    pub schedule: Vec<ScheduleEntry>,
86    #[serde(default)]
87    pub idle_triggers: Vec<IdleTrigger>,
88}
89fn default_max_restarts() -> u32 {
90    3
91}
92fn default_window() -> u64 {
93    600
94}
95fn default_stop_timeout() -> u64 {
96    15
97}
98fn default_mcp_required() -> bool {
99    true
100}
101
102#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
103#[serde(rename_all = "snake_case")]
104pub enum RestartPolicy {
105    Never,
106    OnFailure,
107    Always,
108}
109
110#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
111#[serde(rename_all = "snake_case")]
112pub enum ExecutionMode {
113    #[default]
114    Daemon,
115    OnDemand,
116}
117
118/// Where an agent leaves a schedule it wants but cannot create.
119///
120/// An agent's schedules live in `lifecycle.schedule` inside its own
121/// `profile.yaml`, and an agent may not write that file — the sandbox denies it
122/// unconditionally so a running agent cannot widen its own entitlements and
123/// restart into them. So "remind me at 10 tomorrow" cannot become a schedule
124/// from the inside, however much the agent understands the request.
125///
126/// It becomes a proposal instead: a file in the agent's own home, which it may
127/// write, that `mur agent schedule accept` turns into the real entry.
128///
129/// Public and shared because both halves must name the same directory. Two
130/// spellings would not fail loudly — the agent would write proposals nobody
131/// lists, which is the shape of failure this whole area keeps producing.
132pub const SCHEDULE_PROPOSAL_DIR: &str = "schedule-proposals";
133
134/// File in the agent's home holding the id of the channel a fired schedule
135/// leaves its reply in. One stable channel per agent, remembered rather than
136/// re-derived (#1125).
137pub const SCHEDULE_CHANNEL_FILE: &str = "schedule-channel";
138
139/// Marker file in the agent's home naming the channel that records chat-gate
140/// decisions (`HitlResponse` events keyed by `action_hash`). Same shape as
141/// `SCHEDULE_CHANNEL_FILE`: created on first use, replaced if it names a
142/// channel that no longer loads.
143pub const HITL_CHANNEL_FILE: &str = "hitl-channel";
144
145/// Marker file in the agent's home naming the channel that records the
146/// agent's start-time notices (e.g. the ssh-agent proxy classification). Same
147/// shape as `SCHEDULE_CHANNEL_FILE`. Kept apart from `HITL_CHANNEL_FILE` on
148/// purpose: that channel's signed head is integrity-checked by the gate, and a
149/// notice stream has no business advancing it.
150pub const START_CHANNEL_FILE: &str = "start-channel";
151
152/// Directory in the agent's home holding the signed head of the decision
153/// channel (`<agent_home>/hitl-heads/<channel_id>.head`, #1859). It is how gate
154/// B tells "a record was written and then deleted" from "never written".
155pub const HITL_HEAD_DIR: &str = "hitl-heads";
156
157/// A schedule an agent asked for and a person has not yet granted.
158#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
159pub struct ScheduleProposal {
160    pub cron: String,
161    pub message: String,
162    /// What the user actually said, kept verbatim: a cron expression is not
163    /// reviewable on its own, and the reviewer is being asked whether this is
164    /// what they meant.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub asked_for: Option<String>,
167    /// Proposed bound, carried verbatim onto the accepted [`ScheduleEntry`].
168    /// Present exactly when the agent judged the request to name one occasion
169    /// rather than a recurrence.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub not_after: Option<String>,
172    pub proposed_at: String,
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
176pub struct ScheduleEntry {
177    pub cron: String,
178    pub message: String,
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub sends_to: Option<String>,
181    /// Retire the entry once its next firing would fall after this instant
182    /// (RFC3339 with offset). How a one-shot reminder is expressed: cron has no
183    /// year field, so "tomorrow at 10:00" can only be written as an annual
184    /// recurrence, and unbounded it turns a request for one morning into a
185    /// perpetual commitment (#1119).
186    ///
187    /// A bound rather than a fired-yet flag, because the scheduler runs inside
188    /// the agent's own sandbox where `profile.yaml` is denied
189    /// (`SELF_PROTECTED_AGENT_FILES`, #712) — it cannot record that an entry has
190    /// fired. Comparing the next firing against a stored instant needs no write
191    /// at all, so the bound works where a flag structurally could not.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub not_after: Option<String>,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
197pub struct IdleTrigger {
198    /// Idle threshold in seconds. Fires when (now - last_activity) >= after_secs.
199    pub after_secs: u64,
200    /// Message body injected into the task runner when this trigger fires.
201    pub message: String,
202    /// Optional A2A peer to route the resulting reply to. None means the agent itself.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub sends_to: Option<String>,
205    /// Per-trigger refire cooldown in seconds. Prevents tight loops when the
206    /// idle threshold is short and the runner finishes quickly. Default 600.
207    #[serde(default = "default_idle_cooldown")]
208    pub cooldown_secs: u64,
209    /// When true, suppress firing during the agent's quiet-hours window.
210    /// Default true — idle pings should not wake the user at 3 a.m.
211    #[serde(default = "default_true")]
212    pub respect_quiet_hours: bool,
213}
214
215fn default_idle_cooldown() -> u64 {
216    600
217}
218/// True if `name` is not present in a denylist (i.e. enabled).
219pub fn name_enabled(denylist: &[String], name: &str) -> bool {
220    !denylist.iter().any(|n| n == name)
221}
222
223/// Add/remove `name` in a denylist. `enabled=true` removes it (idempotent),
224/// `enabled=false` adds it once (idempotent).
225pub fn set_denylist(list: &mut Vec<String>, name: &str, enabled: bool) {
226    if enabled {
227        list.retain(|n| n != name);
228    } else if !list.iter().any(|n| n == name) {
229        list.push(name.to_string());
230    }
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
234pub struct FileTransferConfig {
235    #[serde(default = "default_accept_max")]
236    pub accept_incoming_file_max_bytes: u64,
237    #[serde(default = "default_accept_total")]
238    pub accept_incoming_total_per_hour: u64,
239    #[serde(default = "default_approval_threshold")]
240    pub require_approval_above_bytes: u64,
241    #[serde(default = "default_reject_paths")]
242    pub reject_paths: Vec<String>,
243    #[serde(default = "default_allowed_mime")]
244    pub allowed_mime_types: Vec<String>,
245}
246
247impl Default for FileTransferConfig {
248    fn default() -> Self {
249        Self {
250            accept_incoming_file_max_bytes: default_accept_max(),
251            accept_incoming_total_per_hour: default_accept_total(),
252            require_approval_above_bytes: default_approval_threshold(),
253            reject_paths: default_reject_paths(),
254            allowed_mime_types: default_allowed_mime(),
255        }
256    }
257}
258
259fn default_accept_max() -> u64 {
260    10_485_760
261}
262fn default_accept_total() -> u64 {
263    104_857_600
264}
265fn default_approval_threshold() -> u64 {
266    10_485_760
267}
268fn default_reject_paths() -> Vec<String> {
269    vec!["~/.ssh".into(), "~/.aws".into(), "~/.gnupg".into()]
270}
271fn default_allowed_mime() -> Vec<String> {
272    vec!["*".into()]
273}
274
275#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
276#[serde(rename_all = "snake_case")]
277pub enum DeploymentType {
278    #[default]
279    Laptop,
280    Vm,
281    Docker,
282    K8s,
283    Lambda,
284}
285
286#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
287pub struct DeploymentConfig {
288    #[serde(rename = "type", default)]
289    pub deployment_type: DeploymentType,
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub region: Option<String>,
292    #[serde(default = "default_env")]
293    pub environment: Option<String>,
294}
295
296impl Default for DeploymentConfig {
297    fn default() -> Self {
298        Self {
299            deployment_type: DeploymentType::default(),
300            region: None,
301            environment: default_env(),
302        }
303    }
304}
305
306fn default_env() -> Option<String> {
307    Some("dev".into())
308}
309
310/// One filesystem grant the sandbox refused to install, and why.
311///
312/// The grant stays in `profile.yaml` — this records that it did not reach the
313/// kernel, which is otherwise knowable only from a WARN line in a log nobody
314/// queries.
315#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
316pub struct DroppedGrant {
317    pub path: String,
318    /// `"read"` or `"write"`.
319    pub verb: String,
320    pub reason: String,
321}
322
323/// Digest of the filesystem half of a profile's entitlements.
324///
325/// Narrower than `card_digest` on purpose: that one moves whenever any profile
326/// field does, so using it to flag "grants changed since this agent started"
327/// would raise a false alarm on an unrelated edit — and a status line that
328/// cries wolf is one people stop reading.
329pub fn filesystem_grants_digest(fs: &FilesystemEntitlement) -> String {
330    use sha2::{Digest, Sha256};
331    let mut h = Sha256::new();
332    for (label, list) in [("r", &fs.read), ("w", &fs.write), ("d", &fs.deny)] {
333        let mut sorted = list.clone();
334        sorted.sort();
335        for p in sorted {
336            h.update(label.as_bytes());
337            h.update(b"\0");
338            h.update(p.as_bytes());
339            h.update(b"\0");
340        }
341    }
342    format!("sha256:{:x}", h.finalize())
343}
344
345/// Digest of the build-lane grants (`processes.spawn.allowed_dirs`).
346///
347/// Kept apart from [`filesystem_grants_digest`] on purpose: folding these into
348/// that one would change the digest of every agent already running, and each
349/// would then report drift it does not have. Order-insensitive, like its
350/// sibling.
351pub fn spawn_dirs_digest(dirs: &[String]) -> String {
352    use sha2::{Digest, Sha256};
353    let mut sorted = dirs.to_vec();
354    sorted.sort();
355    let mut h = Sha256::new();
356    for p in sorted {
357        h.update(b"s\0");
358        h.update(p.as_bytes());
359        h.update(b"\0");
360    }
361    format!("sha256:{:x}", h.finalize())
362}
363
364/// What the sandbox actually installed, recorded at the moment it sealed.
365///
366/// A seatbelt profile cannot be widened after `sandbox_init`, so this is fixed
367/// for the process's lifetime — the same lifetime as the lock file it rides in.
368/// Without it, `profile.yaml` is the only readable account of an agent's
369/// permissions, and it describes what was asked for rather than what took
370/// effect.
371#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
372pub struct SandboxRecord {
373    /// False means the kernel sandbox is NOT installed and only advisory hooks
374    /// remain — the agent then has MORE access than its profile grants, which
375    /// is the opposite of every other failure here and the one worth shouting.
376    pub enforcing: bool,
377    /// `"macos-sbpl"`, `"linux-landlock"`, `"advisory-only"`, …
378    pub mode: String,
379    /// Digest of `entitlements.filesystem` as sealed. Comparing it against the
380    /// profile on disk answers "were grants changed since this agent started"
381    /// without anyone tracking that — and unlike `card_digest` it does not move
382    /// when an unrelated field does, so it cannot raise a false alarm.
383    pub granted_digest: String,
384    /// Digest of `processes.spawn.allowed_dirs` as sealed (#2030). `None` = a
385    /// lock written before this field existed: whether a build-lane grant
386    /// reached the kernel cannot be established from it, and readers must say
387    /// so rather than assume it did.
388    #[serde(default, skip_serializing_if = "Option::is_none")]
389    pub granted_spawn_dirs_digest: Option<String>,
390    /// Grants that did not reach the kernel. Empty is the normal case.
391    #[serde(default)]
392    pub dropped: Vec<DroppedGrant>,
393}
394
395#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
396pub struct LockFile {
397    pub schema: u32,
398    pub uuid: String,
399    pub name: String,
400    pub pid: u32,
401    pub ppid: u32,
402    pub started_at: String,
403    pub binary_version: String,
404    pub transports: LockTransports,
405    pub card_digest: String,
406    pub capabilities: Vec<String>,
407    /// Git sha the running binary was built from (mur_common::build::SHORT_SHA).
408    /// Empty = an old lock predating this field. Drives stale detection.
409    #[serde(default)]
410    pub build_sha: String,
411    /// A2A method-surface version this runtime supports (A2A_PROTO_VERSION).
412    /// 0 = an old lock; the dial gates versioned methods on it.
413    #[serde(default)]
414    pub proto_version: u32,
415    /// What the sandbox installed at seal time. `None` = a lock written before
416    /// this field existed, or a platform that installs no sandbox.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub sandbox: Option<SandboxRecord>,
419}
420
421#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
422pub struct LockTransports {
423    pub stdio: bool,
424    #[serde(default)]
425    pub unix_socket: Option<String>,
426    #[serde(default)]
427    pub tcp: Option<String>,
428    /// C5 / M5.3 — webhook listener URL (e.g. `http://127.0.0.1:6789`).
429    /// Populated by the supervisor when `transport.webhook.enabled =
430    /// true` so peers and the commander can discover the live
431    /// endpoint without re-reading `profile.yaml`.
432    #[serde(default)]
433    pub webhook: Option<String>,
434}
435
436#[cfg(test)]
437mod tests {
438    /// Order must not matter: the same grants written in a different order are
439    /// the same grants, and a digest that disagreed would report "restart to
440    /// apply" after a cosmetic profile edit.
441    #[test]
442    fn grants_digest_ignores_order_but_not_content() {
443        let a = FilesystemEntitlement {
444            read: vec!["/a".into(), "/b".into()],
445            write: vec!["/w".into()],
446            deny: vec![],
447        };
448        let reordered = FilesystemEntitlement {
449            read: vec!["/b".into(), "/a".into()],
450            ..a.clone()
451        };
452        let changed = FilesystemEntitlement {
453            write: vec!["/w".into(), "/x".into()],
454            ..a.clone()
455        };
456        assert_eq!(
457            filesystem_grants_digest(&a),
458            filesystem_grants_digest(&reordered)
459        );
460        assert_ne!(
461            filesystem_grants_digest(&a),
462            filesystem_grants_digest(&changed)
463        );
464    }
465
466    /// A read grant and a write grant for the same path are different grants.
467    #[test]
468    fn grants_digest_separates_the_verbs() {
469        let r = FilesystemEntitlement {
470            read: vec!["/p".into()],
471            write: vec![],
472            deny: vec![],
473        };
474        let w = FilesystemEntitlement {
475            read: vec![],
476            write: vec!["/p".into()],
477            deny: vec![],
478        };
479        assert_ne!(filesystem_grants_digest(&r), filesystem_grants_digest(&w));
480    }
481
482    /// A lock written before this field existed must still load — every agent
483    /// running at upgrade time wrote one.
484    #[test]
485    fn a_lock_without_the_sandbox_block_still_deserialises() {
486        let old = r#"{"schema":1,"uuid":"u","name":"n","pid":1,"ppid":0,
487            "started_at":"t","binary_version":"v",
488            "transports":{"stdio":true},"card_digest":"d","capabilities":[]}"#;
489        let lf: LockFile = serde_json::from_str(old).expect("old lock must load");
490        assert!(lf.sandbox.is_none());
491    }
492
493    #[test]
494    fn spawn_dirs_digest_ignores_order_and_tracks_membership() {
495        let a = vec!["/a".to_string(), "/b".to_string()];
496        let reordered = vec!["/b".to_string(), "/a".to_string()];
497        let grown = vec!["/a".to_string(), "/b".to_string(), "/c".to_string()];
498        assert_eq!(spawn_dirs_digest(&a), spawn_dirs_digest(&reordered));
499        assert_ne!(spawn_dirs_digest(&a), spawn_dirs_digest(&grown));
500        // An empty list is a real, comparable state, not "unknown".
501        assert_ne!(spawn_dirs_digest(&[]), spawn_dirs_digest(&a));
502    }
503
504    #[test]
505    fn a_lock_sealed_before_the_spawn_digest_existed_loads_as_none() {
506        let old = r#"{"enforcing":true,"mode":"macos-sbpl","granted_digest":"sha256:x"}"#;
507        let rec: SandboxRecord = serde_json::from_str(old).expect("old record must load");
508        assert!(rec.granted_spawn_dirs_digest.is_none());
509    }
510
511    #[test]
512    fn the_sandbox_block_round_trips() {
513        let rec = SandboxRecord {
514            enforcing: false,
515            mode: "advisory-only".into(),
516            granted_digest: "sha256:x".into(),
517            granted_spawn_dirs_digest: Some("sha256:y".into()),
518            dropped: vec![DroppedGrant {
519                path: "/gone".into(),
520                verb: "write".into(),
521                reason: "path does not exist on disk".into(),
522            }],
523        };
524        let back: SandboxRecord =
525            serde_json::from_str(&serde_json::to_string(&rec).unwrap()).unwrap();
526        assert_eq!(back, rec);
527    }
528
529    use super::*;
530
531    #[test]
532    fn broad_audited_mcp_net_serde_roundtrip_and_defaults() {
533        let net = McpServerNetwork {
534            mode: McpNetMode::BroadAudited,
535            allow_hosts: vec![],
536            deny_hosts: vec!["evil.example".into()],
537            authorization: Some(EgressAuthorization {
538                authorized_by: "david".into(),
539                authorized_at_ms: 1_750_000_000_000,
540            }),
541        };
542        let y = serde_yaml::to_string(&net).unwrap();
543        assert!(y.contains("broad_audited"));
544        let back: McpServerNetwork = serde_yaml::from_str(&y).unwrap();
545        assert_eq!(back, net);
546        // legacy per-server policy without the new fields still parses (serde default)
547        let legacy: McpServerNetwork =
548            serde_yaml::from_str("mode: restricted\nallow_hosts: []\n").unwrap();
549        assert_eq!(legacy.deny_hosts, Vec::<String>::new());
550        assert!(legacy.authorization.is_none());
551    }
552
553    #[test]
554    fn mcp_entry_network_is_optional_and_round_trips() {
555        // Absent in YAML → None (every existing profile keeps working).
556        let bare = "name: x\ncommand: npx\n";
557        let e: McpServerEntry = serde_yaml_ng::from_str(bare).unwrap();
558        assert!(e.network.is_none());
559
560        // Present → parsed.
561        let with = "name: browser\ncommand: npx\nnetwork:\n  mode: restricted\n  allow_hosts: [\"example.com\", \"*.api.example.com\"]\n";
562        let e2: McpServerEntry = serde_yaml_ng::from_str(with).unwrap();
563        let net = e2.network.expect("network present");
564        assert_eq!(net.mode, McpNetMode::Restricted);
565        assert_eq!(net.allow_hosts, vec!["example.com", "*.api.example.com"]);
566
567        // Round-trip keeps None out of the serialized form.
568        let out = serde_yaml_ng::to_string(&e).unwrap();
569        assert!(!out.contains("network"));
570    }
571
572    #[test]
573    fn profile_round_trip_yaml() {
574        let yaml = r#"
575schema: 1
576id: 01JQX4TM8Y9K7VQH6B2N3R5DPE
577name: agent_a
578display_name: "Price Hunter"
579version: "0.1.0"
580persona:
581  category: research
582  description: "Finds prices"
583  traits: { tone: concise, risk: cautious, verbosity: low }
584sys_prompt_file: "sys_prompt.md"
585model: { provider: ollama, name: "llama3.2:3b", params: { temperature: 0.2, max_tokens: 4096 } }
586mcp_servers: []
587skills: []
588transport:
589  stdio: true
590  socket: { enabled: true, bind: "unix:///tmp/a.sock" }
591communication: { accepts_from: ["*"], sends_to: [] }
592capabilities: ["a2a.message.send", "a2a.tasks"]
593entitlements:
594  network:
595    inbound: { ports: [] }
596    outbound: { mode: restricted, allow_hosts: [], protocols: ["tcp"], resolve_dns: { mode: system } }
597  filesystem: { read: [], write: [], deny: [] }
598  processes: { spawn: { mode: allowlist, allowed: [] } }
599  syscalls: { mode: default }
600  limits: { memory_mb: 512, file_descriptors: 1024, processes: 32 }
601notifications: { on_task_complete: [], on_error: [], on_shutdown: [] }
602retry:
603  llm: { max_retries: 3, backoff: exponential, initial_delay_ms: 1000, max_delay_ms: 30000, retry_on: [rate_limit, timeout, connection_error] }
604  tool: { max_retries: 1, backoff: fixed, initial_delay_ms: 500 }
605lifecycle: { restart: on_failure, max_restarts: 3, restart_window_secs: 600, stop_timeout_secs: 15, mcp_required: true }
606created_at: "2026-04-22T10:00:00+08:00"
607updated_at: "2026-04-22T10:00:00+08:00"
608"#;
609        let profile: AgentProfile = serde_yaml_ng::from_str(yaml).expect("parse");
610        assert_eq!(profile.name, "agent_a");
611        assert_eq!(profile.persona.category, PersonaCategory::Research);
612        assert_eq!(
613            profile.entitlements.network.outbound.mode,
614            NetworkOutboundMode::Restricted
615        );
616        let reserialized = serde_yaml_ng::to_string(&profile).expect("emit");
617        let round_tripped: AgentProfile = serde_yaml_ng::from_str(&reserialized).expect("re-parse");
618        assert_eq!(profile.id, round_tripped.id);
619    }
620
621    #[test]
622    fn requires_capabilities_defaults_empty_and_round_trips() {
623        let base = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
624        let p: AgentProfile = serde_yaml_ng::from_str(base).unwrap();
625        assert!(p.requires_capabilities.is_empty());
626        let with = format!("{base}\nrequires_capabilities:\n  - media\n");
627        let p2: AgentProfile = serde_yaml_ng::from_str(&with).unwrap();
628        assert_eq!(p2.requires_capabilities, vec!["media"]);
629    }
630}
631
632#[cfg(test)]
633mod idle_trigger_tests {
634    use super::*;
635
636    #[test]
637    fn idle_trigger_yaml_round_trip() {
638        let yaml = r#"
639restart: on_failure
640idle_triggers:
641  - after_secs: 3600
642    message: "still there?"
643    sends_to: other_agent
644    cooldown_secs: 1800
645    respect_quiet_hours: true
646"#;
647        let cfg: LifecycleConfig = serde_yaml_ng::from_str(yaml).unwrap();
648        assert_eq!(cfg.idle_triggers.len(), 1);
649        assert_eq!(cfg.idle_triggers[0].after_secs, 3600);
650        assert_eq!(cfg.idle_triggers[0].message, "still there?");
651        assert_eq!(
652            cfg.idle_triggers[0].sends_to.as_deref(),
653            Some("other_agent")
654        );
655        assert_eq!(cfg.idle_triggers[0].cooldown_secs, 1800);
656        assert!(cfg.idle_triggers[0].respect_quiet_hours);
657    }
658
659    #[test]
660    fn idle_trigger_defaults_when_omitted() {
661        let yaml = "restart: on_failure\n";
662        let cfg: LifecycleConfig = serde_yaml_ng::from_str(yaml).unwrap();
663        assert!(cfg.idle_triggers.is_empty());
664    }
665}
666
667#[cfg(test)]
668mod lockfile_compat_tests {
669    use super::*;
670
671    #[test]
672    fn lockfile_new_fields_default_for_old_locks() {
673        // An old lock JSON without build_sha/proto_version must still parse,
674        // defaulting to "" / 0 (= "predates this feature → stale/unsupported").
675        let old = r#"{"schema":1,"uuid":"u","name":"a","pid":1,"ppid":1,
676          "started_at":"t","binary_version":"mur-agent-runtime 2.26.9",
677          "transports":{"stdio":true},"card_digest":"d","capabilities":[]}"#;
678        let lock: LockFile = serde_json::from_str(old).unwrap();
679        assert_eq!(lock.build_sha, "");
680        assert_eq!(lock.proto_version, 0);
681    }
682}