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.
728///
729/// That second case needs an anchor, and asking every caller to remember [`seed_first_seen`] is how
730/// a `daily` job came to never fire at all (`#561`). So the first sighting is seeded here: a job
731/// this tick has no history for is anchored at this tick, `due` still answers "not yet", and the
732/// next tick has something to measure from. The state is `&mut` for that reason alone.
733pub fn due<'a>(jobs: &'a [Job], state: &mut State, now_ms: i64) -> Vec<&'a Job> {
734    seed_first_seen(jobs, state, now_ms);
735    jobs.iter()
736        .filter(|j| j.enabled)
737        .filter(|j| {
738            let entry = state.jobs.get(&j.name);
739            let last = entry.and_then(|e| e.last_started_ms);
740            match (last, j.schedule) {
741                (None, Schedule::Every(_)) => true,
742                (None, _) => false,
743                (Some(last), schedule) => now_ms >= schedule.next_due(last),
744            }
745        })
746        .collect()
747}
748
749/// Give every job a state entry the first time a tick sees it (`#561`).
750///
751/// A calendar schedule is due *relative to its last fire*, and a job added a minute ago has none —
752/// so `due` answered "never" for `daily`, `weekly` and cron jobs, `cron add` and the dashboard's
753/// form both produced a job that could not run, and `next_due_for` kept promising a next time that
754/// rolled forward on every tick. The first sighting is the seed: an unrun calendar job is anchored
755/// at the moment it was first seen, so its next named moment is its first fire and a 07:30 briefing
756/// installed at noon runs tomorrow morning rather than never.
757///
758/// An interval job is left with no anchor on purpose: `due` fires it at once, which is the rule for
759/// a schedule that only needs "now" to be meaningful.
760///
761/// Returns the names it seeded — the tick has to *save* the state for this to hold, and saying so
762/// is also how the caller knows whether there is anything to write at all.
763pub fn seed_first_seen(jobs: &[Job], state: &mut State, now_ms: i64) -> Vec<String> {
764    let mut seeded = Vec::new();
765    for job in jobs.iter().filter(|j| j.enabled) {
766        if state.jobs.contains_key(&job.name) {
767            continue;
768        }
769        let mut entry = JobState::default();
770        if !matches!(job.schedule, Schedule::Every(_)) {
771            entry.last_started_ms = Some(now_ms);
772        }
773        state.jobs.insert(job.name.clone(), entry);
774        seeded.push(job.name.clone());
775    }
776    seeded
777}
778
779/// When a job fires next, given what has run. `None` for a disabled job.
780pub fn next_due_for(job: &Job, state: &State, now_ms: i64) -> Option<i64> {
781    if !job.enabled {
782        return None;
783    }
784    match state.jobs.get(&job.name).and_then(|e| e.last_started_ms) {
785        None => match job.schedule {
786            Schedule::Every(_) => Some(now_ms),
787            schedule => Some(schedule.next_due(now_ms)),
788        },
789        Some(last) => {
790            let mut next = job.schedule.next_due(last);
791            // A tick that was missed while the machine was off is due at the next tick, not a
792            // burst of catch-up runs: one prompt per job per tick.
793            if next < now_ms && matches!(job.schedule, Schedule::Every(_)) {
794                next = now_ms;
795            }
796            Some(next)
797        }
798    }
799}
800
801// ---------------------------------------------------------------------------------------------
802// The tick lock
803// ---------------------------------------------------------------------------------------------
804
805/// How long a lock may be ignored before it is taken as abandoned.
806///
807/// A run that hangs cannot be waited on forever by a timer that fires every minute; after this
808/// the next tick takes the lock and says so in its output. Long enough that a slow model call
809/// is not cut off, short enough that a wedged one does not go unnoticed for a day.
810///
811/// `#566`: the lock is an OS `flock` now, so this is no longer what decides between two live
812/// ticks — the kernel does, and a holder that dies releases it by dying. It still names the age at
813/// which a takeover is *reported*, because a lock file that old is nearly always a leftover.
814pub const STALE_LOCK_MS: u64 = 30 * 60 * 1000;
815
816/// Held for the duration of one tick, so two timers (a systemd one and a hand-run one) cannot
817/// run the same job twice.
818pub struct Lock {
819    path: PathBuf,
820    /// True when this tick took over a lock file old enough to be a leftover, so it can say so.
821    pub took_over_stale: bool,
822    /// What this holder last wrote. The file's mtime is the staleness signal and its content is
823    /// "this holder is still here", so a `Drop` that removes the file has to know whether the file
824    /// is still the one it wrote (`#407`).
825    stamp: String,
826    /// The open file the kernel lock lives on (`#566`). Held only so the `flock` outlives the tick
827    /// — dropping it is what releases the lock.
828    _file: std::fs::File,
829}
830
831impl Lock {
832    pub fn path(&self) -> &Path {
833        &self.path
834    }
835
836    /// Say this tick is still working, between jobs.
837    ///
838    /// `#407`: staleness is judged from the file's mtime, which was set once and never refreshed,
839    /// so a tick that legitimately ran past `STALE_LOCK_MS` was taken for an abandoned one — the
840    /// next minute's tick took the lock and ran the jobs this one had not reached yet, in both.
841    /// Returns false when the file is no longer ours, which means another tick has taken over and
842    /// this one must stop rather than fight over jobs.
843    pub fn touch(&mut self, now_ms: i64) -> bool {
844        if std::fs::read_to_string(&self.path).ok().as_deref() != Some(self.stamp.as_str()) {
845            return false;
846        }
847        let next = format!("{now_ms}\n");
848        if std::fs::write(&self.path, &next).is_err() {
849            return false;
850        }
851        self.stamp = next;
852        true
853    }
854}
855
856impl Drop for Lock {
857    fn drop(&mut self) {
858        // Only the lock this tick still holds. A tick whose lock was taken over used to delete the
859        // new holder's file on the way out, which let a third tick start beside it (`#407`).
860        if std::fs::read_to_string(&self.path).ok().as_deref() == Some(self.stamp.as_str()) {
861            let _ = std::fs::remove_file(&self.path);
862        }
863    }
864}
865
866pub fn lock(root: &Path, now_ms: i64) -> Result<Option<Lock>> {
867    let path = root.join("state").join("cron.lock");
868    if let Some(dir) = path.parent() {
869        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
870    }
871    // `#566`: the file is opened once, kept, and an OS `flock` decides who holds it. Age and a
872    // plain `write` were a check-then-act — two ticks in the same millisecond both saw an old
873    // file, both wrote it, and both ran every due job, while each one's `Drop` could delete the
874    // other's lock because their stamps were identical. The kernel's lock is exclusive per open
875    // file description and is released by the holder dying, which a stamp file cannot do.
876    #[cfg(not(unix))]
877    let refused = path.exists() && age_ms(&path, now_ms) < STALE_LOCK_MS;
878    let mut file = std::fs::OpenOptions::new()
879        .read(true)
880        .write(true)
881        .create(true)
882        // Not truncated on open: the content is only cleared once the lock is ours, so a tick that
883        // loses the race leaves the holder's stamp untouched.
884        .truncate(false)
885        .open(&path)
886        .map_err(|e| Error::io(&path, e))?;
887    #[cfg(not(unix))]
888    if refused {
889        return Ok(None);
890    }
891    if !try_lock_exclusive(&file) {
892        return Ok(None);
893    }
894    let age = age_ms(&path, now_ms);
895    let stamp = format!("{now_ms}\n");
896    {
897        use std::io::Write;
898        file.set_len(0).map_err(|e| Error::io(&path, e))?;
899        write!(file, "{stamp}").map_err(|e| Error::io(&path, e))?;
900    }
901    Ok(Some(Lock {
902        path,
903        _file: file,
904        took_over_stale: age >= STALE_LOCK_MS,
905        stamp,
906    }))
907}
908
909/// How long ago the lock file was written, in milliseconds, clamped at zero (`#407`: a file a few
910/// milliseconds ahead of our clock used to read as 584 years old).
911fn age_ms(path: &Path, now_ms: i64) -> u64 {
912    std::fs::metadata(path)
913        .and_then(|m| m.modified())
914        .ok()
915        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
916        .map(|d| now_ms.saturating_sub(d.as_millis() as i64).max(0) as u64)
917        .unwrap_or(0)
918}
919
920/// Ask the kernel whether anyone else holds this file; a refusal is the answer, not an error.
921#[cfg(unix)]
922fn try_lock_exclusive(file: &std::fs::File) -> bool {
923    use std::os::unix::io::AsRawFd;
924    // SAFETY: the fd belongs to this live `File`, the call takes no pointers, and `LOCK_NB` makes
925    // it a question rather than a wait. The lock lives as long as the file description does.
926    unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) == 0 }
927}
928
929/// Without `flock` the stamp protocol is all there is; `refused` above decides.
930#[cfg(not(unix))]
931fn try_lock_exclusive(_file: &std::fs::File) -> bool {
932    true
933}
934
935/// The run log for one execution: `<root>/cron/runs/<job>/<ms>.md`.
936pub fn write_run(root: &Path, job: &str, started_ms: i64, body: &str) -> Result<PathBuf> {
937    let dir = runs_dir(root, job);
938    std::fs::create_dir_all(&dir).map_err(|e| Error::io(&dir, e))?;
939    let path = dir.join(format!("{started_ms}.md"));
940    std::fs::write(&path, body).map_err(|e| Error::io(&path, e))?;
941    Ok(path)
942}
943
944/// The most recent runs of a job, newest first.
945pub fn recent_runs(root: &Path, job: &str, limit: usize) -> Vec<PathBuf> {
946    let dir = runs_dir(root, job);
947    let Ok(entries) = std::fs::read_dir(&dir) else {
948        return Vec::new();
949    };
950    let mut paths: Vec<PathBuf> = entries
951        .flatten()
952        .map(|e| e.path())
953        .filter(|p| p.extension().map(|e| e == "md").unwrap_or(false))
954        .collect();
955    paths.sort();
956    paths.reverse();
957    paths.truncate(limit);
958    paths
959}
960
961// ---------------------------------------------------------------------------------------------
962// A job as a surface reads it
963// ---------------------------------------------------------------------------------------------
964
965/// How much of a run's text a surface is handed. A job that answers in ten thousand words is a
966/// job whose log is an essay; the page shows the beginning and says the rest is on disk in
967/// `path`, rather than shipping a megabyte of JSON to a browser to render four lines of it.
968pub const RUN_TEXT_CAP: usize = 4000;
969
970/// How much of a run's first line fits in a table: enough to know what happened, short enough to
971/// sit in one row. The rest is in [`RunView::text`].
972pub const ANSWER_CAP: usize = 160;
973
974/// One job, plus what has run and when it fires next.
975///
976/// This is the shape `cron list --json` prints and the dashboard renders. It is deliberately not
977/// the file's shape: the store's keys (`[[job]]` in TOML) stay where they are so a field renamed
978/// for a page cannot move a key in a file somebody wrote by hand.
979#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
980pub struct JobView {
981    pub name: String,
982    /// As [`Schedule::parse`] accepts it back — the same string an editor shows and submits, so a
983    /// page never has to know that `hourly` and `every 1h` are one schedule.
984    pub schedule: String,
985    pub enabled: bool,
986    pub prompt: String,
987    pub route: Option<String>,
988    pub workdir: Option<String>,
989    pub skills: Vec<String>,
990    pub deliver: Option<String>,
991    pub schema: Option<String>,
992    /// The next fire, or `None` for a disabled job.
993    pub next_ms: Option<i64>,
994    pub last_started_ms: Option<i64>,
995    pub last_finished_ms: Option<i64>,
996    /// `ok`, `failed`, or the first line of what went wrong.
997    pub last_outcome: Option<String>,
998    pub runs: u64,
999}
1000
1001pub fn view(job: &Job, state: &State, now_ms: i64) -> JobView {
1002    let s = state.get(&job.name);
1003    JobView {
1004        name: job.name.clone(),
1005        schedule: job.schedule.describe(),
1006        enabled: job.enabled,
1007        prompt: job.prompt.clone(),
1008        route: job.route.clone(),
1009        workdir: job.workdir.clone(),
1010        skills: job.skills.clone(),
1011        deliver: job.deliver.clone(),
1012        schema: job.schema.clone(),
1013        next_ms: next_due_for(job, state, now_ms),
1014        last_started_ms: s.last_started_ms,
1015        last_finished_ms: s.last_finished_ms,
1016        last_outcome: s.last_outcome,
1017        runs: s.runs,
1018    }
1019}
1020
1021/// Every job, in the order the file has them, as a surface reads them.
1022pub fn views(root: &Path, now_ms: i64) -> Result<Vec<JobView>> {
1023    let state = load_state(root)?;
1024    Ok(load(root)?
1025        .iter()
1026        .map(|job| view(job, &state, now_ms))
1027        .collect())
1028}
1029
1030/// One run of a job, as a surface reads it.
1031#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1032pub struct RunView {
1033    pub at_ms: i64,
1034    /// The same moment for a person, in local time.
1035    pub at: String,
1036    /// The first non-empty line of the answer — what a table column shows.
1037    pub answer: String,
1038    /// The whole text, capped at [`RUN_TEXT_CAP`] characters.
1039    pub text: String,
1040    /// How long the whole text is, so a truncated `text` says so instead of just stopping.
1041    pub chars: usize,
1042    pub truncated: bool,
1043    pub path: String,
1044}
1045
1046/// `2026-11-29 07:30`, in local time.
1047pub fn iso_local(ms: i64) -> String {
1048    let (y, mo, d, h, mi) = local_parts(ms);
1049    format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02}")
1050}
1051
1052/// The newest runs of one job, read off the files the tick wrote.
1053pub fn runs(root: &Path, job: &str, limit: usize) -> Vec<RunView> {
1054    recent_runs(root, job, limit)
1055        .into_iter()
1056        .map(|path| {
1057            let body = std::fs::read_to_string(&path).unwrap_or_default();
1058            let at_ms = path
1059                .file_stem()
1060                .and_then(|s| s.to_str())
1061                .and_then(|s| s.parse::<i64>().ok())
1062                .unwrap_or(0);
1063            // Everything after the first `---` is the answer; before it is the header the tick
1064            // wrote (`# name — when`, the schedule, the route it took).
1065            // One line, short enough to sit in a table cell: a job whose answer opens with a
1066            // paragraph of prose still has to fit beside a schedule and a date. What is cut is
1067            // marked, and the whole thing is in `text`.
1068            let first = body
1069                .split_once("---\n")
1070                .map(|(_, rest)| rest)
1071                .unwrap_or(&body)
1072                .lines()
1073                .find(|l| !l.trim().is_empty())
1074                .unwrap_or("(no output)")
1075                .trim();
1076            let answer = if first.chars().count() > ANSWER_CAP {
1077                let mut cut: String = first.chars().take(ANSWER_CAP).collect();
1078                cut.push('…');
1079                cut
1080            } else {
1081                first.to_string()
1082            };
1083            let chars = body.chars().count();
1084            let text: String = if chars > RUN_TEXT_CAP {
1085                body.chars().take(RUN_TEXT_CAP).collect()
1086            } else {
1087                body.clone()
1088            };
1089            RunView {
1090                at_ms,
1091                at: iso_local(at_ms),
1092                answer,
1093                text,
1094                chars,
1095                truncated: chars > RUN_TEXT_CAP,
1096                path: path.display().to_string(),
1097            }
1098        })
1099        .collect()
1100}
1101
1102// ---------------------------------------------------------------------------------------------
1103// What a surface may write
1104// ---------------------------------------------------------------------------------------------
1105
1106fn yes() -> bool {
1107    true
1108}
1109
1110/// A job as a surface submits it: `cron add`'s arguments, or a page's form.
1111///
1112/// One struct and one set of checks, because the two front ends must not disagree about what a job
1113/// is. `enabled` is the only field a create does not have to mention; everything else is the
1114/// caller's, and the errors are the parsers' own words so the two surfaces say the same sentence.
1115#[derive(Debug, Clone, Deserialize)]
1116pub struct Draft {
1117    pub name: String,
1118    pub schedule: String,
1119    pub prompt: String,
1120    #[serde(default)]
1121    pub deliver: Option<String>,
1122    #[serde(default)]
1123    pub route: Option<String>,
1124    #[serde(default)]
1125    pub workdir: Option<String>,
1126    #[serde(default)]
1127    pub skills: Vec<String>,
1128    #[serde(default)]
1129    pub schema: Option<String>,
1130    #[serde(default = "yes")]
1131    pub enabled: bool,
1132}
1133
1134impl Default for Draft {
1135    fn default() -> Self {
1136        Self {
1137            name: String::new(),
1138            schedule: String::new(),
1139            prompt: String::new(),
1140            deliver: None,
1141            route: None,
1142            workdir: None,
1143            skills: Vec::new(),
1144            schema: None,
1145            enabled: true,
1146        }
1147    }
1148}
1149
1150impl Draft {
1151    /// The job this describes, or why it does not describe one.
1152    ///
1153    /// A prompt is required and a schedule is parsed here rather than at 07:30 in a log nobody
1154    /// reads; a `workdir` is checked to be a directory for the same reason — a workspace that is a
1155    /// typo is a job whose files land somewhere else, or nowhere.
1156    pub fn to_job(&self) -> Result<Job> {
1157        validate_job_name(&self.name)?;
1158        if self.prompt.trim().is_empty() {
1159            return Err(Error::Config("a job needs a prompt".to_string()));
1160        }
1161        let schedule = Schedule::parse(&self.schedule)?;
1162        if let Some(dir) = &self.workdir {
1163            let path = expand_tilde(dir);
1164            if !path.is_dir() {
1165                return Err(Error::Config(format!(
1166                    "`{dir}` is not a directory, so the job would have no workspace"
1167                )));
1168            }
1169        }
1170        Ok(Job {
1171            name: self.name.clone(),
1172            schedule,
1173            prompt: self.prompt.clone(),
1174            enabled: self.enabled,
1175            route: self.route.clone(),
1176            workdir: self.workdir.clone(),
1177            skills: self.skills.clone(),
1178            deliver: self.deliver.clone(),
1179            schema: self.schema.clone(),
1180        })
1181    }
1182
1183    /// The same job as [`Draft`], for editing: what an editor loads into its form.
1184    pub fn from_job(job: &Job) -> Self {
1185        Self {
1186            name: job.name.clone(),
1187            schedule: job.schedule.describe(),
1188            prompt: job.prompt.clone(),
1189            deliver: job.deliver.clone(),
1190            route: job.route.clone(),
1191            workdir: job.workdir.clone(),
1192            skills: job.skills.clone(),
1193            schema: job.schema.clone(),
1194            enabled: job.enabled,
1195        }
1196    }
1197}
1198
1199/// `~/x` and `$HOME/x` as the path they mean.
1200///
1201/// The tick resolves a job's own directory the same way (`cron_cli::expand_path`), so a `workdir`
1202/// that is a directory when it is checked is a directory when it is used.
1203pub fn expand_tilde(text: &str) -> PathBuf {
1204    if let Some(rest) = text.strip_prefix("~/") {
1205        if let Some(home) = crate::config::process_env("HOME") {
1206            return PathBuf::from(home).join(rest);
1207        }
1208    }
1209    PathBuf::from(text)
1210}
1211
1212/// Turn a job on or off, in place. `false` when no job has that name.
1213pub fn set_enabled(root: &Path, name: &str, enabled: bool) -> Result<Option<Job>> {
1214    let jobs = load(root)?;
1215    let Some(mut job) = jobs.into_iter().find(|j| j.name == name) else {
1216        return Ok(None);
1217    };
1218    if job.enabled == enabled {
1219        return Ok(Some(job));
1220    }
1221    job.enabled = enabled;
1222    replace_job(root, &job)?;
1223    // Loading it back is the check that the file it wrote is a file this build can read.
1224    Ok(load(root)?.into_iter().find(|j| j.name == name))
1225}
1226
1227#[cfg(test)]
1228mod tests {
1229    use super::*;
1230
1231    fn job(name: &str, schedule: &str) -> Job {
1232        Job {
1233            name: name.into(),
1234            schedule: Schedule::parse(schedule).unwrap(),
1235            prompt: "say something".into(),
1236            enabled: true,
1237            route: None,
1238            workdir: None,
1239            skills: Vec::new(),
1240            deliver: None,
1241            schema: None,
1242        }
1243    }
1244
1245    /// A directory no other test in this run can be using, removed when the test ends.
1246    fn temp_root() -> crate::scratch::Scratch<PathBuf> {
1247        // Unique by construction: `tempfile` picks the name. It used to be
1248        // `eclipse-cron-test-<pid>-<ms>-<n>` because parallel threads of one process could hand two
1249        // tests the same name and they would delete each other's files; a `TempDir` gives the same
1250        // guarantee and removes itself, which the hand-built path did not — one directory per cron
1251        // test, each with a `cron/jobs.toml`, was left in `$TMPDIR` after every run.
1252        crate::scratch::Scratch::dir("eclipse-cron-test-")
1253    }
1254
1255    #[test]
1256    fn the_four_shapes_of_a_schedule_round_trip() {
1257        for (text, want) in [
1258            ("every 30m", Schedule::Every(1800)),
1259            ("every 2h", Schedule::Every(7200)),
1260            ("hourly", Schedule::Every(3600)),
1261            (
1262                "daily 07:30",
1263                Schedule::Daily {
1264                    hour: 7,
1265                    minute: 30,
1266                },
1267            ),
1268            (
1269                "weekly mon 09:00",
1270                Schedule::Weekly {
1271                    weekday: 1,
1272                    hour: 9,
1273                    minute: 0,
1274                },
1275            ),
1276        ] {
1277            let parsed = Schedule::parse(text).unwrap();
1278            assert_eq!(parsed, want, "{text}");
1279            assert_eq!(Schedule::parse(&parsed.describe()).unwrap(), want);
1280        }
1281    }
1282
1283    #[test]
1284    fn a_schedule_that_is_not_one_says_what_ones_exist() {
1285        for bad in [
1286            "",
1287            "30m",
1288            "every",
1289            "every 30",
1290            "every 30x",
1291            "daily",
1292            "daily 7",
1293            "daily 25:00",
1294            "weekly 9am",
1295        ] {
1296            let err = Schedule::parse(bad).unwrap_err().to_string();
1297            assert!(
1298                err.contains("unrecognised schedule") || err.contains("not a time of day"),
1299                "{bad}: {err}"
1300            );
1301        }
1302    }
1303
1304    #[test]
1305    fn a_sub_minute_interval_is_refused_as_a_busy_loop() {
1306        let err = Schedule::parse("every 30s").unwrap_err().to_string();
1307        assert!(err.contains("shortest interval is `every 1m`"), "{err}");
1308    }
1309
1310    #[test]
1311    fn a_daily_schedule_lands_on_that_wall_clock_time_tomorrow_at_the_latest() {
1312        let now = 1_700_000_000_000i64; // 2023-11-14T22:13:20Z
1313        let s = Schedule::parse("daily 07:30").unwrap();
1314        let next = s.next_due(now);
1315        assert!(next > now);
1316        assert!(next - now <= 86_400_000, "within a day: {}", next - now);
1317        let (_, _, _, hour, minute) = local_parts(next);
1318        assert_eq!((hour, minute), (7, 30), "it fires at 07:30 local, not UTC");
1319    }
1320
1321    #[test]
1322    fn a_weekly_schedule_lands_on_the_named_day() {
1323        let now = 1_700_000_000_000i64;
1324        let s = Schedule::parse("weekly wed 09:00").unwrap();
1325        let next = s.next_due(now);
1326        assert!(next > now);
1327        assert!(next - now <= 8 * 86_400_000);
1328        assert_eq!(weekday_of(next), 3, "a Wednesday");
1329        let (_, _, _, hour, minute) = local_parts(next);
1330        assert_eq!((hour, minute), (9, 0));
1331    }
1332
1333    #[test]
1334    fn civil_dates_survive_leap_days_and_month_ends() {
1335        assert_eq!(days_from_civil(1970, 1, 1), 0);
1336        assert_eq!(civil_from_days(0), (1970, 1, 1));
1337        assert_eq!(
1338            days_from_civil(2024, 2, 29) + 1,
1339            days_from_civil(2024, 3, 1)
1340        );
1341        assert_eq!(civil_add_days(2024, 2, 28, 1), (2024, 2, 29));
1342        assert_eq!(civil_add_days(2024, 12, 31, 1), (2025, 1, 1));
1343        for d in [-1000i64, -1, 0, 1, 20_000, 30_000] {
1344            let (y, m, day) = civil_from_days(d);
1345            assert_eq!(days_from_civil(y, m, day), d, "round trip at {d}");
1346        }
1347    }
1348
1349    #[test]
1350    fn a_new_interval_job_runs_at_once_and_a_new_named_job_waits_for_its_hour() {
1351        let mut state = State::default();
1352        let now = 1_700_000_000_000i64;
1353        let every = job("tick", "every 30m");
1354        let daily = job("brief", "daily 07:30");
1355        let jobs = vec![every, daily];
1356        let due_now = due(&jobs, &mut state, now);
1357        assert_eq!(due_now.len(), 1, "only the interval job");
1358        assert_eq!(due_now[0].name, "tick");
1359    }
1360
1361    #[test]
1362    fn an_interval_job_is_due_again_only_after_its_interval() {
1363        let mut state = State::default();
1364        let now = 1_700_000_000_000i64;
1365        let jobs = vec![job("tick", "every 30m")];
1366        state.jobs.insert(
1367            "tick".into(),
1368            JobState {
1369                last_started_ms: Some(now - 29 * 60 * 1000),
1370                ..Default::default()
1371            },
1372        );
1373        assert!(
1374            due(&jobs, &mut state, now).is_empty(),
1375            "29 minutes is not 30"
1376        );
1377        state.jobs.insert(
1378            "tick".into(),
1379            JobState {
1380                last_started_ms: Some(now - 31 * 60 * 1000),
1381                ..Default::default()
1382            },
1383        );
1384        assert_eq!(due(&jobs, &mut state, now).len(), 1);
1385    }
1386
1387    /// `#561`: a `daily` job that had never run was due *never*. `due` wanted a `last_started_ms`,
1388    /// nothing wrote one for a job that had not run, and the only writer was the runner — which
1389    /// could not run a job that was never due. Every job added by `cron add` or by the dashboard's
1390    /// form was dead, while `cron list` promised a next time that rolled forward on each tick.
1391    #[test]
1392    fn a_new_daily_job_fires_at_its_next_named_moment() {
1393        let mut state = State::default();
1394        let now = 1_700_000_000_000i64;
1395        let jobs = vec![job("brief", "daily 07:30")];
1396        let next = jobs[0].schedule.next_due(now);
1397        assert!(next > now, "the next 07:30 is ahead of this moment");
1398
1399        assert!(due(&jobs, &mut state, now).is_empty(), "not on the spot");
1400        assert!(
1401            due(&jobs, &mut state, next - 1).is_empty(),
1402            "not a millisecond early"
1403        );
1404        let fired = due(&jobs, &mut state, next);
1405        assert_eq!(
1406            fired.len(),
1407            1,
1408            "the job fires at the moment `cron list` promised"
1409        );
1410        assert_eq!(fired[0].name, "brief");
1411    }
1412
1413    /// The anchor is written once. A seed recomputed on every tick would move it forward each time
1414    /// and the job would still never fire — the shape this bug actually had.
1415    #[test]
1416    fn the_anchor_a_new_job_is_given_is_not_moved_by_a_later_tick() {
1417        let mut state = State::default();
1418        let jobs = vec![job("brief", "daily 07:30")];
1419        due(&jobs, &mut state, 1_000_000_000_000);
1420        assert_eq!(
1421            state.get("brief").last_started_ms,
1422            Some(1_000_000_000_000),
1423            "the first sighting is the anchor"
1424        );
1425        due(&jobs, &mut state, 1_500_000_000_000);
1426        assert_eq!(
1427            state.get("brief").last_started_ms,
1428            Some(1_000_000_000_000),
1429            "a later tick left it alone"
1430        );
1431        assert_eq!(
1432            next_due_for(&jobs[0], &state, 1_500_000_000_000),
1433            Some(jobs[0].schedule.next_due(1_000_000_000_000))
1434        );
1435    }
1436
1437    #[test]
1438    fn a_disabled_job_is_never_due_and_has_no_next_time() {
1439        let mut state = State::default();
1440        let mut j = job("tick", "every 1m");
1441        j.enabled = false;
1442        state.jobs.insert(
1443            "tick".into(),
1444            JobState {
1445                last_started_ms: Some(0),
1446                ..Default::default()
1447            },
1448        );
1449        let jobs = vec![j.clone()];
1450        assert!(due(&jobs, &mut state, 1_700_000_000_000).is_empty());
1451        assert_eq!(next_due_for(&j, &state, 1_700_000_000_000), None);
1452    }
1453
1454    #[test]
1455    fn a_jobs_schema_survives_the_file_it_is_written_to() {
1456        let root = temp_root();
1457        let mut shaped = job("shaped", "daily 07:30");
1458        // An inline schema, TOML-quoted: the same string `--schema` and the `cronjob_manage` tool
1459        // hand over, and the one the runner then hands to `resolve_schema`.
1460        shaped.schema = Some(r#"{"type":"object","required":["headline"]}"#.into());
1461        shaped.deliver = Some("~/notes/shaped.json".into());
1462        append_job(&root, &shaped).unwrap();
1463
1464        let text = std::fs::read_to_string(jobs_path(&root)).unwrap();
1465        assert!(
1466            text.contains("schema = \"{\\\"type\\\":\\\"object\\\""),
1467            "the schema is a TOML string, escaped: {text}"
1468        );
1469
1470        let jobs = load(&root).unwrap();
1471        assert_eq!(jobs.len(), 1);
1472        assert_eq!(jobs[0].schema, shaped.schema);
1473        // And a block without one still reads: `schema` is optional, not a new requirement.
1474        assert_eq!(job("plain", "every 1m").schema, None);
1475    }
1476
1477    #[test]
1478    fn the_jobs_file_is_appended_to_and_a_block_cut_out_without_touching_the_rest() {
1479        let root = temp_root();
1480        let first = job("first", "every 1m");
1481        let mut second = job("second", "daily 08:00");
1482        second.deliver = Some("~/notes/brief.md".into());
1483        second.skills = vec!["release-check".into()];
1484        append_job(&root, &first).unwrap();
1485        append_job(&root, &second).unwrap();
1486
1487        let text = std::fs::read_to_string(jobs_path(&root)).unwrap();
1488        assert!(text.contains("[[job]]"));
1489        assert!(text.contains("deliver = \"~/notes/brief.md\""));
1490
1491        let jobs = load(&root).unwrap();
1492        assert_eq!(jobs.len(), 2);
1493        assert_eq!(jobs[1].skills, ["release-check"]);
1494        assert_eq!(jobs[1].schedule, Schedule::Daily { hour: 8, minute: 0 });
1495
1496        assert!(remove_job(&root, "first").unwrap());
1497        let jobs = load(&root).unwrap();
1498        assert_eq!(jobs.len(), 1);
1499        assert_eq!(jobs[0].name, "second");
1500        assert!(!remove_job(&root, "nope").unwrap());
1501        let _ = std::fs::remove_dir_all(&root);
1502    }
1503
1504    #[test]
1505    fn replacing_a_block_keeps_the_file_around_it() {
1506        let root = temp_root();
1507        append_job(&root, &job("one", "every 1m")).unwrap();
1508        append_job(&root, &job("two", "every 2m")).unwrap();
1509        let path = jobs_path(&root);
1510        let before = std::fs::read_to_string(&path).unwrap();
1511        std::fs::write(&path, format!("{before}\n# keep me\n")).unwrap();
1512
1513        let mut paused = job("one", "every 1m");
1514        paused.enabled = false;
1515        replace_job(&root, &paused).unwrap();
1516
1517        let text = std::fs::read_to_string(&path).unwrap();
1518        assert!(text.contains("# keep me"), "the comment survives");
1519        assert!(text.contains("enabled = false"), "the change landed");
1520        let jobs = load(&root).unwrap();
1521        assert!(!jobs[0].enabled);
1522        assert!(jobs[1].enabled);
1523        assert!(replace_job(&root, &job("ghost", "every 1m")).is_err());
1524        let _ = std::fs::remove_dir_all(&root);
1525    }
1526
1527    #[test]
1528    fn two_jobs_cannot_share_a_name() {
1529        let root = temp_root();
1530        append_job(&root, &job("same", "every 1m")).unwrap();
1531        let err = append_job(&root, &job("same", "every 2m"))
1532            .unwrap_err()
1533            .to_string();
1534        assert!(err.contains("already exists"), "{err}");
1535        let _ = std::fs::remove_dir_all(&root);
1536    }
1537
1538    #[test]
1539    fn a_job_with_an_empty_prompt_is_refused() {
1540        let root = temp_root();
1541        std::fs::create_dir_all(root.join("cron")).unwrap();
1542        std::fs::write(
1543            jobs_path(&root),
1544            "[[job]]\nname = \"x\"\nschedule = \"every 1m\"\nprompt = \"  \"\n",
1545        )
1546        .unwrap();
1547        // A job that cannot run is refused, not invented — and since `#405` one such block is a
1548        // skipped job with a report rather than a failure for the whole file.
1549        let (jobs, problems) = load_reporting(&root).unwrap();
1550        assert!(jobs.is_empty(), "a job with nothing to say is not a job");
1551        assert_eq!(problems.len(), 1, "{problems:?}");
1552        assert!(problems[0].contains("empty prompt"), "{problems:?}");
1553        let _ = std::fs::remove_dir_all(&root);
1554    }
1555
1556    #[test]
1557    fn an_unknown_key_is_refused_rather_than_silently_ignored() {
1558        let root = temp_root();
1559        std::fs::create_dir_all(root.join("cron")).unwrap();
1560        std::fs::write(
1561            jobs_path(&root),
1562            "[[job]]\nname = \"x\"\nschedule = \"every 1m\"\nprompt = \"p\"\nsechdule = \"every 2m\"\n",
1563        )
1564        .unwrap();
1565        assert!(load(&root).is_err(), "a typo in a key must not pass");
1566        let _ = std::fs::remove_dir_all(&root);
1567    }
1568
1569    #[test]
1570    fn state_round_trips_and_a_missing_file_is_empty_state() {
1571        let root = temp_root();
1572        assert!(load_state(&root).unwrap().jobs.is_empty());
1573        let mut state = State::default();
1574        state.jobs.insert(
1575            "tick".into(),
1576            JobState {
1577                last_started_ms: Some(5),
1578                last_finished_ms: Some(6),
1579                last_outcome: Some("ok".into()),
1580                runs: 1,
1581            },
1582        );
1583        save_state(&root, &state).unwrap();
1584        let back = load_state(&root).unwrap();
1585        assert_eq!(back.get("tick").runs, 1);
1586        assert_eq!(back.get("tick").last_outcome.as_deref(), Some("ok"));
1587        let _ = std::fs::remove_dir_all(&root);
1588    }
1589
1590    /// `#405`: one malformed block used to be an `Err` for the whole file, so a typo in a job
1591    /// nobody was looking at stopped every other job — and the only trace was a failed systemd
1592    /// unit. A bad block is skipped, named, and the rest still run. The schedule error has to carry
1593    /// the job's own name: `unrecognised schedule "evry 5m"` in a file of twelve blocks is a hunt.
1594    #[test]
1595    fn a_broken_job_is_skipped_and_named_instead_of_stopping_every_job() {
1596        let root = temp_root();
1597        std::fs::create_dir_all(root.join("cron")).unwrap();
1598        std::fs::write(
1599            jobs_path(&root),
1600            "[[job]]\nname = \"good\"\nschedule = \"every 1h\"\nprompt = \"say something\"\n\n\
1601             [[job]]\nname = \"typo\"\nschedule = \"evry 5m\"\nprompt = \"never mind\"\n",
1602        )
1603        .unwrap();
1604
1605        let (jobs, problems) = load_reporting(&root).unwrap();
1606        assert_eq!(jobs.len(), 1, "the good job still loads: {problems:?}");
1607        assert_eq!(jobs[0].name, "good");
1608        assert_eq!(problems.len(), 1, "{problems:?}");
1609        assert!(
1610            problems[0].contains("typo"),
1611            "the problem names the job, not just the schedule: {problems:?}"
1612        );
1613        assert!(
1614            problems[0].contains("evry 5m"),
1615            "and quotes what it could not parse: {problems:?}"
1616        );
1617        // The plain reader is the same list, without the report.
1618        assert_eq!(load(&root).unwrap().len(), 1);
1619        let _ = std::fs::remove_dir_all(&root);
1620    }
1621
1622    /// `#406`: `every <N>d` multiplied without checking, and a release build has no overflow
1623    /// checks — `every 144115188075855873d` wrapped to exactly 86 400 seconds and passed as
1624    /// `every 1d`, i.e. a schedule somebody wrote as "never" silently ran daily.
1625    #[test]
1626    fn an_interval_too_large_to_count_is_refused_not_wrapped() {
1627        assert!(
1628            Schedule::parse("every 144115188075855873d").is_err(),
1629            "an interval that wraps is refused"
1630        );
1631        assert!(Schedule::parse("every 99999999999999999999d").is_err());
1632        assert_eq!(
1633            Schedule::parse("every 2h").unwrap(),
1634            Schedule::Every(7_200),
1635            "an ordinary interval still parses"
1636        );
1637        // And the arithmetic that would have wrapped is saturating, so a `next_due` on an
1638        // interval nobody can represent reports the end of time rather than a moment in the past.
1639        let unrepresentable = Schedule::Every(i64::MAX as u64 / 1000 + 1);
1640        assert_eq!(unrepresentable.next_due(0), i64::MAX);
1641        assert_eq!(
1642            Schedule::Every(3_600).next_due(0),
1643            3_600_000,
1644            "and is exact for a real one"
1645        );
1646    }
1647
1648    /// `#407`: staleness is the lock file's mtime, which was written once and never refreshed, so
1649    /// a tick that legitimately ran past the stale mark was taken for an abandoned one. The next
1650    /// minute's tick then started with its own list and ran the jobs the first had not reached —
1651    /// and when the first finished, its `Drop` deleted the *second* tick's file.
1652    #[test]
1653    fn a_long_tick_stays_alive_and_a_tick_that_lost_the_lock_does_not_delete_it() {
1654        let root = temp_root();
1655        let now = crate::session::now_ms() as i64;
1656        let mut tick = lock(&root, now).unwrap().expect("first tick takes it");
1657        let path = tick.path().to_path_buf();
1658
1659        // Proof of life keeps it fresh: the file's mtime moves and the content is still ours.
1660        assert!(tick.touch(now + 60_000), "a live tick can say so");
1661        let modified = std::fs::metadata(&path).and_then(|m| m.modified()).unwrap();
1662        let fresh = std::time::SystemTime::now()
1663            .duration_since(modified)
1664            .expect("the file is not from the future");
1665        assert!(
1666            fresh.as_secs() < 60,
1667            "touching refreshes the mtime, which is what staleness reads"
1668        );
1669
1670        // Another tick takes the lock over. Ours is now a stale view of a file it does not own:
1671        // it cannot touch it, and its `Drop` must leave the new holder's file alone.
1672        std::fs::write(&path, "999999999999\n").unwrap();
1673        assert!(!tick.touch(now + 120_000), "a taken-over tick stops");
1674        drop(tick);
1675        assert!(
1676            path.exists(),
1677            "the new holder's lock survives the old tick's Drop"
1678        );
1679        let _ = std::fs::remove_dir_all(&root);
1680    }
1681
1682    /// `#566`: taking a stale lock over was a check-then-act — read the age, decide, then write
1683    /// the file. Two ticks at the same instant both saw an old file and both held it, and because
1684    /// their stamps were the same string, neither `Drop` could tell it was deleting the other's
1685    /// lock. The kernel holds it now, so a holder is displaced only by ending.
1686    #[test]
1687    fn a_lock_that_looks_old_is_still_held_by_the_tick_that_wrote_it() {
1688        let root = temp_root();
1689        let now = crate::session::now_ms() as i64;
1690        let held = lock(&root, now).unwrap().expect("first tick takes it");
1691        let path = root.join("state").join("cron.lock");
1692
1693        // A live holder that has not reached a job boundary: its file ages past the stale mark
1694        // without a `touch`.
1695        let old =
1696            std::time::SystemTime::now() - std::time::Duration::from_millis(STALE_LOCK_MS + 5_000);
1697        filetime_set(&path, old);
1698
1699        assert!(
1700            lock(&root, now).unwrap().is_none(),
1701            "a second tick took the lock from a holder that is still running"
1702        );
1703        drop(held);
1704        assert!(
1705            lock(&root, now).unwrap().is_some(),
1706            "and it is free the moment that holder ends"
1707        );
1708        let _ = std::fs::remove_dir_all(&root);
1709    }
1710
1711    #[test]
1712    fn a_second_tick_does_not_take_the_lock_and_an_abandoned_one_does() {
1713        let root = temp_root();
1714        let now = crate::session::now_ms() as i64;
1715        let held = lock(&root, now).unwrap().expect("first tick takes it");
1716        assert!(lock(&root, now).unwrap().is_none(), "second tick waits");
1717        drop(held);
1718        assert!(
1719            lock(&root, now).unwrap().is_some(),
1720            "the lock is released when the tick ends"
1721        );
1722
1723        // Pretend the process died holding it: age the file past the stale mark.
1724        let path = root.join("state").join("cron.lock");
1725        drop(std::fs::File::create(&path).unwrap());
1726        let old =
1727            std::time::SystemTime::now() - std::time::Duration::from_millis(STALE_LOCK_MS + 5_000);
1728        filetime_set(&path, old);
1729        let taken = lock(&root, now)
1730            .unwrap()
1731            .expect("a stale lock is taken over");
1732        assert!(taken.took_over_stale);
1733        let _ = std::fs::remove_dir_all(&root);
1734    }
1735
1736    fn filetime_set(path: &Path, when: std::time::SystemTime) {
1737        // No dependency for this: `utimensat` through libc, unix only. Elsewhere the test is a
1738        // no-op and the stale-lock path is covered by the branch above.
1739        #[cfg(unix)]
1740        {
1741            use std::os::unix::ffi::OsStrExt;
1742            let c = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
1743            let times = [
1744                libc::timespec {
1745                    tv_sec: when
1746                        .duration_since(std::time::UNIX_EPOCH)
1747                        .map(|d| d.as_secs() as i64)
1748                        .unwrap_or(0),
1749                    tv_nsec: 0,
1750                },
1751                libc::timespec {
1752                    tv_sec: when
1753                        .duration_since(std::time::UNIX_EPOCH)
1754                        .map(|d| d.as_secs() as i64)
1755                        .unwrap_or(0),
1756                    tv_nsec: 0,
1757                },
1758            ];
1759            // SAFETY: a valid C string and an array of exactly two timespecs, as the call
1760            // requires.
1761            unsafe {
1762                libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), 0);
1763            }
1764        }
1765        #[cfg(not(unix))]
1766        let _ = (path, when);
1767    }
1768
1769    #[test]
1770    fn runs_are_written_newest_first() {
1771        let root = temp_root();
1772        for ms in [1, 2, 3] {
1773            write_run(&root, "tick", ms, "hello").unwrap();
1774        }
1775        let runs = recent_runs(&root, "tick", 10);
1776        assert_eq!(runs.len(), 3);
1777        assert!(runs[0].to_string_lossy().contains("3.md"), "newest first");
1778        assert_eq!(recent_runs(&root, "nothing", 10).len(), 0);
1779        let _ = std::fs::remove_dir_all(&root);
1780    }
1781
1782    #[test]
1783    fn a_job_name_becomes_a_directory_so_it_is_held_to_an_alphabet() {
1784        for bad in ["..", "a/b", "with space", ""] {
1785            assert!(validate_job_name(bad).is_err(), "{bad:?} must be refused");
1786        }
1787        assert!(validate_job_name("nightly-backup_2").is_ok());
1788    }
1789
1790    #[test]
1791    fn a_view_carries_the_next_fire_and_what_last_ran() {
1792        let root = temp_root();
1793        let job = job("brief", "every 30m");
1794        append_job(&root, &job).unwrap();
1795        let now = 1_700_000_000_000_i64;
1796
1797        let fresh = views(&root, now).unwrap();
1798        assert_eq!(fresh.len(), 1);
1799        assert_eq!(fresh[0].schedule, "every 30m");
1800        // Never run and an interval: due immediately, which is what `due` says too.
1801        assert_eq!(fresh[0].next_ms, Some(now));
1802        assert_eq!(fresh[0].last_outcome, None);
1803        assert_eq!(fresh[0].runs, 0);
1804
1805        let mut state = load_state(&root).unwrap();
1806        let entry = state.jobs.entry("brief".into()).or_default();
1807        entry.last_started_ms = Some(now);
1808        entry.last_finished_ms = Some(now + 1000);
1809        entry.last_outcome = Some("ok".into());
1810        entry.runs = 3;
1811        save_state(&root, &state).unwrap();
1812
1813        let after = views(&root, now + 1000).unwrap();
1814        assert_eq!(after[0].runs, 3);
1815        assert_eq!(after[0].last_outcome.as_deref(), Some("ok"));
1816        assert_eq!(after[0].next_ms, Some(now + 30 * 60 * 1000));
1817        let _ = std::fs::remove_dir_all(&root);
1818    }
1819
1820    #[test]
1821    fn a_schedule_a_job_is_shown_with_is_the_one_an_editor_can_submit_back() {
1822        for text in [
1823            "every 30m",
1824            "every 2h",
1825            "hourly",
1826            "daily 07:30",
1827            "weekly mon 09:00",
1828        ] {
1829            let draft = Draft {
1830                name: "brief".into(),
1831                schedule: text.into(),
1832                prompt: "p".into(),
1833                ..Default::default()
1834            };
1835            let job = draft.to_job().unwrap();
1836            // What the view shows is what comes back to `to_job` as the same schedule.
1837            let shown = Draft::from_job(&job);
1838            assert_eq!(shown.schedule, job.schedule.describe());
1839            let again = shown.to_job().unwrap();
1840            assert_eq!(again.schedule, job.schedule, "{text} did not round-trip");
1841        }
1842        // And the one that means an hour twice says so once: `hourly` is `every 1h`.
1843        let hourly = Schedule::parse("hourly").unwrap();
1844        assert_eq!(hourly.describe(), "every 1h");
1845    }
1846
1847    #[test]
1848    fn a_draft_refuses_a_job_nothing_could_run() {
1849        let base = Draft {
1850            name: "brief".into(),
1851            schedule: "hourly".into(),
1852            prompt: "p".into(),
1853            ..Default::default()
1854        };
1855        assert!(base.to_job().is_ok());
1856
1857        let empty_prompt = Draft {
1858            prompt: "  \n ".into(),
1859            ..base.clone()
1860        };
1861        assert!(empty_prompt
1862            .to_job()
1863            .unwrap_err()
1864            .to_string()
1865            .contains("prompt"));
1866
1867        let bad_schedule = Draft {
1868            schedule: "every tuesday".into(),
1869            ..base.clone()
1870        };
1871        assert_eq!(
1872            bad_schedule.to_job().unwrap_err().to_string(),
1873            Schedule::parse("every tuesday").unwrap_err().to_string(),
1874            "the parser's own sentence, not a paraphrase"
1875        );
1876
1877        let bad_name = Draft {
1878            name: "a/b".into(),
1879            ..base.clone()
1880        };
1881        assert!(bad_name.to_job().is_err());
1882
1883        let missing_dir = Draft {
1884            workdir: Some("/nonexistent/eclipse-cron-test".into()),
1885            ..base
1886        };
1887        let why = missing_dir.to_job().unwrap_err().to_string();
1888        assert!(why.contains("not a directory"), "{why}");
1889    }
1890
1891    #[test]
1892    fn a_draft_keeps_being_enabled_unless_it_says_otherwise() {
1893        // A create that says nothing about `enabled` gets a job that fires: the default belongs in
1894        // the shared struct, not in whichever front end remembered to set it.
1895        let draft: Draft = serde_json::from_value(serde_json::json!({
1896            "name": "brief",
1897            "schedule": "hourly",
1898            "prompt": "p",
1899        }))
1900        .unwrap();
1901        assert!(draft.enabled);
1902        assert!(draft.to_job().unwrap().enabled);
1903    }
1904
1905    #[test]
1906    fn a_run_reads_back_with_its_answer_and_how_much_more_there_is() {
1907        let root = temp_root();
1908        let header = "# brief — 2026-11-30 07:30\n\nschedule every 30m\n\n---\n\n";
1909        write_run(
1910            &root,
1911            "brief",
1912            1_700_000_000_000,
1913            &format!("{header}it ran\n"),
1914        )
1915        .unwrap();
1916
1917        let long = format!("{header}{}", "x".repeat(RUN_TEXT_CAP + 500));
1918        write_run(&root, "brief", 1_700_000_100_000, &long).unwrap();
1919
1920        let runs = runs(&root, "brief", 5);
1921        assert_eq!(runs.len(), 2);
1922        // Newest first, and the answer is the first line after the tick's header.
1923        assert_eq!(runs[0].at_ms, 1_700_000_100_000);
1924        assert_eq!(
1925            runs[0].answer.chars().count(),
1926            ANSWER_CAP + 1,
1927            "the answer is the first line, cut at the cap and marked"
1928        );
1929        assert!(runs[0].answer.ends_with('…'), "{}", runs[0].answer);
1930        assert!(runs[0].answer.starts_with("xxx"));
1931        assert!(runs[0].truncated, "a capped text must say it is capped");
1932        assert_eq!(runs[0].chars, long.chars().count());
1933        assert_eq!(runs[0].text.chars().count(), RUN_TEXT_CAP);
1934
1935        assert_eq!(runs[1].answer, "it ran");
1936        assert!(!runs[1].truncated);
1937        assert_eq!(runs[1].at, iso_local(1_700_000_000_000));
1938        let _ = std::fs::remove_dir_all(&root);
1939    }
1940
1941    #[test]
1942    fn a_job_switched_off_leaves_its_prompt_and_schedule_where_they_were() {
1943        let root = temp_root();
1944        append_job(&root, &job("brief", "every 30m")).unwrap();
1945        let off = set_enabled(&root, "brief", false)
1946            .unwrap()
1947            .expect("the job");
1948        assert!(!off.enabled);
1949
1950        let on_disk = load(&root).unwrap();
1951        assert_eq!(on_disk.len(), 1);
1952        assert_eq!(on_disk[0].prompt, "say something");
1953        assert_eq!(on_disk[0].schedule, Schedule::parse("every 30m").unwrap());
1954        assert!(!on_disk[0].enabled);
1955        // A disabled job is not due and has no next fire, which is what the pane shows.
1956        assert!(due(&on_disk, &mut State::default(), 1_700_000_000_000).is_empty());
1957        assert_eq!(
1958            next_due_for(&on_disk[0], &State::default(), 1_700_000_000_000),
1959            None
1960        );
1961
1962        assert!(set_enabled(&root, "nothing", false).unwrap().is_none());
1963        assert!(set_enabled(&root, "brief", true).unwrap().unwrap().enabled);
1964        let _ = std::fs::remove_dir_all(&root);
1965    }
1966}