pulpod 0.1.0

Pulpo daemon — manages agent sessions via tmux/Docker
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
#[cfg(not(coverage))]
use std::time::Duration;

use chrono::{DateTime, Local};
use cron::Schedule as CronSchedule;
#[cfg(not(coverage))]
use pulpo_common::api::CreateSessionRequest;
use pulpo_common::api::Schedule;
#[cfg(not(coverage))]
use pulpo_common::event::PulpoEvent;
#[cfg(not(coverage))]
use tokio::sync::{broadcast, watch};
#[cfg(not(coverage))]
use tracing::{debug, info, warn};

#[cfg(not(coverage))]
use crate::session::manager::SessionManager;
#[cfg(not(coverage))]
use crate::store::Store;

/// Normalize a cron expression to the 7-field format expected by the `cron` crate.
/// Accepts standard 5-field (`min hour dom month dow`) and prepends `0` for seconds
/// and appends `*` for year. Also accepts 6-field (with seconds) and 7-field (full).
fn normalize_cron(expr: &str) -> String {
    let field_count = expr.split_whitespace().count();
    match field_count {
        5 => format!("0 {expr} *"),
        6 => format!("{expr} *"),
        _ => expr.to_owned(),
    }
}

/// Validate a cron expression. Returns an error message if invalid.
/// Accepts standard 5-field cron expressions (e.g., `0 3 * * *`).
pub fn validate_cron(expr: &str) -> Result<(), String> {
    normalize_cron(expr)
        .parse::<CronSchedule>()
        .map(|_| ())
        .map_err(|e| format!("invalid cron expression: {e}"))
}

/// Check if a schedule is due to fire now.
/// Cron expressions are evaluated in the daemon's local timezone (matching
/// conventional crontab behavior). The reference time (`last_run_at` or
/// `created_at`) is converted to local time before computing the next fire.
#[cfg_attr(coverage, allow(dead_code))]
fn is_due(schedule: &Schedule) -> bool {
    is_due_at(schedule, Local::now())
}

#[cfg_attr(coverage, allow(dead_code))]
fn is_due_at(schedule: &Schedule, now: DateTime<Local>) -> bool {
    let Ok(cron) = normalize_cron(&schedule.cron).parse::<CronSchedule>() else {
        return false;
    };

    // Parse the reference time and convert to local timezone so that cron
    // fields (hour, minute, etc.) match the daemon machine's wall clock.
    let reference_time = schedule
        .last_run_at
        .as_ref()
        .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
        .map_or_else(
            || {
                chrono::DateTime::parse_from_rfc3339(&schedule.created_at)
                    .map_or_else(|_| now, |dt| dt.with_timezone(&Local))
            },
            |dt| dt.with_timezone(&Local),
        );

    // Get the next fire time after the reference, in local time
    cron.after(&reference_time)
        .next()
        .is_some_and(|next| next <= now)
}

/// Run the scheduler loop. Ticks every 60 seconds and fires due schedules.
#[cfg(not(coverage))]
pub async fn run_scheduler_loop(
    session_manager: SessionManager,
    store: Store,
    event_tx: Option<broadcast::Sender<PulpoEvent>>,
    mut shutdown_rx: watch::Receiver<bool>,
) {
    let mut tick = tokio::time::interval(Duration::from_secs(60));
    tick.tick().await; // first tick completes immediately

    loop {
        tokio::select! {
            _ = tick.tick() => {
                fire_due_schedules(&session_manager, &store, event_tx.as_ref()).await;
            }
            _ = shutdown_rx.changed() => {
                info!("Scheduler shutting down");
                break;
            }
        }
    }
}

#[cfg(not(coverage))]
async fn fire_due_schedules(
    session_manager: &SessionManager,
    store: &Store,
    _event_tx: Option<&broadcast::Sender<PulpoEvent>>,
) {
    let schedules = match store.list_schedules().await {
        Ok(s) => s,
        Err(e) => {
            warn!("Scheduler: failed to list schedules: {e}");
            return;
        }
    };

    for schedule in schedules {
        if !schedule.enabled {
            continue;
        }
        if !is_due(&schedule) {
            continue;
        }

        debug!(schedule_name = %schedule.name, "Schedule is due, firing");

        // Build session name from schedule name + timestamp suffix
        let session_name = format!("{}-{}", schedule.name, Local::now().format("%Y%m%d-%H%M"));

        let runtime = schedule.runtime.as_deref().map(|r| {
            r.parse::<pulpo_common::session::Runtime>().unwrap_or_else(|_| {
                warn!(schedule_name = %schedule.name, runtime = r, "Unknown runtime, falling back to tmux");
                pulpo_common::session::Runtime::Tmux
            })
        });

        let secrets = if schedule.secrets.is_empty() {
            None
        } else {
            Some(schedule.secrets.clone())
        };

        let req = CreateSessionRequest {
            name: session_name,
            workdir: Some(schedule.workdir.clone()),
            command: if schedule.command.is_empty() {
                None
            } else {
                Some(schedule.command.clone())
            },
            description: schedule.description.clone(),
            metadata: None,
            idle_threshold_secs: None,
            worktree: schedule.worktree,
            worktree_base: schedule.worktree_base.clone(),
            runtime,
            secrets,
            term_program: None,
            budget_cost_usd: schedule.budget_cost_usd,
        };

        let result = session_manager.create_session(req).await;

        match result {
            Ok(session) => {
                info!(
                    schedule_name = %schedule.name,
                    session_name = %session.name,
                    session_id = %session.id,
                    "Schedule fired successfully"
                );
                if let Err(e) = store
                    .update_schedule_last_run(&schedule.id, &session.id.to_string())
                    .await
                {
                    warn!(
                        schedule_name = %schedule.name,
                        "Failed to update schedule last_run: {e}"
                    );
                }
            }
            Err(e) => {
                warn!(
                    schedule_name = %schedule.name,
                    "Schedule fire failed: {e}"
                );
                if let Err(err) = store
                    .record_schedule_failure(&schedule.id, &e.to_string())
                    .await
                {
                    warn!(
                        schedule_name = %schedule.name,
                        "Failed to record schedule failure: {err}"
                    );
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Duration as ChronoDuration, TimeZone, Utc};

    #[test]
    fn test_normalize_cron_5_fields() {
        assert_eq!(normalize_cron("0 3 * * *"), "0 0 3 * * * *");
    }

    #[test]
    fn test_normalize_cron_6_fields() {
        assert_eq!(normalize_cron("0 0 3 * * *"), "0 0 3 * * * *");
    }

    #[test]
    fn test_normalize_cron_7_fields() {
        assert_eq!(normalize_cron("0 0 3 * * * *"), "0 0 3 * * * *");
    }

    #[test]
    fn test_validate_cron_valid() {
        assert!(validate_cron("0 3 * * *").is_ok());
        assert!(validate_cron("*/5 * * * *").is_ok());
        assert!(validate_cron("0 0 * * SUN").is_ok());
    }

    #[test]
    fn test_validate_cron_invalid() {
        assert!(validate_cron("not a cron").is_err());
        assert!(validate_cron("").is_err());
    }

    #[test]
    fn test_is_due_never_run() {
        // Schedule created 2 hours ago with "every minute" cron — should be due
        let now_local = Local.timestamp_opt(1_700_000_100, 0).single().unwrap();
        let schedule = Schedule {
            id: "s1".into(),
            name: "test".into(),
            cron: "* * * * *".into(),
            command: "echo".into(),
            workdir: "/tmp".into(),
            ink: None,
            description: None,
            runtime: None,
            secrets: vec![],
            worktree: None,
            worktree_base: None,
            budget_cost_usd: None,
            enabled: true,
            last_run_at: None,
            last_session_id: None,
            last_attempted_at: None,
            last_error: None,
            created_at: (now_local - ChronoDuration::hours(2))
                .with_timezone(&Utc)
                .to_rfc3339(),
        };
        assert!(is_due_at(&schedule, now_local));
    }

    #[cfg(not(coverage))]
    fn due_schedule(id: &str, name: &str, workdir: &str) -> Schedule {
        Schedule {
            id: id.into(),
            name: name.into(),
            cron: "* * * * *".into(),
            command: "echo hi".into(),
            workdir: workdir.into(),
            ink: None,
            description: None,
            runtime: None,
            secrets: vec![],
            worktree: None,
            worktree_base: None,
            budget_cost_usd: None,
            enabled: true,
            last_run_at: None,
            last_session_id: None,
            last_attempted_at: None,
            last_error: None,
            created_at: (Utc::now() - ChronoDuration::hours(2)).to_rfc3339(),
        }
    }

    #[cfg(not(coverage))]
    async fn scheduler_test_manager()
    -> (crate::session::manager::SessionManager, crate::store::Store) {
        let tmp = Box::leak(Box::new(tempfile::tempdir().unwrap()));
        let store = crate::store::Store::new(tmp.path().to_str().unwrap())
            .await
            .unwrap();
        store.migrate().await.unwrap();
        let manager = crate::session::manager::SessionManager::new(
            std::sync::Arc::new(crate::backend::StubBackend),
            store.clone(),
            None,
        )
        .with_no_stale_grace();
        (manager, store)
    }

    #[cfg(not(coverage))]
    #[tokio::test]
    async fn test_fire_due_schedules_creates_session_and_records_last_run() {
        let (manager, store) = scheduler_test_manager().await;
        store
            .insert_schedule(&due_schedule("sched-1", "nightly", "/tmp"))
            .await
            .unwrap();

        fire_due_schedules(&manager, &store, None).await;

        // A session was created from the due schedule.
        let sessions = store.list_sessions().await.unwrap();
        assert_eq!(sessions.len(), 1);
        assert!(sessions[0].name.starts_with("nightly-"));
        assert_eq!(sessions[0].command, "echo hi");

        // last_run was recorded on the schedule.
        let after = store.get_schedule("sched-1").await.unwrap().unwrap();
        assert!(after.last_session_id.is_some());
    }

    #[cfg(not(coverage))]
    #[tokio::test]
    async fn test_fire_due_schedules_passes_budget_cost_usd_to_session() {
        let (manager, store) = scheduler_test_manager().await;
        let mut schedule = due_schedule("sched-budget", "nightly-budget", "/tmp");
        schedule.budget_cost_usd = Some(3.5);
        store.insert_schedule(&schedule).await.unwrap();

        fire_due_schedules(&manager, &store, None).await;

        let sessions = store.list_sessions().await.unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(
            sessions[0].meta_str(pulpo_common::session::meta::BUDGET_COST_USD),
            Some("3.5")
        );
    }

    #[cfg(not(coverage))]
    #[tokio::test]
    async fn test_fire_due_schedules_records_failure_on_bad_workdir() {
        let (manager, store) = scheduler_test_manager().await;
        // A non-existent workdir makes session creation fail (validate_workdir).
        store
            .insert_schedule(&due_schedule("sched-2", "broken", "/no/such/dir-xyz"))
            .await
            .unwrap();

        fire_due_schedules(&manager, &store, None).await;

        assert!(store.list_sessions().await.unwrap().is_empty());
        let after = store.get_schedule("sched-2").await.unwrap().unwrap();
        assert!(after.last_error.is_some(), "failure should be recorded");
        assert!(after.last_session_id.is_none());
    }

    #[test]
    fn test_is_due_recently_run() {
        // Last run 10 seconds ago with "every hour" cron — should NOT be due
        let now_local = Local.timestamp_opt(1_700_000_100, 0).single().unwrap();
        let schedule = Schedule {
            id: "s1".into(),
            name: "test".into(),
            cron: "0 * * * *".into(),
            command: "echo".into(),
            workdir: "/tmp".into(),
            ink: None,
            description: None,
            runtime: None,
            secrets: vec![],
            worktree: None,
            worktree_base: None,
            budget_cost_usd: None,
            enabled: true,
            last_run_at: Some(
                (now_local - ChronoDuration::seconds(10))
                    .with_timezone(&Utc)
                    .to_rfc3339(),
            ),
            last_session_id: Some("prev".into()),
            last_attempted_at: None,
            last_error: None,
            created_at: (now_local - ChronoDuration::hours(24))
                .with_timezone(&Utc)
                .to_rfc3339(),
        };
        assert!(!is_due_at(&schedule, now_local));
    }

    #[test]
    fn test_is_due_invalid_cron() {
        let now_local = Local.timestamp_opt(1_700_000_100, 0).single().unwrap();
        let schedule = Schedule {
            id: "s1".into(),
            name: "test".into(),
            cron: "invalid".into(),
            command: "echo".into(),
            workdir: "/tmp".into(),
            ink: None,
            description: None,
            runtime: None,
            secrets: vec![],
            worktree: None,
            worktree_base: None,
            budget_cost_usd: None,
            enabled: true,
            last_run_at: None,
            last_session_id: None,
            last_attempted_at: None,
            last_error: None,
            created_at: now_local.with_timezone(&Utc).to_rfc3339(),
        };
        assert!(!is_due_at(&schedule, now_local));
    }

    #[test]
    fn test_is_due_disabled_still_checks() {
        // is_due doesn't check enabled — that's the caller's job
        let schedule = Schedule {
            id: "s1".into(),
            name: "test".into(),
            cron: "* * * * *".into(),
            command: "echo".into(),
            workdir: "/tmp".into(),
            ink: None,
            description: None,
            runtime: None,
            secrets: vec![],
            worktree: None,
            worktree_base: None,
            budget_cost_usd: None,
            enabled: false,
            last_run_at: None,
            last_session_id: None,
            last_attempted_at: None,
            last_error: None,
            created_at: (Utc::now() - ChronoDuration::hours(1)).to_rfc3339(),
        };
        assert!(is_due(&schedule));
    }
}