iron-core 0.1.34

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
//! Host scheduler abstraction, installation context, and platform factory.
//!
//! The `HostScheduler` trait defines the operations each platform adapter
//! implements: install, remove, list, and inspect owned entries. The
//! `SchedulerInstallContext` supplies the trusted runner executable and
//! ConfigStore path used to generate fixed `agent-iron run` invocations.
//!
//! Callers never provide executables, arguments, shell text, or environment
//! variables — the installed command is always core-derived.

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

use super::cron::CronExpression;
use super::HostRunMetadata;

/// Render structured program arguments as a shell-safe command string.
///
/// Each argument is single-quoted if it contains characters that are
/// special to the shell. This is used for cron entries (which run via
/// `/bin/sh -c`) and for comparing expected vs observed commands.
pub fn render_command(program: &std::path::Path, args: &[String]) -> String {
    let mut parts = vec![shell_quote(&program.display().to_string())];
    for arg in args {
        parts.push(shell_quote(arg));
    }
    parts.join(" ")
}

/// Render a command string for cron entries, escaping the `%` metacharacter.
///
/// Cron processes unescaped `%` as a newline **before** invoking `/bin/sh`,
/// so single-quote protection alone is insufficient. The `\%` escape is
/// recognised by cron (which strips the backslash) regardless of shell
/// quoting context, so it is safe both inside and outside single quotes.
pub fn render_cron_command(program: &std::path::Path, args: &[String]) -> String {
    render_command(program, args).replace('%', "\\%")
}

/// Quote a string for safe shell usage. If the string contains only
/// "safe" characters (alphanumeric, dash, underscore, slash, dot, colon),
/// it is returned unquoted. Otherwise it is single-quoted with embedded
/// single-quotes escaped.
fn shell_quote(s: &str) -> String {
    if s.is_empty() {
        return "''".to_string();
    }
    if s.chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/' | '.' | ':' | '='))
    {
        return s.to_string();
    }
    format!("'{}'", s.replace('\'', "'\"'\"'"))
}

// ============================================================================
// Installation context
// ============================================================================

/// Trusted installation context for generating host scheduler entries.
///
/// Supplied by the embedding application (e.g. the desktop app). Core does
/// not assume `current_exe()` is the runner.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchedulerInstallContext {
    /// Absolute path to the `agent-iron` binary.
    pub runner_executable: PathBuf,
    /// Absolute path to the ConfigStore database.
    pub config_store_path: PathBuf,
}

impl SchedulerInstallContext {
    /// Generate the structured program invocation for a scheduled task.
    ///
    /// Returns the runner executable path and argument list for
    /// `agent-iron run <task-id> --config <path>` with absolute paths and
    /// no reliance on `PATH`, process working directory, or environment
    /// variables.
    pub fn generate_invocation(&self, automation_task_id: &str) -> (PathBuf, Vec<String>) {
        (
            self.runner_executable.clone(),
            vec![
                "run".to_string(),
                automation_task_id.to_string(),
                "--config".to_string(),
                self.config_store_path.display().to_string(),
            ],
        )
    }
}

// ============================================================================
// Request and observed types
// ============================================================================

/// A core-generated request to install or replace a host scheduler entry.
///
/// All fields are derived by core from the desired ConfigStore state and the
/// trusted installation context. The host adapter never receives arbitrary
/// caller-provided command content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostInstallRequest {
    /// Stable schedule ID used for ownership.
    pub schedule_id: String,
    /// The automation task being scheduled.
    pub automation_task_id: String,
    /// Parsed cron expression to compile into native triggers.
    pub cron: CronExpression,
    /// Whether the entry should be enabled or disabled.
    pub enabled: bool,
    /// Core-generated runner executable path.
    pub program: PathBuf,
    /// Core-generated runner arguments.
    pub args: Vec<String>,
}

/// An observed host scheduler entry belonging to AgentIron.
#[derive(Debug, Clone, PartialEq)]
pub struct ObservedHostEntry {
    /// Schedule ID extracted from ownership markers.
    pub schedule_id: String,
    /// Whether the entry is currently enabled.
    pub enabled: bool,
    /// Whether the entry appears corrupt or malformed.
    pub corrupt: bool,
    /// The observed raw schedule text, if parseable.
    pub raw_schedule: Option<String>,
    /// The observed command, if extractable.
    pub observed_command: Option<String>,
    /// Optional host-reported run metadata.
    pub metadata: Option<HostRunMetadata>,
}

// ============================================================================
// Errors
// ============================================================================

/// Errors from host scheduler operations.
#[derive(Debug, Clone, thiserror::Error)]
pub enum HostSchedulerError {
    /// The platform does not support the requested schedule.
    #[error("unsupported schedule for {platform}: {reason}")]
    UnsupportedSchedule {
        platform: &'static str,
        reason: String,
    },

    /// The host scheduler service is unavailable.
    #[error("platform unavailable: {0}")]
    PlatformUnavailable(String),

    /// A command or filesystem operation failed.
    #[error("io error: {0}")]
    Io(String),

    /// The cron expression cannot be faithfully compiled.
    #[error("compilation failed: {0}")]
    CompilationFailed(String),
}

// ============================================================================
// HostScheduler trait
// ============================================================================

/// Platform-specific host scheduler operations.
///
/// Each adapter manages only AgentIron-owned entries identified by
/// platform-specific ownership markers. Non-owned entries are never
/// mutated.
#[async_trait]
pub trait HostScheduler: Send + Sync {
    /// The platform name (e.g. "cron", "launchd", "task-scheduler").
    fn platform(&self) -> &'static str;

    /// Install or replace an owned host entry.
    ///
    /// If an owned entry for the same schedule ID already exists, it is
    /// replaced atomically. Disabled requests install a disabled entry
    /// rather than skipping installation.
    async fn install(&self, request: &HostInstallRequest) -> Result<(), HostSchedulerError>;

    /// Remove an owned host entry by schedule ID.
    ///
    /// Returns `Ok(())` if the entry did not exist.
    async fn remove(&self, schedule_id: &str) -> Result<(), HostSchedulerError>;

    /// List all AgentIron-owned host entries.
    async fn list_owned(&self) -> Result<Vec<ObservedHostEntry>, HostSchedulerError>;

    /// Inspect a single owned host entry by schedule ID.
    ///
    /// Returns `Ok(None)` if no owned entry exists for the given ID.
    async fn inspect(
        &self,
        schedule_id: &str,
    ) -> Result<Option<ObservedHostEntry>, HostSchedulerError>;
}

// ============================================================================
// Factory
// ============================================================================

/// Create the platform-appropriate host scheduler.
///
/// Returns `Err(PlatformUnavailable)` on unsupported targets.
pub fn create_host_scheduler(
    _context: SchedulerInstallContext,
) -> Result<Box<dyn HostScheduler>, HostSchedulerError> {
    cfg_if::cfg_if! {
        if #[cfg(target_os = "linux")] {
            use super::platform::cron_adapter::CronHostScheduler;
            Ok(Box::new(CronHostScheduler::new(Box::new(ProductionCommandRunner))))
        } else if #[cfg(target_os = "macos")] {
            use super::platform::launchd::LaunchdHostScheduler;
            use std::path::PathBuf;
            let home = std::env::var("HOME")
                .map_err(|_| HostSchedulerError::PlatformUnavailable(
                    "HOME environment variable is not set; cannot locate LaunchAgents directory".to_string(),
                ))?;
            if home.is_empty() {
                return Err(HostSchedulerError::PlatformUnavailable(
                    "HOME environment variable is empty; cannot locate LaunchAgents directory".to_string(),
                ));
            }
            let dir = PathBuf::from(&home).join("Library/LaunchAgents");
            if !dir.is_absolute() {
                return Err(HostSchedulerError::PlatformUnavailable(
                    format!("resolved LaunchAgents path is not absolute: {}", dir.display()),
                ));
            }
            Ok(Box::new(LaunchdHostScheduler::new(Box::new(ProductionCommandRunner), dir)))
        } else if #[cfg(target_os = "windows")] {
            use super::platform::task_scheduler::TaskSchedulerHostScheduler;
            Ok(Box::new(TaskSchedulerHostScheduler::new(Box::new(ProductionCommandRunner))))
        } else {
            Err(HostSchedulerError::PlatformUnavailable(
                "unsupported platform".to_string(),
            ))
        }
    }
}

/// Production command runner using `tokio::process::Command`.
pub struct ProductionCommandRunner;

/// Default timeout for host scheduler commands (30 seconds).
const COMMAND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

#[async_trait]
impl CommandRunner for ProductionCommandRunner {
    async fn run(&self, program: &str, args: &[&str]) -> Result<CommandOutput, std::io::Error> {
        let fut = async {
            let output = tokio::process::Command::new(program)
                .args(args)
                .output()
                .await?;
            Ok(CommandOutput {
                exit_code: output.status.code().unwrap_or(-1),
                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            })
        };
        match tokio::time::timeout(COMMAND_TIMEOUT, fut).await {
            Ok(result) => result,
            Err(_) => Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                format!(
                    "command '{}' timed out after {}s",
                    program,
                    COMMAND_TIMEOUT.as_secs()
                ),
            )),
        }
    }

    async fn run_with_stdin(
        &self,
        program: &str,
        args: &[&str],
        stdin: &str,
    ) -> Result<CommandOutput, std::io::Error> {
        use tokio::io::AsyncWriteExt;
        let stdin_bytes = stdin.as_bytes().to_vec();
        let fut = async {
            let mut child = tokio::process::Command::new(program)
                .args(args)
                .stdin(std::process::Stdio::piped())
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped())
                .spawn()?;
            if let Some(ref mut stdin_handle) = child.stdin {
                stdin_handle.write_all(&stdin_bytes).await?;
            }
            let output = child.wait_with_output().await?;
            Ok(CommandOutput {
                exit_code: output.status.code().unwrap_or(-1),
                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            })
        };
        match tokio::time::timeout(COMMAND_TIMEOUT, fut).await {
            Ok(result) => result,
            Err(_) => Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                format!(
                    "command '{}' timed out after {}s",
                    program,
                    COMMAND_TIMEOUT.as_secs()
                ),
            )),
        }
    }
}

// ============================================================================
// Injectable boundaries for testing
// ============================================================================

/// Injectable command runner for executing host scheduler commands.
#[async_trait]
pub trait CommandRunner: Send + Sync {
    /// Run a program with arguments and return the output.
    async fn run(&self, program: &str, args: &[&str]) -> Result<CommandOutput, std::io::Error>;

    /// Run a program with stdin input and return the output.
    async fn run_with_stdin(
        &self,
        program: &str,
        args: &[&str],
        stdin: &str,
    ) -> Result<CommandOutput, std::io::Error>;
}

/// Output from a command runner invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandOutput {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
}

/// Injectable filesystem boundary.
#[async_trait]
pub trait SchedulerFilesystem: Send + Sync {
    async fn read_to_string(&self, path: &std::path::Path) -> Result<String, std::io::Error>;
    async fn write(&self, path: &std::path::Path, content: &str) -> Result<(), std::io::Error>;
    async fn exists(&self, path: &std::path::Path) -> bool;
    async fn remove_file(&self, path: &std::path::Path) -> Result<(), std::io::Error>;
}

// ============================================================================
// Fake host scheduler for testing
// ============================================================================

/// In-memory fake host scheduler for testing schedule management without
/// touching the real host scheduler.
#[derive(Debug, Default)]
pub struct FakeHostScheduler {
    entries: parking_lot::RwLock<std::collections::HashMap<String, ObservedHostEntry>>,
    /// If set, all operations return this error.
    pub force_error: parking_lot::Mutex<Option<HostSchedulerError>>,
    install_count: std::sync::atomic::AtomicU32,
}

impl FakeHostScheduler {
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of times `install` was called.
    pub fn install_count(&self) -> u32 {
        self.install_count
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    fn check_error(&self) -> Result<(), HostSchedulerError> {
        if let Some(ref e) = *self.force_error.lock() {
            return Err(e.clone());
        }
        Ok(())
    }
}

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

    async fn install(&self, request: &HostInstallRequest) -> Result<(), HostSchedulerError> {
        self.check_error()?;
        self.install_count
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let command = render_command(&request.program, &request.args);
        let mut entries = self.entries.write();
        entries.insert(
            request.schedule_id.clone(),
            ObservedHostEntry {
                schedule_id: request.schedule_id.clone(),
                enabled: request.enabled,
                corrupt: false,
                raw_schedule: Some(request.cron.as_str().to_string()),
                observed_command: Some(command),
                metadata: None,
            },
        );
        Ok(())
    }

    async fn remove(&self, schedule_id: &str) -> Result<(), HostSchedulerError> {
        self.check_error()?;
        let mut entries = self.entries.write();
        entries.remove(schedule_id);
        Ok(())
    }

    async fn list_owned(&self) -> Result<Vec<ObservedHostEntry>, HostSchedulerError> {
        self.check_error()?;
        let entries = self.entries.read();
        let mut list: Vec<_> = entries.values().cloned().collect();
        list.sort_by(|a, b| a.schedule_id.cmp(&b.schedule_id));
        Ok(list)
    }

    async fn inspect(
        &self,
        schedule_id: &str,
    ) -> Result<Option<ObservedHostEntry>, HostSchedulerError> {
        self.check_error()?;
        let entries = self.entries.read();
        Ok(entries.get(schedule_id).cloned())
    }
}

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

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

    fn test_context() -> SchedulerInstallContext {
        SchedulerInstallContext {
            runner_executable: PathBuf::from("/usr/local/bin/agent-iron"),
            config_store_path: PathBuf::from("/home/user/.config/agentiron/config.db"),
        }
    }

    fn make_request(id: &str, cron: &str, enabled: bool) -> HostInstallRequest {
        let ctx = test_context();
        let (program, args) = ctx.generate_invocation("task-1");
        HostInstallRequest {
            schedule_id: id.to_string(),
            automation_task_id: "task-1".to_string(),
            cron: CronExpression::parse(cron).unwrap(),
            enabled,
            program,
            args,
        }
    }

    #[test]
    fn generate_invocation_uses_absolute_paths() {
        let ctx = test_context();
        let (program, args) = ctx.generate_invocation("daily-report");
        assert!(program.starts_with("/usr/local/bin/agent-iron"));
        assert!(args.contains(&"run".to_string()));
        assert!(args.contains(&"daily-report".to_string()));
        assert!(args.contains(&"--config".to_string()));
    }

    #[test]
    fn generate_invocation_no_path_reliance() {
        let ctx = test_context();
        let (program, _) = ctx.generate_invocation("task-1");
        assert!(!program.starts_with("agent-iron"));
        assert!(program.is_absolute());
    }

    #[test]
    fn factory_returns_scheduler_on_supported_platform() {
        let ctx = test_context();
        let result = create_host_scheduler(ctx);
        cfg_if::cfg_if! {
            if #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] {
                assert!(result.is_ok());
            } else {
                assert!(matches!(result, Err(HostSchedulerError::PlatformUnavailable(_))));
            }
        }
    }

    #[tokio::test]
    async fn fake_install_and_inspect() {
        let scheduler = FakeHostScheduler::new();
        let request = make_request("s1", "0 9 * * *", true);
        scheduler.install(&request).await.unwrap();

        let entry = scheduler.inspect("s1").await.unwrap().unwrap();
        assert_eq!(entry.schedule_id, "s1");
        assert!(entry.enabled);
        assert_eq!(entry.raw_schedule.as_deref(), Some("0 9 * * *"));
    }

    #[tokio::test]
    async fn fake_remove() {
        let scheduler = FakeHostScheduler::new();
        scheduler
            .install(&make_request("s1", "0 9 * * *", true))
            .await
            .unwrap();
        scheduler.remove("s1").await.unwrap();
        assert!(scheduler.inspect("s1").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn fake_list_owned_sorted() {
        let scheduler = FakeHostScheduler::new();
        for id in &["charlie", "alpha", "bravo"] {
            scheduler
                .install(&make_request(id, "0 9 * * *", true))
                .await
                .unwrap();
        }
        let list = scheduler.list_owned().await.unwrap();
        let ids: Vec<&str> = list.iter().map(|e| e.schedule_id.as_str()).collect();
        assert_eq!(ids, vec!["alpha", "bravo", "charlie"]);
    }

    #[tokio::test]
    async fn fake_replace_on_reinstall() {
        let scheduler = FakeHostScheduler::new();
        scheduler
            .install(&make_request("s1", "0 9 * * *", true))
            .await
            .unwrap();
        scheduler
            .install(&make_request("s1", "0 9 * * *", false))
            .await
            .unwrap();
        let entry = scheduler.inspect("s1").await.unwrap().unwrap();
        assert!(!entry.enabled);
    }

    #[tokio::test]
    async fn fake_install_request_has_no_arbitrary_command() {
        let _scheduler = FakeHostScheduler::new();
        let request = make_request("s1", "0 9 * * *", true);
        assert!(request.program.is_absolute());
        assert!(request.args.contains(&"run".to_string()));
        assert!(request.args.contains(&"task-1".to_string()));
    }

    #[tokio::test]
    async fn fake_force_error() {
        let scheduler = FakeHostScheduler::new();
        *scheduler.force_error.lock() =
            Some(HostSchedulerError::PlatformUnavailable("test".to_string()));
        let result = scheduler.list_owned().await;
        assert!(matches!(
            result,
            Err(HostSchedulerError::PlatformUnavailable(_))
        ));
    }

    #[test]
    fn shell_quote_safe_chars() {
        assert_eq!(shell_quote("hello"), "hello");
        assert_eq!(shell_quote("/usr/bin/agent-iron"), "/usr/bin/agent-iron");
        assert_eq!(shell_quote("a-b_c.d"), "a-b_c.d");
    }

    #[test]
    fn shell_quote_unsafe_chars() {
        assert_eq!(shell_quote(""), "''");
        assert_eq!(shell_quote("hello world"), "'hello world'");
        assert_eq!(
            shell_quote("/path with spaces/run"),
            "'/path with spaces/run'"
        );
    }
}