Skip to main content

eclipse_core/
cron.rs

1//! `eclipse cron`: prompts that run on a timer.
2//!
3//! Three files, all under one root: `<root>/cron/jobs.toml` says what should run and when,
4//! `<root>/state/cron.json` remembers what did, and `<root>/cron/runs/<job>/<ms>.md` is what came
5//! back. The jobs file is yours to edit — the tool and the CLI write the same format — and a
6//! hand-edit is never lost: nothing here rewrites blocks it was not asked to touch.
7//!
8//! Time is the hard part. A schedule of "daily 07:30" means 07:30 where the person is, not
9//! 07:30 UTC, and the project takes no date-time dependency, so local time comes from `libc`
10//! (offset at an instant, and the civil calendar) with a pure-Rust civil-date conversion that is
11//! also what the tests use. An interval schedule never consults a calendar at all.
12//!
13//! Nothing here runs an agent: [`due`] decides, and the caller runs. That keeps the decision
14//! testable with a clock the test controls, and keeps the core free of a dependency cycle
15//! (runtime depends on this, not the other way round).
16
17use crate::error::{Error, Result};
18use serde::{Deserialize, Serialize};
19use std::collections::BTreeMap;
20use std::path::{Path, PathBuf};
21
22/// Where jobs live: `<root>/cron/jobs.toml`.
23pub fn jobs_path(root: &Path) -> PathBuf {
24    root.join("cron").join("jobs.toml")
25}
26
27/// Where a job's run history goes: `<root>/cron/runs/<name>/`.
28/// Every job's run logs: `<root>/cron/runs`, before a job name is appended.
29pub fn runs_root(root: &Path) -> PathBuf {
30    root.join("cron").join("runs")
31}
32
33pub fn runs_dir(root: &Path, name: &str) -> PathBuf {
34    root.join("cron").join("runs").join(name)
35}
36
37/// Where `<root>/state/cron.json` — the record of what ran — lives.
38pub fn state_path(root: &Path) -> PathBuf {
39    root.join("state").join("cron.json")
40}
41
42/// A named job: what to say, when to say it.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Job {
45    pub name: String,
46    pub schedule: Schedule,
47    pub prompt: String,
48    pub enabled: bool,
49    /// Run this route and no other. `None` follows the config's chain.
50    pub route: Option<String>,
51    /// This job's workspace: the file tools are confined to it, `shell` runs in it, and the
52    /// `AGENT.md` walk begins there. `None` keeps whatever `[tools] workspace_root` says. The
53    /// directory is checked at `add`; `~/` is expanded at both ends.
54    pub workdir: Option<String>,
55    /// Skills to load before the prompt runs.
56    pub skills: Vec<String>,
57    /// Write the reply here too (`/abs/path` or `~/path`). `None` writes only the run log.
58    pub deliver: Option<String>,
59    /// Demand a shape: a path to a JSON schema, or the schema itself. `None` falls back to
60    /// `[agent] output_schema`. The schema rides in the request as `response_format`; a reply
61    /// that is not a JSON document fails the job, which is what `run --schema` does too.
62    pub schema: Option<String>,
63}
64
65/// When a job fires.
66///
67/// Deliberately small: four shapes a person can hold in their head, and no cron syntax to
68/// mis-remember. `every 30m` is an interval; the rest name a moment in local time.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Schedule {
71    /// Every N seconds, counted from the last start.
72    Every(u64),
73    Daily {
74        hour: u32,
75        minute: u32,
76    },
77    /// `weekday` is 0 = Sunday, matching `localtime`'s `tm_wday`.
78    Weekly {
79        weekday: u32,
80        hour: u32,
81        minute: u32,
82    },
83}
84
85/// A minute is the floor: anything finer is a busy loop wearing a schedule's clothes, and the
86/// timer that drives these ticks wakes once a minute anyway.
87pub const MIN_EVERY_SECS: u64 = 60;
88
89const WEEKDAYS: [&str; 7] = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
90
91impl Schedule {
92    /// What the file said, as someone would write it back.
93    pub fn describe(&self) -> String {
94        match self {
95            Schedule::Every(secs) if *secs % 3600 == 0 => format!("every {}h", secs / 3600),
96            Schedule::Every(secs) if *secs % 60 == 0 => format!("every {}m", secs / 60),
97            Schedule::Every(secs) => format!("every {secs}s"),
98            Schedule::Daily { hour, minute } => format!("daily {hour:02}:{minute:02}"),
99            Schedule::Weekly {
100                weekday,
101                hour,
102                minute,
103            } => format!(
104                "weekly {} {hour:02}:{minute:02}",
105                WEEKDAYS[(*weekday as usize).min(6)]
106            ),
107        }
108    }
109
110    pub fn parse(text: &str) -> Result<Schedule> {
111        let t = text.trim();
112        let lower = t.to_ascii_lowercase();
113        if lower == "hourly" {
114            return Ok(Schedule::Every(3600));
115        }
116        if let Some(rest) = lower.strip_prefix("every ") {
117            return parse_every(rest.trim(), text);
118        }
119        if let Some(rest) = lower.strip_prefix("daily ") {
120            let (hour, minute) = parse_clock(rest.trim(), text)?;
121            return Ok(Schedule::Daily { hour, minute });
122        }
123        if let Some(rest) = lower.strip_prefix("weekly ") {
124            let mut parts = rest.split_whitespace();
125            let day = parts.next().unwrap_or("");
126            let clock = parts.next().unwrap_or("");
127            if parts.next().is_some() {
128                return Err(bad_schedule(text));
129            }
130            let weekday = WEEKDAYS
131                .iter()
132                .position(|d| *d == day)
133                .ok_or_else(|| bad_schedule(text))? as u32;
134            let (hour, minute) = parse_clock(clock, text)?;
135            return Ok(Schedule::Weekly {
136                weekday,
137                hour,
138                minute,
139            });
140        }
141        Err(bad_schedule(text))
142    }
143
144    /// The first moment this schedule fires strictly after `after_ms`, in epoch milliseconds.
145    ///
146    /// For an interval this is arithmetic. For a named moment it is a search in local time,
147    /// which is why it can take up to eight days: a weekly job whose moment passed a minute ago
148    /// is due next week, not now.
149    pub fn next_due(&self, after_ms: i64) -> i64 {
150        match *self {
151            // Saturating rather than wrapping: the parse above refuses an interval that cannot be
152            // multiplied out, but a `next_due` that reported a negative moment would be worse than
153            // one that reported the end of time (`#406`).
154            Schedule::Every(secs) => after_ms.saturating_add((secs as i64).saturating_mul(1000)),
155            Schedule::Daily { hour, minute } => next_matching(after_ms, None, hour, minute),
156            Schedule::Weekly {
157                weekday,
158                hour,
159                minute,
160            } => next_matching(after_ms, Some(weekday), hour, minute),
161        }
162    }
163}
164
165fn bad_schedule(text: &str) -> Error {
166    Error::Config(format!(
167        "unrecognised schedule {text:?}. Write `every 30m`, `hourly`, `daily 07:30` or \
168         `weekly mon 09:00`"
169    ))
170}
171
172fn parse_every(rest: &str, original: &str) -> Result<Schedule> {
173    let (number, unit) = match rest.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
174        Some((i, _)) => rest.split_at(i),
175        None => (rest, ""),
176    };
177    let n: u64 = number.parse().map_err(|_| bad_schedule(original))?;
178    // `#406`: unchecked multiplication, and a release build has no overflow checks —
179    // `every 144115188075855873d` wrapped to exactly 86_400 seconds and passed as `every 1d`.
180    // A debug build panicked instead. Both are the same bug seen from two builds.
181    let per_second = match unit {
182        "s" => 1u64,
183        "m" => 60,
184        "h" => 3_600,
185        "d" => 86_400,
186        _ => return Err(bad_schedule(original)),
187    };
188    let secs = n.checked_mul(per_second).ok_or_else(|| {
189        Error::Config(format!(
190            "`every {rest}` is longer than this machine can count; the longest interval is \
191             `every {}d`",
192            i64::MAX as u64 / 1000 / 86_400
193        ))
194    })?;
195    // `next_due` multiplies seconds by 1000 in an `i64`; past this the schedule could not be
196    // represented, and `cron list` is one of the callers.
197    if secs > i64::MAX as u64 / 1000 {
198        return Err(Error::Config(format!(
199            "`every {rest}` is longer than this machine can count; the longest interval is \
200             `every {}d`",
201            i64::MAX as u64 / 1000 / 86_400
202        )));
203    }
204    if secs < MIN_EVERY_SECS {
205        return Err(Error::Config(format!(
206            "`every {rest}` is finer than a minute, which is a busy loop rather than a schedule; \
207             the shortest interval is `every 1m`"
208        )));
209    }
210    Ok(Schedule::Every(secs))
211}
212
213fn parse_clock(text: &str, original: &str) -> Result<(u32, u32)> {
214    let (h, m) = text.split_once(':').ok_or_else(|| bad_schedule(original))?;
215    let hour: u32 = h.trim().parse().map_err(|_| bad_schedule(original))?;
216    let minute: u32 = m.trim().parse().map_err(|_| bad_schedule(original))?;
217    if hour > 23 || minute > 59 || h.trim().len() > 2 || m.trim().len() > 2 {
218        return Err(Error::Config(format!(
219            "{text:?} is not a time of day; write it as HH:MM in 24 hours, e.g. `07:30`"
220        )));
221    }
222    Ok((hour, minute))
223}
224
225/// The next local wall-clock moment of `hour:minute`, on `weekday` when one is named.
226///
227/// Walks forward a day at a time in the civil calendar rather than adding 86_400_000ms, so that
228/// a day with 23 or 25 hours in it (a DST boundary) lands on the same wall-clock time instead of
229/// drifting an hour. Eight days covers "this weekday, an instant ago" plus a DST shift.
230fn next_matching(after_ms: i64, weekday: Option<u32>, hour: u32, minute: u32) -> i64 {
231    let (y, mo, d, ..) = local_parts(after_ms);
232    for skip in 0..=8 {
233        let (yy, mm, dd) = civil_add_days(y, mo, d, skip);
234        let candidate = local_moment_ms(yy, mm, dd, hour, minute);
235        if candidate <= after_ms {
236            continue;
237        }
238        if let Some(want) = weekday {
239            if weekday_of(candidate) != want {
240                continue;
241            }
242        }
243        return candidate;
244    }
245    // Unreachable in practice: eight consecutive days contain every weekday, and the candidate
246    // for a day at least two ahead is always in the future.
247    after_ms + 7 * 86_400_000
248}
249
250// ---------------------------------------------------------------------------------------------
251// Local time
252// ---------------------------------------------------------------------------------------------
253
254/// Offset of local time from UTC at an instant, in seconds east. Zero without a C library.
255#[cfg(unix)]
256fn local_offset_secs(ms: i64) -> i64 {
257    let secs = ms.div_euclid(1000) as libc::time_t;
258    // SAFETY: `localtime_r` writes into the `tm` we hand it and reads nothing else; the pointer
259    // is valid for the call.
260    unsafe {
261        let mut tm: libc::tm = std::mem::zeroed();
262        if libc::localtime_r(&secs, &mut tm).is_null() {
263            return 0;
264        }
265        tm.tm_gmtoff as i64
266    }
267}
268
269#[cfg(not(unix))]
270fn local_offset_secs(_ms: i64) -> i64 {
271    0
272}
273
274/// `(year, month, day, hour, minute)` in local time.
275pub fn local_parts(ms: i64) -> (i32, u32, u32, u32, u32) {
276    let offset = local_offset_secs(ms);
277    let local_secs = ms.div_euclid(1000) + offset;
278    let days = local_secs.div_euclid(86_400);
279    let rem = local_secs.rem_euclid(86_400);
280    let (y, m, d) = civil_from_days(days);
281    (y, m, d, (rem / 3600) as u32, ((rem % 3600) / 60) as u32)
282}
283
284/// Epoch milliseconds for a local wall-clock moment.
285///
286/// Two passes: guess the offset at the naive instant, then re-read the offset at the guessed
287/// instant. They differ only across a DST change, and the second pass is what makes "07:30"
288/// mean 07:30 on both sides of one.
289fn local_moment_ms(y: i32, mo: u32, d: u32, hour: u32, minute: u32) -> i64 {
290    let naive = days_from_civil(y, mo, d) * 86_400 + hour as i64 * 3600 + minute as i64 * 60;
291    let first = naive - local_offset_secs(naive * 1000);
292    let second = naive - local_offset_secs(first * 1000);
293    second * 1000
294}
295
296/// Which day of the week a local instant falls on: 0 = Sunday.
297pub fn weekday_of(ms: i64) -> u32 {
298    let offset = local_offset_secs(ms);
299    let days = (ms.div_euclid(1000) + offset).div_euclid(86_400);
300    // 1970-01-01 was a Thursday.
301    (days + 4).rem_euclid(7) as u32
302}
303
304/// Days since the Unix epoch for a proleptic Gregorian date (Howard Hinnant's algorithm, which
305/// every date library ends up reimplementing).
306fn days_from_civil(y: i32, m: u32, d: u32) -> i64 {
307    let y = if m <= 2 { y - 1 } else { y } as i64;
308    let era = if y >= 0 { y } else { y - 399 } / 400;
309    let yoe = y - era * 400;
310    let mp = (m as i64 + 9) % 12;
311    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
312    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
313    era * 146_097 + doe - 719_468
314}
315
316/// The inverse of [`days_from_civil`]; `pub(crate)` because the install record writes its
317/// timestamp in the same calendar rather than carrying a second copy of it.
318pub(crate) fn civil_from_days(z: i64) -> (i32, u32, u32) {
319    let z = z + 719_468;
320    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
321    let doe = z - era * 146_097;
322    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
323    let y = yoe + era * 400;
324    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
325    let mp = (5 * doy + 2) / 153;
326    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
327    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
328    ((if m <= 2 { y + 1 } else { y }) as i32, m, d)
329}
330
331fn civil_add_days(y: i32, m: u32, d: u32, days: i64) -> (i32, u32, u32) {
332    civil_from_days(days_from_civil(y, m, d) + days)
333}
334
335// ---------------------------------------------------------------------------------------------
336// The jobs file
337// ---------------------------------------------------------------------------------------------
338
339#[derive(Deserialize)]
340#[serde(deny_unknown_fields)]
341struct RawFile {
342    #[serde(default, rename = "job")]
343    jobs: Vec<RawJob>,
344}
345
346#[derive(Deserialize)]
347#[serde(deny_unknown_fields)]
348struct RawJob {
349    name: String,
350    schedule: String,
351    prompt: String,
352    enabled: Option<bool>,
353    route: Option<String>,
354    workdir: Option<String>,
355    #[serde(default)]
356    skills: Vec<String>,
357    deliver: Option<String>,
358    schema: Option<String>,
359}
360
361/// Read `<root>/cron/jobs.toml`. A missing file is not an error: it is a machine with no jobs.
362pub fn load(root: &Path) -> Result<Vec<Job>> {
363    Ok(load_reporting(root)?.0)
364}
365
366/// Read `<root>/cron/jobs.toml` and say which blocks are unusable.
367///
368/// `#405`: one malformed block used to be an `Err` for the whole file, so a typo in a job nobody
369/// was looking at stopped every other job, and a failed systemd unit was the only trace. The docs
370/// invite hand-editing, so a bad block is skipped and named instead. The *file* still has to parse:
371/// a TOML syntax error is the file's shape, not one job's, and the parse error already names a
372/// line number.
373pub fn load_reporting(root: &Path) -> Result<(Vec<Job>, Vec<String>)> {
374    let path = jobs_path(root);
375    let text = match std::fs::read_to_string(&path) {
376        Ok(t) => t,
377        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((Vec::new(), Vec::new())),
378        Err(e) => return Err(Error::io(&path, e)),
379    };
380    let raw: RawFile = toml::from_str(&text).map_err(|e| Error::Parse {
381        path: path.clone(),
382        message: e.to_string(),
383    })?;
384    let mut jobs: Vec<Job> = Vec::new();
385    let mut problems: Vec<String> = Vec::new();
386    for r in raw.jobs {
387        // The name is what a reader needs to find the block again, and it is the one field that is
388        // allowed to be missing — say `job 3` then, rather than a bare `""`.
389        let label = if r.name.trim().is_empty() {
390            format!("job #{}", jobs.len() + problems.len() + 1)
391        } else {
392            format!("job `{}`", r.name)
393        };
394        match build_job(r, &jobs) {
395            Ok(job) => jobs.push(job),
396            Err(e) => problems.push(format!("{label} was skipped: {e}")),
397        }
398    }
399    Ok((jobs, problems))
400}
401
402/// One `[[job]]` block, or the reason it cannot be run. Split out so a bad block can be skipped
403/// with its own message instead of failing the file (`#405`).
404fn build_job(r: RawJob, jobs: &[Job]) -> Result<Job> {
405    if r.name.trim().is_empty() {
406        return Err(Error::Config("it has an empty name".into()));
407    }
408    validate_job_name(&r.name)?;
409    if r.prompt.trim().is_empty() {
410        return Err(Error::Config(format!(
411            "`{}` has an empty prompt; a timer with nothing to say is not a job",
412            r.name
413        )));
414    }
415    if jobs.iter().any(|j: &Job| j.name == r.name) {
416        return Err(Error::Config(format!(
417            "another job is already named `{}`; the name is how a run is recorded and how you \
418             refer to it",
419            r.name
420        )));
421    }
422    // The schedule error names the job it came from, because a list of twelve blocks and one
423    // `unrecognised schedule "evry 5m"` is a search (`#405`).
424    let schedule =
425        Schedule::parse(&r.schedule).map_err(|e| Error::Config(format!("`{}`: {e}", r.name)))?;
426    Ok(Job {
427        name: r.name,
428        schedule,
429        prompt: r.prompt,
430        enabled: r.enabled.unwrap_or(true),
431        route: r.route,
432        workdir: r.workdir,
433        skills: r.skills,
434        deliver: r.deliver,
435        schema: r.schema,
436    })
437}
438
439/// Names become directory names, so they are held to the same alphabet as profile names.
440pub fn validate_job_name(name: &str) -> Result<()> {
441    let ok = !name.is_empty()
442        && name.len() <= 64
443        && name
444            .chars()
445            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
446    if ok {
447        Ok(())
448    } else {
449        Err(Error::Config(format!(
450            "invalid job name {name:?}: letters, digits, `-` and `_`, because it names a \
451             directory the runs are kept in"
452        )))
453    }
454}
455
456fn block_for(job: &Job) -> String {
457    let mut s = String::from("[[job]]\n");
458    s.push_str(&format!("name = {}\n", quote(&job.name)));
459    s.push_str(&format!("schedule = {}\n", quote(&job.schedule.describe())));
460    if !job.enabled {
461        s.push_str("enabled = false\n");
462    }
463    if let Some(route) = &job.route {
464        s.push_str(&format!("route = {}\n", quote(route)));
465    }
466    if let Some(workdir) = &job.workdir {
467        s.push_str(&format!("workdir = {}\n", quote(workdir)));
468    }
469    if !job.skills.is_empty() {
470        let list: Vec<String> = job.skills.iter().map(|s| quote(s)).collect();
471        s.push_str(&format!("skills = [{}]\n", list.join(", ")));
472    }
473    if let Some(deliver) = &job.deliver {
474        s.push_str(&format!("deliver = {}\n", quote(deliver)));
475    }
476    if let Some(schema) = &job.schema {
477        s.push_str(&format!("schema = {}\n", quote(schema)));
478    }
479    s.push_str(&format!("prompt = {}\n", quote(&job.prompt)));
480    s
481}
482
483/// A TOML basic string, escaped. Enough for names, paths and prompts; the file is meant to be
484/// read by a person, so multi-line prompts still come out as one long line and are edited by
485/// hand when they need to be.
486fn quote(s: &str) -> String {
487    let mut out = String::with_capacity(s.len() + 2);
488    out.push('"');
489    for c in s.chars() {
490        match c {
491            '"' => out.push_str("\\\""),
492            '\\' => out.push_str("\\\\"),
493            '\n' => out.push_str("\\n"),
494            '\t' => out.push_str("\\t"),
495            '\r' => out.push_str("\\r"),
496            c => out.push(c),
497        }
498    }
499    out.push('"');
500    out
501}
502
503/// Append a job to the file, creating it with a one-line explanation if it does not exist.
504///
505/// Appending never touches what is already there, so comments and hand-formatting survive a
506/// job being added by the tool.
507pub fn append_job(root: &Path, job: &Job) -> Result<()> {
508    validate_job_name(&job.name)?;
509    let existing = load(root)?;
510    if existing.iter().any(|j| j.name == job.name) {
511        return Err(Error::Config(format!(
512            "a job named `{}` already exists; remove it first, or pick another name",
513            job.name
514        )));
515    }
516    let path = jobs_path(root);
517    if let Some(dir) = path.parent() {
518        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
519    }
520    let mut text = match std::fs::read_to_string(&path) {
521        Ok(t) => t,
522        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
523        Err(e) => return Err(Error::io(&path, e)),
524    };
525    if text.trim().is_empty() {
526        text.push_str("# Prompts that run on a timer. `eclipse cron list` reads this file,\n");
527        text.push_str("# `eclipse cron run` is what the systemd timer invokes.\n");
528    } else if !text.ends_with('\n') {
529        text.push('\n');
530    }
531    text.push('\n');
532    text.push_str(&block_for(job));
533    // `#408`: `jobs.toml` is hand-edited, so a half-written one is somebody's work lost and a job
534    // list that no longer parses. Write beside and rename.
535    crate::atomic::write_file_atomically(&path, &text).map_err(|e| Error::io(&path, e))
536}
537
538/// Remove a job by name, leaving every other block exactly as it was.
539pub fn remove_job(root: &Path, name: &str) -> Result<bool> {
540    let path = jobs_path(root);
541    let text = match std::fs::read_to_string(&path) {
542        Ok(t) => t,
543        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
544        Err(e) => return Err(Error::io(&path, e)),
545    };
546    let kept = drop_block(&text, name);
547    match kept {
548        None => Ok(false),
549        Some(new_text) => {
550            crate::atomic::write_file_atomically(&path, &new_text)
551                .map_err(|e| Error::io(&path, e))?;
552            Ok(true)
553        }
554    }
555}
556
557/// Replace a job's `[[job]]` block in place, leaving every other byte of the file alone.
558///
559/// This is what `pause` and `resume` need: rewriting the whole file from the parsed jobs would
560/// be correct and would also delete the comments and formatting a person put next to their
561/// other jobs.
562pub fn replace_job(root: &Path, job: &Job) -> Result<()> {
563    let path = jobs_path(root);
564    let text = std::fs::read_to_string(&path).map_err(|e| Error::io(&path, e))?;
565    let updated = with_block_replaced(&text, job)
566        .ok_or_else(|| Error::Config(format!("no job named `{}`", job.name)))?;
567    crate::atomic::write_file_atomically(&path, &updated).map_err(|e| Error::io(&path, e))
568}
569
570fn with_block_replaced(text: &str, job: &Job) -> Option<String> {
571    let lines: Vec<&str> = text.lines().collect();
572    let mut out: Vec<String> = Vec::new();
573    let mut found = false;
574    let mut i = 0;
575    while i < lines.len() {
576        if lines[i].trim() == "[[job]]" {
577            let mut end = i + 1;
578            while end < lines.len() && lines[end].trim() != "[[job]]" {
579                end += 1;
580            }
581            let block = &lines[i..end];
582            let is_ours = block.iter().any(|l| {
583                l.trim_start()
584                    .strip_prefix("name")
585                    .map(|rest| rest.trim_start().starts_with('='))
586                    .unwrap_or(false)
587                    && l.contains(&quote(&job.name))
588            });
589            if is_ours && !found {
590                found = true;
591                for line in block_for(job).lines() {
592                    out.push(line.to_string());
593                }
594            } else {
595                out.extend(block.iter().map(|l| l.to_string()));
596            }
597            i = end;
598            continue;
599        }
600        out.push(lines[i].to_string());
601        i += 1;
602    }
603    if !found {
604        return None;
605    }
606    let mut s = out.join("\n");
607    if text.ends_with('\n') {
608        s.push('\n');
609    }
610    Some(s)
611}
612
613/// The file with `name`'s `[[job]]` block cut out, or `None` when it holds no such block.
614///
615/// Blocks are found by the `[[job]]` line that opens them and the `name = "…"` line inside, so a
616/// comment above a block stays with the block that follows it rather than orphaning onto the
617/// next one.
618fn drop_block(text: &str, name: &str) -> Option<String> {
619    let lines: Vec<&str> = text.lines().collect();
620    let mut out: Vec<&str> = Vec::new();
621    let mut found = false;
622    let mut i = 0;
623    while i < lines.len() {
624        if lines[i].trim() == "[[job]]" {
625            let mut end = i + 1;
626            while end < lines.len() && lines[end].trim() != "[[job]]" {
627                end += 1;
628            }
629            let block = &lines[i..end];
630            let is_ours = block.iter().any(|l| {
631                l.trim_start()
632                    .strip_prefix("name")
633                    .map(|rest| rest.trim_start().starts_with('='))
634                    .unwrap_or(false)
635                    && l.contains(&quote(name))
636            });
637            if is_ours {
638                found = true;
639                // Swallow the blank line that separated it from the block below, if any.
640                let mut stop = end;
641                while stop < lines.len() && lines[stop].trim().is_empty() {
642                    stop += 1;
643                }
644                i = stop;
645                continue;
646            }
647            out.extend_from_slice(block);
648            i = end;
649            continue;
650        }
651        out.push(lines[i]);
652        i += 1;
653    }
654    if !found {
655        return None;
656    }
657    let mut s = out.join("\n");
658    if text.ends_with('\n') {
659        s.push('\n');
660    }
661    Some(s)
662}
663
664// ---------------------------------------------------------------------------------------------
665// What ran
666// ---------------------------------------------------------------------------------------------
667
668#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
669pub struct JobState {
670    #[serde(default, skip_serializing_if = "Option::is_none")]
671    pub last_started_ms: Option<i64>,
672    #[serde(default, skip_serializing_if = "Option::is_none")]
673    pub last_finished_ms: Option<i64>,
674    /// `ok`, or the first line of what went wrong.
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub last_outcome: Option<String>,
677    #[serde(default)]
678    pub runs: u64,
679}
680
681#[derive(Debug, Clone, Default, Serialize, Deserialize)]
682pub struct State {
683    #[serde(default)]
684    pub jobs: BTreeMap<String, JobState>,
685}
686
687impl State {
688    pub fn get(&self, name: &str) -> JobState {
689        self.jobs.get(name).cloned().unwrap_or_default()
690    }
691}
692
693pub fn load_state(root: &Path) -> Result<State> {
694    let path = state_path(root);
695    let text = match std::fs::read_to_string(&path) {
696        Ok(t) => t,
697        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(State::default()),
698        Err(e) => return Err(Error::io(&path, e)),
699    };
700    if text.trim().is_empty() {
701        return Ok(State::default());
702    }
703    serde_json::from_str(&text).map_err(|e| Error::Parse {
704        path,
705        message: e.to_string(),
706    })
707}
708
709pub fn save_state(root: &Path, state: &State) -> Result<()> {
710    let path = state_path(root);
711    if let Some(dir) = path.parent() {
712        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
713    }
714    let text = serde_json::to_string_pretty(state)
715        .map_err(|e| Error::Config(format!("cannot encode cron state: {e}")))?;
716    // Write beside and rename: a tick that dies mid-write must not leave the record half a
717    // record, because the next tick reads it to decide what is due. The scratch name used to be a
718    // fixed `state.json.tmp`, which two ticks share (`#408`).
719    crate::atomic::write_file_atomically(&path, &text).map_err(|e| Error::io(&path, e))
720}
721
722/// The jobs that should run now.
723///
724/// A job that has never run is due immediately when its schedule is an interval — the timer was
725/// just installed, and waiting half an hour to prove it works is not useful — and at its next
726/// named moment otherwise, so that installing a timer at noon does not execute a 07:30 briefing
727/// on the spot.
728pub fn due<'a>(jobs: &'a [Job], state: &State, now_ms: i64) -> Vec<&'a Job> {
729    jobs.iter()
730        .filter(|j| j.enabled)
731        .filter(|j| {
732            let entry = state.jobs.get(&j.name);
733            let last = entry.and_then(|e| e.last_started_ms);
734            match (last, j.schedule) {
735                (None, Schedule::Every(_)) => true,
736                (None, _) => false,
737                (Some(last), schedule) => now_ms >= schedule.next_due(last),
738            }
739        })
740        .collect()
741}
742
743/// When a job fires next, given what has run. `None` for a disabled job.
744pub fn next_due_for(job: &Job, state: &State, now_ms: i64) -> Option<i64> {
745    if !job.enabled {
746        return None;
747    }
748    match state.jobs.get(&job.name).and_then(|e| e.last_started_ms) {
749        None => match job.schedule {
750            Schedule::Every(_) => Some(now_ms),
751            schedule => Some(schedule.next_due(now_ms)),
752        },
753        Some(last) => {
754            let mut next = job.schedule.next_due(last);
755            // A tick that was missed while the machine was off is due at the next tick, not a
756            // burst of catch-up runs: one prompt per job per tick.
757            if next < now_ms && matches!(job.schedule, Schedule::Every(_)) {
758                next = now_ms;
759            }
760            Some(next)
761        }
762    }
763}
764
765// ---------------------------------------------------------------------------------------------
766// The tick lock
767// ---------------------------------------------------------------------------------------------
768
769/// How long a lock may be ignored before it is taken as abandoned.
770///
771/// A run that hangs cannot be waited on forever by a timer that fires every minute; after this
772/// the next tick takes the lock and says so in its output. Long enough that a slow model call
773/// is not cut off, short enough that a wedged tick does not stop the schedule for a day.
774pub const STALE_LOCK_MS: u64 = 30 * 60 * 1000;
775
776/// Held for the duration of one tick, so two timers (a systemd one and a hand-run one) cannot
777/// run the same job twice.
778pub struct Lock {
779    path: PathBuf,
780    /// True when this tick took over an abandoned lock, so it can say so.
781    pub took_over_stale: bool,
782    /// What this holder last wrote. The file's mtime is the staleness signal and its content is
783    /// "this holder is still here", so a `Drop` that removes the file has to know whether the file
784    /// is still the one it wrote (`#407`).
785    stamp: String,
786}
787
788impl Lock {
789    pub fn path(&self) -> &Path {
790        &self.path
791    }
792
793    /// Say this tick is still working, between jobs.
794    ///
795    /// `#407`: staleness is judged from the file's mtime, which was set once and never refreshed,
796    /// so a tick that legitimately ran past `STALE_LOCK_MS` was taken for an abandoned one — the
797    /// next minute's tick took the lock and ran the jobs this one had not reached yet, in both.
798    /// Returns false when the file is no longer ours, which means another tick has taken over and
799    /// this one must stop rather than fight over jobs.
800    pub fn touch(&mut self, now_ms: i64) -> bool {
801        if std::fs::read_to_string(&self.path).ok().as_deref() != Some(self.stamp.as_str()) {
802            return false;
803        }
804        let next = format!("{now_ms}\n");
805        if std::fs::write(&self.path, &next).is_err() {
806            return false;
807        }
808        self.stamp = next;
809        true
810    }
811}
812
813impl Drop for Lock {
814    fn drop(&mut self) {
815        // Only the lock this tick still holds. A tick whose lock was taken over used to delete the
816        // new holder's file on the way out, which let a third tick start beside it (`#407`).
817        if std::fs::read_to_string(&self.path).ok().as_deref() == Some(self.stamp.as_str()) {
818            let _ = std::fs::remove_file(&self.path);
819        }
820    }
821}
822
823pub fn lock(root: &Path, now_ms: i64) -> Result<Option<Lock>> {
824    let path = root.join("state").join("cron.lock");
825    if let Some(dir) = path.parent() {
826        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
827    }
828    match std::fs::OpenOptions::new()
829        .write(true)
830        .create_new(true)
831        .open(&path)
832    {
833        Ok(mut f) => {
834            use std::io::Write;
835            let stamp = format!("{now_ms}\n");
836            let _ = write!(f, "{stamp}");
837            Ok(Some(Lock {
838                path,
839                took_over_stale: false,
840                stamp,
841            }))
842        }
843        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
844            // `saturating_sub` clamps at the type's bounds, not at zero: a lock written a few
845            // milliseconds ahead of our clock came out as a negative age, cast to u64 it read as
846            // 584 years old, and every tick took it over. Clamp here, and where the clock cannot
847            // be read at all, refuse — a lock of unknown age is a lock.
848            let age = std::fs::metadata(&path)
849                .and_then(|m| m.modified())
850                .ok()
851                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
852                .map(|d| now_ms.saturating_sub(d.as_millis() as i64).max(0) as u64)
853                .unwrap_or(0);
854            if age < STALE_LOCK_MS {
855                return Ok(None);
856            }
857            let stamp = format!("{now_ms}\n");
858            std::fs::write(&path, &stamp).map_err(|e| Error::io(&path, e))?;
859            Ok(Some(Lock {
860                path,
861                took_over_stale: true,
862                stamp,
863            }))
864        }
865        Err(e) => Err(Error::io(&path, e)),
866    }
867}
868
869/// The run log for one execution: `<root>/cron/runs/<job>/<ms>.md`.
870pub fn write_run(root: &Path, job: &str, started_ms: i64, body: &str) -> Result<PathBuf> {
871    let dir = runs_dir(root, job);
872    std::fs::create_dir_all(&dir).map_err(|e| Error::io(&dir, e))?;
873    let path = dir.join(format!("{started_ms}.md"));
874    std::fs::write(&path, body).map_err(|e| Error::io(&path, e))?;
875    Ok(path)
876}
877
878/// The most recent runs of a job, newest first.
879pub fn recent_runs(root: &Path, job: &str, limit: usize) -> Vec<PathBuf> {
880    let dir = runs_dir(root, job);
881    let Ok(entries) = std::fs::read_dir(&dir) else {
882        return Vec::new();
883    };
884    let mut paths: Vec<PathBuf> = entries
885        .flatten()
886        .map(|e| e.path())
887        .filter(|p| p.extension().map(|e| e == "md").unwrap_or(false))
888        .collect();
889    paths.sort();
890    paths.reverse();
891    paths.truncate(limit);
892    paths
893}
894
895// ---------------------------------------------------------------------------------------------
896// A job as a surface reads it
897// ---------------------------------------------------------------------------------------------
898
899/// How much of a run's text a surface is handed. A job that answers in ten thousand words is a
900/// job whose log is an essay; the page shows the beginning and says the rest is on disk in
901/// `path`, rather than shipping a megabyte of JSON to a browser to render four lines of it.
902pub const RUN_TEXT_CAP: usize = 4000;
903
904/// How much of a run's first line fits in a table: enough to know what happened, short enough to
905/// sit in one row. The rest is in [`RunView::text`].
906pub const ANSWER_CAP: usize = 160;
907
908/// One job, plus what has run and when it fires next.
909///
910/// This is the shape `cron list --json` prints and the dashboard renders. It is deliberately not
911/// the file's shape: the store's keys (`[[job]]` in TOML) stay where they are so a field renamed
912/// for a page cannot move a key in a file somebody wrote by hand.
913#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
914pub struct JobView {
915    pub name: String,
916    /// As [`Schedule::parse`] accepts it back — the same string an editor shows and submits, so a
917    /// page never has to know that `hourly` and `every 1h` are one schedule.
918    pub schedule: String,
919    pub enabled: bool,
920    pub prompt: String,
921    pub route: Option<String>,
922    pub workdir: Option<String>,
923    pub skills: Vec<String>,
924    pub deliver: Option<String>,
925    pub schema: Option<String>,
926    /// The next fire, or `None` for a disabled job.
927    pub next_ms: Option<i64>,
928    pub last_started_ms: Option<i64>,
929    pub last_finished_ms: Option<i64>,
930    /// `ok`, `failed`, or the first line of what went wrong.
931    pub last_outcome: Option<String>,
932    pub runs: u64,
933}
934
935pub fn view(job: &Job, state: &State, now_ms: i64) -> JobView {
936    let s = state.get(&job.name);
937    JobView {
938        name: job.name.clone(),
939        schedule: job.schedule.describe(),
940        enabled: job.enabled,
941        prompt: job.prompt.clone(),
942        route: job.route.clone(),
943        workdir: job.workdir.clone(),
944        skills: job.skills.clone(),
945        deliver: job.deliver.clone(),
946        schema: job.schema.clone(),
947        next_ms: next_due_for(job, state, now_ms),
948        last_started_ms: s.last_started_ms,
949        last_finished_ms: s.last_finished_ms,
950        last_outcome: s.last_outcome,
951        runs: s.runs,
952    }
953}
954
955/// Every job, in the order the file has them, as a surface reads them.
956pub fn views(root: &Path, now_ms: i64) -> Result<Vec<JobView>> {
957    let state = load_state(root)?;
958    Ok(load(root)?
959        .iter()
960        .map(|job| view(job, &state, now_ms))
961        .collect())
962}
963
964/// One run of a job, as a surface reads it.
965#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
966pub struct RunView {
967    pub at_ms: i64,
968    /// The same moment for a person, in local time.
969    pub at: String,
970    /// The first non-empty line of the answer — what a table column shows.
971    pub answer: String,
972    /// The whole text, capped at [`RUN_TEXT_CAP`] characters.
973    pub text: String,
974    /// How long the whole text is, so a truncated `text` says so instead of just stopping.
975    pub chars: usize,
976    pub truncated: bool,
977    pub path: String,
978}
979
980/// `2026-11-29 07:30`, in local time.
981pub fn iso_local(ms: i64) -> String {
982    let (y, mo, d, h, mi) = local_parts(ms);
983    format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02}")
984}
985
986/// The newest runs of one job, read off the files the tick wrote.
987pub fn runs(root: &Path, job: &str, limit: usize) -> Vec<RunView> {
988    recent_runs(root, job, limit)
989        .into_iter()
990        .map(|path| {
991            let body = std::fs::read_to_string(&path).unwrap_or_default();
992            let at_ms = path
993                .file_stem()
994                .and_then(|s| s.to_str())
995                .and_then(|s| s.parse::<i64>().ok())
996                .unwrap_or(0);
997            // Everything after the first `---` is the answer; before it is the header the tick
998            // wrote (`# name — when`, the schedule, the route it took).
999            // One line, short enough to sit in a table cell: a job whose answer opens with a
1000            // paragraph of prose still has to fit beside a schedule and a date. What is cut is
1001            // marked, and the whole thing is in `text`.
1002            let first = body
1003                .split_once("---\n")
1004                .map(|(_, rest)| rest)
1005                .unwrap_or(&body)
1006                .lines()
1007                .find(|l| !l.trim().is_empty())
1008                .unwrap_or("(no output)")
1009                .trim();
1010            let answer = if first.chars().count() > ANSWER_CAP {
1011                let mut cut: String = first.chars().take(ANSWER_CAP).collect();
1012                cut.push('…');
1013                cut
1014            } else {
1015                first.to_string()
1016            };
1017            let chars = body.chars().count();
1018            let text: String = if chars > RUN_TEXT_CAP {
1019                body.chars().take(RUN_TEXT_CAP).collect()
1020            } else {
1021                body.clone()
1022            };
1023            RunView {
1024                at_ms,
1025                at: iso_local(at_ms),
1026                answer,
1027                text,
1028                chars,
1029                truncated: chars > RUN_TEXT_CAP,
1030                path: path.display().to_string(),
1031            }
1032        })
1033        .collect()
1034}
1035
1036// ---------------------------------------------------------------------------------------------
1037// What a surface may write
1038// ---------------------------------------------------------------------------------------------
1039
1040fn yes() -> bool {
1041    true
1042}
1043
1044/// A job as a surface submits it: `cron add`'s arguments, or a page's form.
1045///
1046/// One struct and one set of checks, because the two front ends must not disagree about what a job
1047/// is. `enabled` is the only field a create does not have to mention; everything else is the
1048/// caller's, and the errors are the parsers' own words so the two surfaces say the same sentence.
1049#[derive(Debug, Clone, Deserialize)]
1050pub struct Draft {
1051    pub name: String,
1052    pub schedule: String,
1053    pub prompt: String,
1054    #[serde(default)]
1055    pub deliver: Option<String>,
1056    #[serde(default)]
1057    pub route: Option<String>,
1058    #[serde(default)]
1059    pub workdir: Option<String>,
1060    #[serde(default)]
1061    pub skills: Vec<String>,
1062    #[serde(default)]
1063    pub schema: Option<String>,
1064    #[serde(default = "yes")]
1065    pub enabled: bool,
1066}
1067
1068impl Default for Draft {
1069    fn default() -> Self {
1070        Self {
1071            name: String::new(),
1072            schedule: String::new(),
1073            prompt: String::new(),
1074            deliver: None,
1075            route: None,
1076            workdir: None,
1077            skills: Vec::new(),
1078            schema: None,
1079            enabled: true,
1080        }
1081    }
1082}
1083
1084impl Draft {
1085    /// The job this describes, or why it does not describe one.
1086    ///
1087    /// A prompt is required and a schedule is parsed here rather than at 07:30 in a log nobody
1088    /// reads; a `workdir` is checked to be a directory for the same reason — a workspace that is a
1089    /// typo is a job whose files land somewhere else, or nowhere.
1090    pub fn to_job(&self) -> Result<Job> {
1091        validate_job_name(&self.name)?;
1092        if self.prompt.trim().is_empty() {
1093            return Err(Error::Config("a job needs a prompt".to_string()));
1094        }
1095        let schedule = Schedule::parse(&self.schedule)?;
1096        if let Some(dir) = &self.workdir {
1097            let path = expand_tilde(dir);
1098            if !path.is_dir() {
1099                return Err(Error::Config(format!(
1100                    "`{dir}` is not a directory, so the job would have no workspace"
1101                )));
1102            }
1103        }
1104        Ok(Job {
1105            name: self.name.clone(),
1106            schedule,
1107            prompt: self.prompt.clone(),
1108            enabled: self.enabled,
1109            route: self.route.clone(),
1110            workdir: self.workdir.clone(),
1111            skills: self.skills.clone(),
1112            deliver: self.deliver.clone(),
1113            schema: self.schema.clone(),
1114        })
1115    }
1116
1117    /// The same job as [`Draft`], for editing: what an editor loads into its form.
1118    pub fn from_job(job: &Job) -> Self {
1119        Self {
1120            name: job.name.clone(),
1121            schedule: job.schedule.describe(),
1122            prompt: job.prompt.clone(),
1123            deliver: job.deliver.clone(),
1124            route: job.route.clone(),
1125            workdir: job.workdir.clone(),
1126            skills: job.skills.clone(),
1127            schema: job.schema.clone(),
1128            enabled: job.enabled,
1129        }
1130    }
1131}
1132
1133/// `~/x` and `$HOME/x` as the path they mean.
1134///
1135/// The tick resolves a job's own directory the same way (`cron_cli::expand_path`), so a `workdir`
1136/// that is a directory when it is checked is a directory when it is used.
1137pub fn expand_tilde(text: &str) -> PathBuf {
1138    if let Some(rest) = text.strip_prefix("~/") {
1139        if let Some(home) = crate::config::process_env("HOME") {
1140            return PathBuf::from(home).join(rest);
1141        }
1142    }
1143    PathBuf::from(text)
1144}
1145
1146/// Turn a job on or off, in place. `false` when no job has that name.
1147pub fn set_enabled(root: &Path, name: &str, enabled: bool) -> Result<Option<Job>> {
1148    let jobs = load(root)?;
1149    let Some(mut job) = jobs.into_iter().find(|j| j.name == name) else {
1150        return Ok(None);
1151    };
1152    if job.enabled == enabled {
1153        return Ok(Some(job));
1154    }
1155    job.enabled = enabled;
1156    replace_job(root, &job)?;
1157    // Loading it back is the check that the file it wrote is a file this build can read.
1158    Ok(load(root)?.into_iter().find(|j| j.name == name))
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164
1165    fn job(name: &str, schedule: &str) -> Job {
1166        Job {
1167            name: name.into(),
1168            schedule: Schedule::parse(schedule).unwrap(),
1169            prompt: "say something".into(),
1170            enabled: true,
1171            route: None,
1172            workdir: None,
1173            skills: Vec::new(),
1174            deliver: None,
1175            schema: None,
1176        }
1177    }
1178
1179    /// A directory no other test in this run can be using, removed when the test ends.
1180    fn temp_root() -> crate::scratch::Scratch<PathBuf> {
1181        // Unique by construction: `tempfile` picks the name. It used to be
1182        // `eclipse-cron-test-<pid>-<ms>-<n>` because parallel threads of one process could hand two
1183        // tests the same name and they would delete each other's files; a `TempDir` gives the same
1184        // guarantee and removes itself, which the hand-built path did not — one directory per cron
1185        // test, each with a `cron/jobs.toml`, was left in `$TMPDIR` after every run.
1186        crate::scratch::Scratch::dir("eclipse-cron-test-")
1187    }
1188
1189    #[test]
1190    fn the_four_shapes_of_a_schedule_round_trip() {
1191        for (text, want) in [
1192            ("every 30m", Schedule::Every(1800)),
1193            ("every 2h", Schedule::Every(7200)),
1194            ("hourly", Schedule::Every(3600)),
1195            (
1196                "daily 07:30",
1197                Schedule::Daily {
1198                    hour: 7,
1199                    minute: 30,
1200                },
1201            ),
1202            (
1203                "weekly mon 09:00",
1204                Schedule::Weekly {
1205                    weekday: 1,
1206                    hour: 9,
1207                    minute: 0,
1208                },
1209            ),
1210        ] {
1211            let parsed = Schedule::parse(text).unwrap();
1212            assert_eq!(parsed, want, "{text}");
1213            assert_eq!(Schedule::parse(&parsed.describe()).unwrap(), want);
1214        }
1215    }
1216
1217    #[test]
1218    fn a_schedule_that_is_not_one_says_what_ones_exist() {
1219        for bad in [
1220            "",
1221            "30m",
1222            "every",
1223            "every 30",
1224            "every 30x",
1225            "daily",
1226            "daily 7",
1227            "daily 25:00",
1228            "weekly 9am",
1229        ] {
1230            let err = Schedule::parse(bad).unwrap_err().to_string();
1231            assert!(
1232                err.contains("unrecognised schedule") || err.contains("not a time of day"),
1233                "{bad}: {err}"
1234            );
1235        }
1236    }
1237
1238    #[test]
1239    fn a_sub_minute_interval_is_refused_as_a_busy_loop() {
1240        let err = Schedule::parse("every 30s").unwrap_err().to_string();
1241        assert!(err.contains("shortest interval is `every 1m`"), "{err}");
1242    }
1243
1244    #[test]
1245    fn a_daily_schedule_lands_on_that_wall_clock_time_tomorrow_at_the_latest() {
1246        let now = 1_700_000_000_000i64; // 2023-11-14T22:13:20Z
1247        let s = Schedule::parse("daily 07:30").unwrap();
1248        let next = s.next_due(now);
1249        assert!(next > now);
1250        assert!(next - now <= 86_400_000, "within a day: {}", next - now);
1251        let (_, _, _, hour, minute) = local_parts(next);
1252        assert_eq!((hour, minute), (7, 30), "it fires at 07:30 local, not UTC");
1253    }
1254
1255    #[test]
1256    fn a_weekly_schedule_lands_on_the_named_day() {
1257        let now = 1_700_000_000_000i64;
1258        let s = Schedule::parse("weekly wed 09:00").unwrap();
1259        let next = s.next_due(now);
1260        assert!(next > now);
1261        assert!(next - now <= 8 * 86_400_000);
1262        assert_eq!(weekday_of(next), 3, "a Wednesday");
1263        let (_, _, _, hour, minute) = local_parts(next);
1264        assert_eq!((hour, minute), (9, 0));
1265    }
1266
1267    #[test]
1268    fn civil_dates_survive_leap_days_and_month_ends() {
1269        assert_eq!(days_from_civil(1970, 1, 1), 0);
1270        assert_eq!(civil_from_days(0), (1970, 1, 1));
1271        assert_eq!(
1272            days_from_civil(2024, 2, 29) + 1,
1273            days_from_civil(2024, 3, 1)
1274        );
1275        assert_eq!(civil_add_days(2024, 2, 28, 1), (2024, 2, 29));
1276        assert_eq!(civil_add_days(2024, 12, 31, 1), (2025, 1, 1));
1277        for d in [-1000i64, -1, 0, 1, 20_000, 30_000] {
1278            let (y, m, day) = civil_from_days(d);
1279            assert_eq!(days_from_civil(y, m, day), d, "round trip at {d}");
1280        }
1281    }
1282
1283    #[test]
1284    fn a_new_interval_job_runs_at_once_and_a_new_named_job_waits_for_its_hour() {
1285        let state = State::default();
1286        let now = 1_700_000_000_000i64;
1287        let every = job("tick", "every 30m");
1288        let daily = job("brief", "daily 07:30");
1289        let jobs = vec![every, daily];
1290        let due_now = due(&jobs, &state, now);
1291        assert_eq!(due_now.len(), 1, "only the interval job");
1292        assert_eq!(due_now[0].name, "tick");
1293    }
1294
1295    #[test]
1296    fn an_interval_job_is_due_again_only_after_its_interval() {
1297        let mut state = State::default();
1298        let now = 1_700_000_000_000i64;
1299        let jobs = vec![job("tick", "every 30m")];
1300        state.jobs.insert(
1301            "tick".into(),
1302            JobState {
1303                last_started_ms: Some(now - 29 * 60 * 1000),
1304                ..Default::default()
1305            },
1306        );
1307        assert!(due(&jobs, &state, now).is_empty(), "29 minutes is not 30");
1308        state.jobs.insert(
1309            "tick".into(),
1310            JobState {
1311                last_started_ms: Some(now - 31 * 60 * 1000),
1312                ..Default::default()
1313            },
1314        );
1315        assert_eq!(due(&jobs, &state, now).len(), 1);
1316    }
1317
1318    #[test]
1319    fn a_disabled_job_is_never_due_and_has_no_next_time() {
1320        let mut state = State::default();
1321        let mut j = job("tick", "every 1m");
1322        j.enabled = false;
1323        state.jobs.insert(
1324            "tick".into(),
1325            JobState {
1326                last_started_ms: Some(0),
1327                ..Default::default()
1328            },
1329        );
1330        let jobs = vec![j.clone()];
1331        assert!(due(&jobs, &state, 1_700_000_000_000).is_empty());
1332        assert_eq!(next_due_for(&j, &state, 1_700_000_000_000), None);
1333    }
1334
1335    #[test]
1336    fn a_jobs_schema_survives_the_file_it_is_written_to() {
1337        let root = temp_root();
1338        let mut shaped = job("shaped", "daily 07:30");
1339        // An inline schema, TOML-quoted: the same string `--schema` and the `cronjob_manage` tool
1340        // hand over, and the one the runner then hands to `resolve_schema`.
1341        shaped.schema = Some(r#"{"type":"object","required":["headline"]}"#.into());
1342        shaped.deliver = Some("~/notes/shaped.json".into());
1343        append_job(&root, &shaped).unwrap();
1344
1345        let text = std::fs::read_to_string(jobs_path(&root)).unwrap();
1346        assert!(
1347            text.contains("schema = \"{\\\"type\\\":\\\"object\\\""),
1348            "the schema is a TOML string, escaped: {text}"
1349        );
1350
1351        let jobs = load(&root).unwrap();
1352        assert_eq!(jobs.len(), 1);
1353        assert_eq!(jobs[0].schema, shaped.schema);
1354        // And a block without one still reads: `schema` is optional, not a new requirement.
1355        assert_eq!(job("plain", "every 1m").schema, None);
1356    }
1357
1358    #[test]
1359    fn the_jobs_file_is_appended_to_and_a_block_cut_out_without_touching_the_rest() {
1360        let root = temp_root();
1361        let first = job("first", "every 1m");
1362        let mut second = job("second", "daily 08:00");
1363        second.deliver = Some("~/notes/brief.md".into());
1364        second.skills = vec!["release-check".into()];
1365        append_job(&root, &first).unwrap();
1366        append_job(&root, &second).unwrap();
1367
1368        let text = std::fs::read_to_string(jobs_path(&root)).unwrap();
1369        assert!(text.contains("[[job]]"));
1370        assert!(text.contains("deliver = \"~/notes/brief.md\""));
1371
1372        let jobs = load(&root).unwrap();
1373        assert_eq!(jobs.len(), 2);
1374        assert_eq!(jobs[1].skills, ["release-check"]);
1375        assert_eq!(jobs[1].schedule, Schedule::Daily { hour: 8, minute: 0 });
1376
1377        assert!(remove_job(&root, "first").unwrap());
1378        let jobs = load(&root).unwrap();
1379        assert_eq!(jobs.len(), 1);
1380        assert_eq!(jobs[0].name, "second");
1381        assert!(!remove_job(&root, "nope").unwrap());
1382        let _ = std::fs::remove_dir_all(&root);
1383    }
1384
1385    #[test]
1386    fn replacing_a_block_keeps_the_file_around_it() {
1387        let root = temp_root();
1388        append_job(&root, &job("one", "every 1m")).unwrap();
1389        append_job(&root, &job("two", "every 2m")).unwrap();
1390        let path = jobs_path(&root);
1391        let before = std::fs::read_to_string(&path).unwrap();
1392        std::fs::write(&path, format!("{before}\n# keep me\n")).unwrap();
1393
1394        let mut paused = job("one", "every 1m");
1395        paused.enabled = false;
1396        replace_job(&root, &paused).unwrap();
1397
1398        let text = std::fs::read_to_string(&path).unwrap();
1399        assert!(text.contains("# keep me"), "the comment survives");
1400        assert!(text.contains("enabled = false"), "the change landed");
1401        let jobs = load(&root).unwrap();
1402        assert!(!jobs[0].enabled);
1403        assert!(jobs[1].enabled);
1404        assert!(replace_job(&root, &job("ghost", "every 1m")).is_err());
1405        let _ = std::fs::remove_dir_all(&root);
1406    }
1407
1408    #[test]
1409    fn two_jobs_cannot_share_a_name() {
1410        let root = temp_root();
1411        append_job(&root, &job("same", "every 1m")).unwrap();
1412        let err = append_job(&root, &job("same", "every 2m"))
1413            .unwrap_err()
1414            .to_string();
1415        assert!(err.contains("already exists"), "{err}");
1416        let _ = std::fs::remove_dir_all(&root);
1417    }
1418
1419    #[test]
1420    fn a_job_with_an_empty_prompt_is_refused() {
1421        let root = temp_root();
1422        std::fs::create_dir_all(root.join("cron")).unwrap();
1423        std::fs::write(
1424            jobs_path(&root),
1425            "[[job]]\nname = \"x\"\nschedule = \"every 1m\"\nprompt = \"  \"\n",
1426        )
1427        .unwrap();
1428        // A job that cannot run is refused, not invented — and since `#405` one such block is a
1429        // skipped job with a report rather than a failure for the whole file.
1430        let (jobs, problems) = load_reporting(&root).unwrap();
1431        assert!(jobs.is_empty(), "a job with nothing to say is not a job");
1432        assert_eq!(problems.len(), 1, "{problems:?}");
1433        assert!(problems[0].contains("empty prompt"), "{problems:?}");
1434        let _ = std::fs::remove_dir_all(&root);
1435    }
1436
1437    #[test]
1438    fn an_unknown_key_is_refused_rather_than_silently_ignored() {
1439        let root = temp_root();
1440        std::fs::create_dir_all(root.join("cron")).unwrap();
1441        std::fs::write(
1442            jobs_path(&root),
1443            "[[job]]\nname = \"x\"\nschedule = \"every 1m\"\nprompt = \"p\"\nsechdule = \"every 2m\"\n",
1444        )
1445        .unwrap();
1446        assert!(load(&root).is_err(), "a typo in a key must not pass");
1447        let _ = std::fs::remove_dir_all(&root);
1448    }
1449
1450    #[test]
1451    fn state_round_trips_and_a_missing_file_is_empty_state() {
1452        let root = temp_root();
1453        assert!(load_state(&root).unwrap().jobs.is_empty());
1454        let mut state = State::default();
1455        state.jobs.insert(
1456            "tick".into(),
1457            JobState {
1458                last_started_ms: Some(5),
1459                last_finished_ms: Some(6),
1460                last_outcome: Some("ok".into()),
1461                runs: 1,
1462            },
1463        );
1464        save_state(&root, &state).unwrap();
1465        let back = load_state(&root).unwrap();
1466        assert_eq!(back.get("tick").runs, 1);
1467        assert_eq!(back.get("tick").last_outcome.as_deref(), Some("ok"));
1468        let _ = std::fs::remove_dir_all(&root);
1469    }
1470
1471    /// `#405`: one malformed block used to be an `Err` for the whole file, so a typo in a job
1472    /// nobody was looking at stopped every other job — and the only trace was a failed systemd
1473    /// unit. A bad block is skipped, named, and the rest still run. The schedule error has to carry
1474    /// the job's own name: `unrecognised schedule "evry 5m"` in a file of twelve blocks is a hunt.
1475    #[test]
1476    fn a_broken_job_is_skipped_and_named_instead_of_stopping_every_job() {
1477        let root = temp_root();
1478        std::fs::create_dir_all(root.join("cron")).unwrap();
1479        std::fs::write(
1480            jobs_path(&root),
1481            "[[job]]\nname = \"good\"\nschedule = \"every 1h\"\nprompt = \"say something\"\n\n\
1482             [[job]]\nname = \"typo\"\nschedule = \"evry 5m\"\nprompt = \"never mind\"\n",
1483        )
1484        .unwrap();
1485
1486        let (jobs, problems) = load_reporting(&root).unwrap();
1487        assert_eq!(jobs.len(), 1, "the good job still loads: {problems:?}");
1488        assert_eq!(jobs[0].name, "good");
1489        assert_eq!(problems.len(), 1, "{problems:?}");
1490        assert!(
1491            problems[0].contains("typo"),
1492            "the problem names the job, not just the schedule: {problems:?}"
1493        );
1494        assert!(
1495            problems[0].contains("evry 5m"),
1496            "and quotes what it could not parse: {problems:?}"
1497        );
1498        // The plain reader is the same list, without the report.
1499        assert_eq!(load(&root).unwrap().len(), 1);
1500        let _ = std::fs::remove_dir_all(&root);
1501    }
1502
1503    /// `#406`: `every <N>d` multiplied without checking, and a release build has no overflow
1504    /// checks — `every 144115188075855873d` wrapped to exactly 86 400 seconds and passed as
1505    /// `every 1d`, i.e. a schedule somebody wrote as "never" silently ran daily.
1506    #[test]
1507    fn an_interval_too_large_to_count_is_refused_not_wrapped() {
1508        assert!(
1509            Schedule::parse("every 144115188075855873d").is_err(),
1510            "an interval that wraps is refused"
1511        );
1512        assert!(Schedule::parse("every 99999999999999999999d").is_err());
1513        assert_eq!(
1514            Schedule::parse("every 2h").unwrap(),
1515            Schedule::Every(7_200),
1516            "an ordinary interval still parses"
1517        );
1518        // And the arithmetic that would have wrapped is saturating, so a `next_due` on an
1519        // interval nobody can represent reports the end of time rather than a moment in the past.
1520        let unrepresentable = Schedule::Every(i64::MAX as u64 / 1000 + 1);
1521        assert_eq!(unrepresentable.next_due(0), i64::MAX);
1522        assert_eq!(
1523            Schedule::Every(3_600).next_due(0),
1524            3_600_000,
1525            "and is exact for a real one"
1526        );
1527    }
1528
1529    /// `#407`: staleness is the lock file's mtime, which was written once and never refreshed, so
1530    /// a tick that legitimately ran past the stale mark was taken for an abandoned one. The next
1531    /// minute's tick then started with its own list and ran the jobs the first had not reached —
1532    /// and when the first finished, its `Drop` deleted the *second* tick's file.
1533    #[test]
1534    fn a_long_tick_stays_alive_and_a_tick_that_lost_the_lock_does_not_delete_it() {
1535        let root = temp_root();
1536        let now = crate::session::now_ms() as i64;
1537        let mut tick = lock(&root, now).unwrap().expect("first tick takes it");
1538        let path = tick.path().to_path_buf();
1539
1540        // Proof of life keeps it fresh: the file's mtime moves and the content is still ours.
1541        assert!(tick.touch(now + 60_000), "a live tick can say so");
1542        let modified = std::fs::metadata(&path).and_then(|m| m.modified()).unwrap();
1543        let fresh = std::time::SystemTime::now()
1544            .duration_since(modified)
1545            .expect("the file is not from the future");
1546        assert!(
1547            fresh.as_secs() < 60,
1548            "touching refreshes the mtime, which is what staleness reads"
1549        );
1550
1551        // Another tick takes the lock over. Ours is now a stale view of a file it does not own:
1552        // it cannot touch it, and its `Drop` must leave the new holder's file alone.
1553        std::fs::write(&path, "999999999999\n").unwrap();
1554        assert!(!tick.touch(now + 120_000), "a taken-over tick stops");
1555        drop(tick);
1556        assert!(
1557            path.exists(),
1558            "the new holder's lock survives the old tick's Drop"
1559        );
1560        let _ = std::fs::remove_dir_all(&root);
1561    }
1562
1563    #[test]
1564    fn a_second_tick_does_not_take_the_lock_and_an_abandoned_one_does() {
1565        let root = temp_root();
1566        let now = crate::session::now_ms() as i64;
1567        let held = lock(&root, now).unwrap().expect("first tick takes it");
1568        assert!(lock(&root, now).unwrap().is_none(), "second tick waits");
1569        drop(held);
1570        assert!(
1571            lock(&root, now).unwrap().is_some(),
1572            "the lock is released when the tick ends"
1573        );
1574
1575        // Pretend the process died holding it: age the file past the stale mark.
1576        let path = root.join("state").join("cron.lock");
1577        drop(std::fs::File::create(&path).unwrap());
1578        let old =
1579            std::time::SystemTime::now() - std::time::Duration::from_millis(STALE_LOCK_MS + 5_000);
1580        filetime_set(&path, old);
1581        let taken = lock(&root, now)
1582            .unwrap()
1583            .expect("a stale lock is taken over");
1584        assert!(taken.took_over_stale);
1585        let _ = std::fs::remove_dir_all(&root);
1586    }
1587
1588    fn filetime_set(path: &Path, when: std::time::SystemTime) {
1589        // No dependency for this: `utimensat` through libc, unix only. Elsewhere the test is a
1590        // no-op and the stale-lock path is covered by the branch above.
1591        #[cfg(unix)]
1592        {
1593            use std::os::unix::ffi::OsStrExt;
1594            let c = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
1595            let times = [
1596                libc::timespec {
1597                    tv_sec: when
1598                        .duration_since(std::time::UNIX_EPOCH)
1599                        .map(|d| d.as_secs() as i64)
1600                        .unwrap_or(0),
1601                    tv_nsec: 0,
1602                },
1603                libc::timespec {
1604                    tv_sec: when
1605                        .duration_since(std::time::UNIX_EPOCH)
1606                        .map(|d| d.as_secs() as i64)
1607                        .unwrap_or(0),
1608                    tv_nsec: 0,
1609                },
1610            ];
1611            // SAFETY: a valid C string and an array of exactly two timespecs, as the call
1612            // requires.
1613            unsafe {
1614                libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), 0);
1615            }
1616        }
1617        #[cfg(not(unix))]
1618        let _ = (path, when);
1619    }
1620
1621    #[test]
1622    fn runs_are_written_newest_first() {
1623        let root = temp_root();
1624        for ms in [1, 2, 3] {
1625            write_run(&root, "tick", ms, "hello").unwrap();
1626        }
1627        let runs = recent_runs(&root, "tick", 10);
1628        assert_eq!(runs.len(), 3);
1629        assert!(runs[0].to_string_lossy().contains("3.md"), "newest first");
1630        assert_eq!(recent_runs(&root, "nothing", 10).len(), 0);
1631        let _ = std::fs::remove_dir_all(&root);
1632    }
1633
1634    #[test]
1635    fn a_job_name_becomes_a_directory_so_it_is_held_to_an_alphabet() {
1636        for bad in ["..", "a/b", "with space", ""] {
1637            assert!(validate_job_name(bad).is_err(), "{bad:?} must be refused");
1638        }
1639        assert!(validate_job_name("nightly-backup_2").is_ok());
1640    }
1641
1642    #[test]
1643    fn a_view_carries_the_next_fire_and_what_last_ran() {
1644        let root = temp_root();
1645        let job = job("brief", "every 30m");
1646        append_job(&root, &job).unwrap();
1647        let now = 1_700_000_000_000_i64;
1648
1649        let fresh = views(&root, now).unwrap();
1650        assert_eq!(fresh.len(), 1);
1651        assert_eq!(fresh[0].schedule, "every 30m");
1652        // Never run and an interval: due immediately, which is what `due` says too.
1653        assert_eq!(fresh[0].next_ms, Some(now));
1654        assert_eq!(fresh[0].last_outcome, None);
1655        assert_eq!(fresh[0].runs, 0);
1656
1657        let mut state = load_state(&root).unwrap();
1658        let entry = state.jobs.entry("brief".into()).or_default();
1659        entry.last_started_ms = Some(now);
1660        entry.last_finished_ms = Some(now + 1000);
1661        entry.last_outcome = Some("ok".into());
1662        entry.runs = 3;
1663        save_state(&root, &state).unwrap();
1664
1665        let after = views(&root, now + 1000).unwrap();
1666        assert_eq!(after[0].runs, 3);
1667        assert_eq!(after[0].last_outcome.as_deref(), Some("ok"));
1668        assert_eq!(after[0].next_ms, Some(now + 30 * 60 * 1000));
1669        let _ = std::fs::remove_dir_all(&root);
1670    }
1671
1672    #[test]
1673    fn a_schedule_a_job_is_shown_with_is_the_one_an_editor_can_submit_back() {
1674        for text in [
1675            "every 30m",
1676            "every 2h",
1677            "hourly",
1678            "daily 07:30",
1679            "weekly mon 09:00",
1680        ] {
1681            let draft = Draft {
1682                name: "brief".into(),
1683                schedule: text.into(),
1684                prompt: "p".into(),
1685                ..Default::default()
1686            };
1687            let job = draft.to_job().unwrap();
1688            // What the view shows is what comes back to `to_job` as the same schedule.
1689            let shown = Draft::from_job(&job);
1690            assert_eq!(shown.schedule, job.schedule.describe());
1691            let again = shown.to_job().unwrap();
1692            assert_eq!(again.schedule, job.schedule, "{text} did not round-trip");
1693        }
1694        // And the one that means an hour twice says so once: `hourly` is `every 1h`.
1695        let hourly = Schedule::parse("hourly").unwrap();
1696        assert_eq!(hourly.describe(), "every 1h");
1697    }
1698
1699    #[test]
1700    fn a_draft_refuses_a_job_nothing_could_run() {
1701        let base = Draft {
1702            name: "brief".into(),
1703            schedule: "hourly".into(),
1704            prompt: "p".into(),
1705            ..Default::default()
1706        };
1707        assert!(base.to_job().is_ok());
1708
1709        let empty_prompt = Draft {
1710            prompt: "  \n ".into(),
1711            ..base.clone()
1712        };
1713        assert!(empty_prompt
1714            .to_job()
1715            .unwrap_err()
1716            .to_string()
1717            .contains("prompt"));
1718
1719        let bad_schedule = Draft {
1720            schedule: "every tuesday".into(),
1721            ..base.clone()
1722        };
1723        assert_eq!(
1724            bad_schedule.to_job().unwrap_err().to_string(),
1725            Schedule::parse("every tuesday").unwrap_err().to_string(),
1726            "the parser's own sentence, not a paraphrase"
1727        );
1728
1729        let bad_name = Draft {
1730            name: "a/b".into(),
1731            ..base.clone()
1732        };
1733        assert!(bad_name.to_job().is_err());
1734
1735        let missing_dir = Draft {
1736            workdir: Some("/nonexistent/eclipse-cron-test".into()),
1737            ..base
1738        };
1739        let why = missing_dir.to_job().unwrap_err().to_string();
1740        assert!(why.contains("not a directory"), "{why}");
1741    }
1742
1743    #[test]
1744    fn a_draft_keeps_being_enabled_unless_it_says_otherwise() {
1745        // A create that says nothing about `enabled` gets a job that fires: the default belongs in
1746        // the shared struct, not in whichever front end remembered to set it.
1747        let draft: Draft = serde_json::from_value(serde_json::json!({
1748            "name": "brief",
1749            "schedule": "hourly",
1750            "prompt": "p",
1751        }))
1752        .unwrap();
1753        assert!(draft.enabled);
1754        assert!(draft.to_job().unwrap().enabled);
1755    }
1756
1757    #[test]
1758    fn a_run_reads_back_with_its_answer_and_how_much_more_there_is() {
1759        let root = temp_root();
1760        let header = "# brief — 2026-11-30 07:30\n\nschedule every 30m\n\n---\n\n";
1761        write_run(
1762            &root,
1763            "brief",
1764            1_700_000_000_000,
1765            &format!("{header}it ran\n"),
1766        )
1767        .unwrap();
1768
1769        let long = format!("{header}{}", "x".repeat(RUN_TEXT_CAP + 500));
1770        write_run(&root, "brief", 1_700_000_100_000, &long).unwrap();
1771
1772        let runs = runs(&root, "brief", 5);
1773        assert_eq!(runs.len(), 2);
1774        // Newest first, and the answer is the first line after the tick's header.
1775        assert_eq!(runs[0].at_ms, 1_700_000_100_000);
1776        assert_eq!(
1777            runs[0].answer.chars().count(),
1778            ANSWER_CAP + 1,
1779            "the answer is the first line, cut at the cap and marked"
1780        );
1781        assert!(runs[0].answer.ends_with('…'), "{}", runs[0].answer);
1782        assert!(runs[0].answer.starts_with("xxx"));
1783        assert!(runs[0].truncated, "a capped text must say it is capped");
1784        assert_eq!(runs[0].chars, long.chars().count());
1785        assert_eq!(runs[0].text.chars().count(), RUN_TEXT_CAP);
1786
1787        assert_eq!(runs[1].answer, "it ran");
1788        assert!(!runs[1].truncated);
1789        assert_eq!(runs[1].at, iso_local(1_700_000_000_000));
1790        let _ = std::fs::remove_dir_all(&root);
1791    }
1792
1793    #[test]
1794    fn a_job_switched_off_leaves_its_prompt_and_schedule_where_they_were() {
1795        let root = temp_root();
1796        append_job(&root, &job("brief", "every 30m")).unwrap();
1797        let off = set_enabled(&root, "brief", false)
1798            .unwrap()
1799            .expect("the job");
1800        assert!(!off.enabled);
1801
1802        let on_disk = load(&root).unwrap();
1803        assert_eq!(on_disk.len(), 1);
1804        assert_eq!(on_disk[0].prompt, "say something");
1805        assert_eq!(on_disk[0].schedule, Schedule::parse("every 30m").unwrap());
1806        assert!(!on_disk[0].enabled);
1807        // A disabled job is not due and has no next fire, which is what the pane shows.
1808        assert!(due(&on_disk, &State::default(), 1_700_000_000_000).is_empty());
1809        assert_eq!(
1810            next_due_for(&on_disk[0], &State::default(), 1_700_000_000_000),
1811            None
1812        );
1813
1814        assert!(set_enabled(&root, "nothing", false).unwrap().is_none());
1815        assert!(set_enabled(&root, "brief", true).unwrap().unwrap().enabled);
1816        let _ = std::fs::remove_dir_all(&root);
1817    }
1818}