iron-core 0.1.35

Core AgentIron loop, session state, and tool registry
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! macOS launchd host scheduler adapter.
//!
//! Manages user-level LaunchAgent plists with `com.agentiron.task.` labels.
//! Cron expressions are expanded into launchd `StartCalendarInterval`
//! entries. plist files live in `~/Library/LaunchAgents/`.
//!
//! The plist rendering and cron expansion logic is platform-independent
//! and tested here. The actual `launchctl` command execution is Linux
//! unavailable but the adapter is designed for correctness on macOS.

use async_trait::async_trait;
use std::path::PathBuf;

use crate::scheduled_task::cron::CronExpression;
use crate::scheduled_task::host::{
    CommandRunner, HostInstallRequest, HostScheduler, HostSchedulerError, ObservedHostEntry,
};

/// Escape XML special characters.
fn escape_xml(s: &str) -> String {
    s.replace('&', "&")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// Reverse the entity escaping applied by [`escape_xml`].
fn unescape_xml(s: &str) -> String {
    s.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&amp;", "&")
}

/// Label prefix for AgentIron launchd entries.
pub const LABEL_PREFIX: &str = "com.agentiron.task.";

/// Maximum number of StartCalendarInterval entries before rejecting.
/// Prevents combinatorial explosion from complex cron expressions.
pub const MAX_INTERVALS: usize = 64;

// ============================================================================
// Cron to StartCalendarInterval expansion
// ============================================================================

/// A single launchd calendar interval.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CalendarInterval {
    pub minute: Option<u32>,
    pub hour: Option<u32>,
    pub day_of_month: Option<u32>,
    pub month: Option<u32>,
    pub day_of_week: Option<u32>,
}

/// Expand a parsed cron expression into launchd calendar intervals.
///
/// Returns `Err` if the expansion would exceed `MAX_INTERVALS` entries or
/// if the expression cannot be faithfully represented.
pub fn expand_cron(cron: &CronExpression) -> Result<Vec<CalendarInterval>, String> {
    let minutes = cron.minutes();
    let hours = cron.hours();
    let doms = cron.days_of_month();
    let months = cron.months();
    let dows = cron.days_of_week();

    let dom_restricted = doms.len() < 31;
    let dow_restricted = dows.len() < 7;
    let month_restricted = months.len() < 12;

    // Wildcard minute/hour fields produce None (match any).
    let minute_vals: Vec<Option<u32>> = if minutes.len() < 60 {
        minutes.iter().copied().map(Some).collect()
    } else {
        vec![None]
    };
    let hour_vals: Vec<Option<u32>> = if hours.len() < 24 {
        hours.iter().copied().map(Some).collect()
    } else {
        vec![None]
    };
    let month_vals: Vec<Option<u32>> = if month_restricted {
        months.iter().copied().map(Some).collect()
    } else {
        vec![None]
    };

    let mut intervals = Vec::new();

    /// Push an interval, aborting early if MAX_INTERVALS would be exceeded.
    macro_rules! push_interval {
        ($intervals:expr, $val:expr) => {
            if $intervals.len() >= MAX_INTERVALS {
                return Err(format!(
                    "cron expression expands to more than {} launchd intervals; \
                     use a simpler expression",
                    MAX_INTERVALS
                ));
            }
            $intervals.push($val);
        };
    }

    if dom_restricted && dow_restricted {
        // Cron DOM-or-DOW: fire when either matches.
        // Set 1: specific DOM, DOW wildcard.
        for &m_val in &minute_vals {
            for &h_val in &hour_vals {
                for &dom in doms {
                    for &mo in &month_vals {
                        push_interval!(
                            intervals,
                            CalendarInterval {
                                minute: m_val,
                                hour: h_val,
                                day_of_month: Some(dom),
                                month: mo,
                                day_of_week: None,
                            }
                        );
                    }
                }
            }
        }
        // Set 2: DOM wildcard, specific DOW.
        for &m_val in &minute_vals {
            for &h_val in &hour_vals {
                for &dow in dows {
                    for &mo in &month_vals {
                        push_interval!(
                            intervals,
                            CalendarInterval {
                                minute: m_val,
                                hour: h_val,
                                day_of_month: None,
                                month: mo,
                                day_of_week: Some(if dow == 0 { 7 } else { dow }),
                            }
                        );
                    }
                }
            }
        }
    } else {
        // Simple case: iterate only over restricted fields.
        let dom_vals: Vec<Option<u32>> = if dom_restricted {
            doms.iter().copied().map(Some).collect()
        } else {
            vec![None]
        };
        let dow_vals: Vec<Option<u32>> = if dow_restricted {
            dows.iter()
                .copied()
                .map(|d| Some(if d == 0 { 7 } else { d }))
                .collect()
        } else {
            vec![None]
        };

        for &m_val in &minute_vals {
            for &h_val in &hour_vals {
                for &dom in &dom_vals {
                    for &mo in &month_vals {
                        for &dow in &dow_vals {
                            push_interval!(
                                intervals,
                                CalendarInterval {
                                    minute: m_val,
                                    hour: h_val,
                                    day_of_month: dom,
                                    month: mo,
                                    day_of_week: dow,
                                }
                            );
                        }
                    }
                }
            }
        }
    }

    intervals.sort_by_key(|i| (i.minute, i.hour, i.day_of_month, i.month, i.day_of_week));
    intervals.dedup();

    if intervals.len() > MAX_INTERVALS {
        return Err(format!(
            "cron expression expands to {} launchd intervals (max {}); \
             use a simpler expression",
            intervals.len(),
            MAX_INTERVALS
        ));
    }

    Ok(intervals)
}

// ============================================================================
// Plist rendering
// ============================================================================

/// Render a complete LaunchAgent plist for the given parameters.
pub fn render_plist(
    schedule_id: &str,
    intervals: &[CalendarInterval],
    program_args: &[String],
    disabled: bool,
) -> String {
    let label = format!("{}{}", LABEL_PREFIX, escape_xml(schedule_id));

    let mut xml = String::new();
    xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    xml.push_str("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n");
    xml.push_str("<plist version=\"1.0\">\n");
    xml.push_str("<dict>\n");

    xml.push_str(&format!(
        "    <key>Label</key>\n    <string>{}</string>\n",
        label
    ));

    if disabled {
        xml.push_str("    <key>Disabled</key>\n    <true/>\n");
    }

    xml.push_str("    <key>ProgramArguments</key>\n    <array>\n");
    for arg in program_args {
        xml.push_str(&format!("        <string>{}</string>\n", escape_xml(arg)));
    }
    xml.push_str("    </array>\n");

    xml.push_str("    <key>StartCalendarInterval</key>\n");
    if intervals.len() == 1 {
        xml.push_str("    <dict>\n");
        push_interval_keys(&mut xml, &intervals[0], "        ");
        xml.push_str("    </dict>\n");
    } else {
        xml.push_str("    <array>\n");
        for interval in intervals {
            xml.push_str("        <dict>\n");
            push_interval_keys(&mut xml, interval, "            ");
            xml.push_str("        </dict>\n");
        }
        xml.push_str("    </array>\n");
    }

    xml.push_str("</dict>\n");
    xml.push_str("</plist>\n");
    xml
}

fn push_interval_keys(xml: &mut String, interval: &CalendarInterval, indent: &str) {
    if let Some(m) = interval.minute {
        xml.push_str(&format!(
            "{}<key>Minute</key>\n{}<integer>{}</integer>\n",
            indent, indent, m
        ));
    }
    if let Some(h) = interval.hour {
        xml.push_str(&format!(
            "{}<key>Hour</key>\n{}<integer>{}</integer>\n",
            indent, indent, h
        ));
    }
    if let Some(d) = interval.day_of_month {
        xml.push_str(&format!(
            "{}<key>Day</key>\n{}<integer>{}</integer>\n",
            indent, indent, d
        ));
    }
    if let Some(mo) = interval.month {
        xml.push_str(&format!(
            "{}<key>Month</key>\n{}<integer>{}</integer>\n",
            indent, indent, mo
        ));
    }
    if let Some(dow) = interval.day_of_week {
        xml.push_str(&format!(
            "{}<key>Weekday</key>\n{}<integer>{}</integer>\n",
            indent, indent, dow
        ));
    }
}

/// Extract the `<string>` values inside a plist's `ProgramArguments` array.
///
/// Returns an empty vector if the key or array cannot be located.
/// String values are XML-decoded so escaped paths and arguments match
/// their actual values.
fn parse_program_arguments(text: &str) -> Vec<String> {
    let key = "<key>ProgramArguments</key>";
    let key_pos = match text.find(key) {
        Some(p) => p + key.len(),
        None => return Vec::new(),
    };
    let after_key = &text[key_pos..];
    let array_open = match after_key.find("<array>") {
        Some(p) => key_pos + p + "<array>".len(),
        None => return Vec::new(),
    };
    let array_close = match text[array_open..].find("</array>") {
        Some(p) => array_open + p,
        None => return Vec::new(),
    };
    let body = &text[array_open..array_close];

    let mut args = Vec::new();
    let mut cursor = body;
    while let Some(open) = cursor.find("<string>") {
        let value_start = open + "<string>".len();
        let rest = &cursor[value_start..];
        let close = match rest.find("</string>") {
            Some(p) => p,
            None => break,
        };
        args.push(unescape_xml(&rest[..close]));
        cursor = &rest[close + "</string>".len()..];
    }
    args
}

// ============================================================================
// Adapter
// ============================================================================

/// macOS launchd host scheduler.
pub struct LaunchdHostScheduler {
    runner: Box<dyn CommandRunner>,
    launchagents_dir: PathBuf,
    uid: u32,
}

impl LaunchdHostScheduler {
    pub fn new(runner: Box<dyn CommandRunner>, launchagents_dir: PathBuf) -> Self {
        let uid = extern_uid();
        Self {
            runner,
            launchagents_dir,
            uid,
        }
    }

    fn plist_path(&self, schedule_id: &str) -> PathBuf {
        self.launchagents_dir
            .join(format!("{}{}.plist", LABEL_PREFIX, schedule_id))
    }

    fn domain_target(&self) -> String {
        format!("gui/{}", self.uid)
    }

    fn service_target(&self, schedule_id: &str) -> String {
        format!("{}/{}{}", self.domain_target(), LABEL_PREFIX, schedule_id)
    }

    /// Bootout (unload) the agent if currently loaded.
    ///
    /// Returns `Ok(())` if the agent was successfully unloaded or was not
    /// loaded to begin with. Other failures are propagated.
    async fn bootout_if_loaded(&self, schedule_id: &str) -> Result<(), HostSchedulerError> {
        let target = self.service_target(schedule_id);
        let output = self
            .runner
            .run("launchctl", &["bootout", &target])
            .await
            .map_err(|e| HostSchedulerError::Io(e.to_string()))?;

        if output.exit_code == 0 {
            return Ok(());
        }

        let stderr = output.stderr.to_lowercase();
        if stderr.contains("not loaded")
            || stderr.contains("could not find")
            || stderr.contains("no such process")
        {
            return Ok(());
        }

        Err(HostSchedulerError::Io(format!(
            "launchctl bootout failed (exit {}): {}",
            output.exit_code, output.stderr
        )))
    }

    /// Bootstrap (load) the agent from its plist.
    ///
    /// Returns `Ok(())` if the agent was successfully loaded or was already
    /// loaded. Other failures are propagated.
    async fn bootstrap(&self, schedule_id: &str) -> Result<(), HostSchedulerError> {
        let plist_path = self.plist_path(schedule_id);
        let path_str = plist_path.to_string_lossy().to_string();
        let domain = self.domain_target();

        let output = self
            .runner
            .run("launchctl", &["bootstrap", &domain, &path_str])
            .await
            .map_err(|e| HostSchedulerError::Io(e.to_string()))?;

        if output.exit_code == 0 {
            return Ok(());
        }

        let stderr = output.stderr.to_lowercase();
        if stderr.contains("already loaded") || stderr.contains("already bootstrapped") {
            return Ok(());
        }

        Err(HostSchedulerError::Io(format!(
            "launchctl bootstrap failed: {}",
            output.stderr
        )))
    }

    /// Read and parse a schedule's plist file into an observed entry.
    ///
    /// Returns `Ok(None)` if the plist file is confirmed absent. Returns
    /// `Ok(Some(entry))` with `corrupt: true` if the file exists but is
    /// malformed. Returns `Err` for command execution failures or
    /// non-"not found" errors so reconciliation does not treat
    /// inaccessible state as absence.
    async fn read_plist_entry(
        &self,
        schedule_id: &str,
    ) -> Result<Option<ObservedHostEntry>, HostSchedulerError> {
        let plist_path = self.plist_path(schedule_id);
        let path_str = plist_path.to_string_lossy().to_string();

        let output = self
            .runner
            .run("cat", &[&path_str])
            .await
            .map_err(|e| HostSchedulerError::Io(e.to_string()))?;

        if output.exit_code != 0 {
            let stderr = output.stderr.to_lowercase();
            if stderr.contains("no such file") || stderr.contains("not found") {
                return Ok(None);
            }
            return Err(HostSchedulerError::Io(format!(
                "cat failed (exit {}): {}",
                output.exit_code, output.stderr
            )));
        }

        let text = &output.stdout;
        let expected_label = format!("{}{}", LABEL_PREFIX, schedule_id);

        // Structural validation: require well-formed plist structure.
        let has_plist_open = text.contains("<plist");
        let has_plist_close = text.contains("</plist>");
        let has_dict = text.contains("<dict>") && text.contains("</dict>");

        if !has_plist_open || !has_plist_close || !has_dict {
            return Ok(Some(ObservedHostEntry {
                schedule_id: schedule_id.to_string(),
                enabled: false,
                corrupt: true,
                raw_schedule: None,
                observed_command: None,
                metadata: None,
            }));
        }

        // Validate Label matches expected schedule ID (XML-decoded).
        let label_key = "<key>Label</key>";
        let label_ok = text.find(label_key).is_some_and(|pos| {
            let after = &text[pos + label_key.len()..];
            after.contains(&format!("<string>{}</string>", escape_xml(&expected_label)))
        });

        if !label_ok {
            return Ok(Some(ObservedHostEntry {
                schedule_id: schedule_id.to_string(),
                enabled: false,
                corrupt: true,
                raw_schedule: None,
                observed_command: None,
                metadata: None,
            }));
        }

        // Disabled is true when <true/> is the value following the Disabled key.
        let disabled = text.find("<key>Disabled</key>").map(|pos| {
            let after = &text[pos + "<key>Disabled</key>".len()..];
            match (after.find("<true/>"), after.find("<key>")) {
                (Some(t), Some(k)) => t < k,
                (Some(_), None) => true,
                _ => false,
            }
        });

        // Validate ProgramArguments exists and has at least one string value.
        let command = parse_program_arguments(text).join(" ");
        let has_program_args = text.contains("<key>ProgramArguments</key>") && !command.is_empty();

        if !has_program_args {
            return Ok(Some(ObservedHostEntry {
                schedule_id: schedule_id.to_string(),
                enabled: !disabled.unwrap_or(false),
                corrupt: true,
                raw_schedule: None,
                observed_command: None,
                metadata: None,
            }));
        }

        Ok(Some(ObservedHostEntry {
            schedule_id: schedule_id.to_string(),
            enabled: !disabled.unwrap_or(false),
            corrupt: false,
            raw_schedule: None,
            observed_command: Some(command),
            metadata: None,
        }))
    }
}

/// Get the current process UID without external crate dependencies.
fn extern_uid() -> u32 {
    extern "C" {
        fn getuid() -> u32;
    }
    unsafe { getuid() }
}

#[async_trait]
impl HostScheduler for LaunchdHostScheduler {
    fn platform(&self) -> &'static str {
        "launchd"
    }

    async fn install(&self, request: &HostInstallRequest) -> Result<(), HostSchedulerError> {
        let intervals = expand_cron(&request.cron).map_err(|reason| {
            HostSchedulerError::UnsupportedSchedule {
                platform: "launchd",
                reason,
            }
        })?;

        let mut program_args = vec![request.program.display().to_string()];
        program_args.extend(request.args.iter().cloned());

        let plist_content = render_plist(
            &request.schedule_id,
            &intervals,
            &program_args,
            !request.enabled,
        );

        // Write plist file.
        let plist_path = self.plist_path(&request.schedule_id);
        let path_str = plist_path.to_string_lossy().to_string();

        let output = self
            .runner
            .run_with_stdin("tee", &[&path_str], &plist_content)
            .await
            .map_err(|e| HostSchedulerError::Io(e.to_string()))?;

        if output.exit_code != 0 {
            return Err(HostSchedulerError::Io(format!(
                "failed to write plist: {}",
                output.stderr
            )));
        }

        // Reload: bootout if loaded, then bootstrap.
        self.bootout_if_loaded(&request.schedule_id).await?;
        self.bootstrap(&request.schedule_id).await?;

        // Apply enabled/disabled state via launchctl.
        let target = self.service_target(&request.schedule_id);
        if request.enabled {
            let output = self
                .runner
                .run("launchctl", &["enable", &target])
                .await
                .map_err(|e| HostSchedulerError::Io(e.to_string()))?;
            if output.exit_code != 0 {
                return Err(HostSchedulerError::Io(format!(
                    "launchctl enable failed: {}",
                    output.stderr
                )));
            }
        } else {
            let output = self
                .runner
                .run("launchctl", &["disable", &target])
                .await
                .map_err(|e| HostSchedulerError::Io(e.to_string()))?;
            if output.exit_code != 0 {
                return Err(HostSchedulerError::Io(format!(
                    "launchctl disable failed: {}",
                    output.stderr
                )));
            }
        }

        Ok(())
    }

    async fn remove(&self, schedule_id: &str) -> Result<(), HostSchedulerError> {
        // Unload the agent first.
        self.bootout_if_loaded(schedule_id).await?;

        // Then delete the plist file.
        let plist_path = self.plist_path(schedule_id);
        let path_str = plist_path.to_string_lossy().to_string();

        let output = self
            .runner
            .run("rm", &["-f", &path_str])
            .await
            .map_err(|e| HostSchedulerError::Io(e.to_string()))?;

        if output.exit_code != 0 {
            return Err(HostSchedulerError::Io(format!(
                "failed to remove plist: {}",
                output.stderr
            )));
        }

        Ok(())
    }

    async fn list_owned(&self) -> Result<Vec<ObservedHostEntry>, HostSchedulerError> {
        let dir_str = self.launchagents_dir.to_string_lossy().to_string();
        let output = self
            .runner
            .run("ls", &["-1", &dir_str])
            .await
            .map_err(|e| HostSchedulerError::Io(e.to_string()))?;

        if output.exit_code != 0 {
            return Err(HostSchedulerError::Io(format!(
                "ls failed (exit {}): {}",
                output.exit_code, output.stderr
            )));
        }

        let mut entries = Vec::new();
        for line in output.stdout.lines() {
            if let Some(schedule_id) = line
                .strip_prefix(&format!("{}{}", LABEL_PREFIX, ""))
                .and_then(|s| s.strip_suffix(".plist"))
            {
                if let Some(entry) = self.read_plist_entry(schedule_id).await? {
                    entries.push(entry);
                }
            }
        }
        Ok(entries)
    }

    async fn inspect(
        &self,
        schedule_id: &str,
    ) -> Result<Option<ObservedHostEntry>, HostSchedulerError> {
        self.read_plist_entry(schedule_id).await
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn expand_simple_daily() {
        let cron = CronExpression::parse("0 9 * * *").unwrap();
        let intervals = expand_cron(&cron).unwrap();
        assert_eq!(intervals.len(), 1);
        assert_eq!(intervals[0].minute, Some(0));
        assert_eq!(intervals[0].hour, Some(9));
    }

    #[test]
    fn expand_every_15_minutes() {
        let cron = CronExpression::parse("*/15 * * * *").unwrap();
        let intervals = expand_cron(&cron).unwrap();
        assert_eq!(intervals.len(), 4);
        assert_eq!(intervals[0].minute, Some(0));
        assert_eq!(intervals[1].minute, Some(15));
    }

    #[test]
    fn expand_weekdays() {
        let cron = CronExpression::parse("0 9 * * 1-5").unwrap();
        let intervals = expand_cron(&cron).unwrap();
        assert!(intervals.len() >= 5);
    }

    #[test]
    fn expand_dom_and_dow_creates_union() {
        let cron = CronExpression::parse("0 9 1 * 1").unwrap();
        let intervals = expand_cron(&cron).unwrap();
        // DOM=1 OR DOW=1 → at least 2 intervals
        assert!(intervals.len() >= 2);
    }

    #[test]
    fn expand_rejects_excessive() {
        // Complex expression that exceeds MAX_INTERVALS (64).
        // 4 minutes × 5 hours × 2 DOM × 2 DOW (DOM-and-DOW union doubles) = ~80+
        let cron = CronExpression::parse("0,15,30,45 9,10,11,12,13 1,15 * 1,2,3,4,5").unwrap();
        let result = expand_cron(&cron);
        assert!(result.is_err());
    }

    #[test]
    fn render_plist_basic() {
        let intervals = vec![CalendarInterval {
            minute: Some(0),
            hour: Some(9),
            day_of_month: None,
            month: None,
            day_of_week: None,
        }];
        let args = vec![
            "/usr/local/bin/agent-iron".to_string(),
            "run".to_string(),
            "task-1".to_string(),
        ];
        let plist = render_plist("s1", &intervals, &args, false);
        assert!(plist.contains("<string>com.agentiron.task.s1</string>"));
        assert!(plist.contains("<key>Minute</key>"));
        assert!(plist.contains("<key>Hour</key>"));
        assert!(plist.contains("<integer>0</integer>"));
        assert!(plist.contains("<integer>9</integer>"));
        assert!(!plist.contains("<key>Disabled</key>"));
    }

    #[test]
    fn render_plist_disabled() {
        let intervals = vec![CalendarInterval {
            minute: Some(30),
            hour: Some(5),
            day_of_month: None,
            month: None,
            day_of_week: None,
        }];
        let args = vec!["/agent-iron".to_string(), "run".to_string()];
        let plist = render_plist("s1", &intervals, &args, true);
        assert!(plist.contains("<key>Disabled</key>"));
        assert!(plist.contains("<true/>"));
    }

    #[test]
    fn render_plist_multiple_intervals() {
        let intervals = vec![
            CalendarInterval {
                minute: Some(0),
                hour: Some(9),
                day_of_month: None,
                month: None,
                day_of_week: None,
            },
            CalendarInterval {
                minute: Some(0),
                hour: Some(17),
                day_of_month: None,
                month: None,
                day_of_week: None,
            },
        ];
        let args = vec!["/agent-iron".to_string()];
        let plist = render_plist("s1", &intervals, &args, false);
        assert!(plist.contains("<array>"));
    }
}