use crate::cron::Schedule;
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
pub fn dir(root: &Path) -> PathBuf {
root.join("state").join("loops")
}
pub fn state_path(root: &Path, session: &str) -> Result<PathBuf> {
crate::session::validate_id(session)?;
Ok(dir(root).join(format!("{session}.json")))
}
pub const MAX_TIMES: u32 = 100_000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Request {
Start(Spec),
Status,
Pause,
Resume,
Stop,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Spec {
pub prompt: String,
pub schedule: Schedule,
pub times: Option<u32>,
pub until: Option<String>,
}
impl Spec {
pub fn summary(&self) -> String {
let bound = match (self.times, &self.until) {
(None, None) => String::new(),
(Some(n), None) => format!(", at most {n} time(s)"),
(None, Some(c)) => format!(", until {c}"),
(Some(n), Some(c)) => format!(", at most {n} time(s) or until {c}"),
};
format!("{}: {}{bound}", self.schedule.describe(), self.prompt)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
Running,
Paused,
Ended,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Ended {
Times,
Until,
Stopped,
Failed,
}
impl Ended {
pub fn sentence(self) -> &'static str {
match self {
Ended::Times => "it reached the number of ticks it was given",
Ended::Until => "its condition was met",
Ended::Stopped => "it was stopped",
Ended::Failed => "it failed",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Owner {
Cli,
Gateway,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct State {
pub session: String,
pub prompt: String,
pub interval: String,
#[serde(default)]
pub times: Option<u32>,
#[serde(default)]
pub until: Option<String>,
pub status: Status,
#[serde(default)]
pub ended: Option<Ended>,
pub fired: u32,
#[serde(default)]
pub skipped: u32,
pub next_due_ms: i64,
pub created_ms: i64,
pub owner: Owner,
pub owner_pid: u32,
#[serde(default)]
pub note: Option<String>,
}
impl State {
pub fn start(session: &str, spec: Spec, owner: Owner, now_ms: i64) -> State {
State {
session: session.to_string(),
prompt: spec.prompt,
interval: spec.schedule.describe(),
times: spec.times,
until: spec.until,
status: Status::Running,
ended: None,
fired: 0,
skipped: 0,
next_due_ms: spec.schedule.next_due(now_ms),
created_ms: now_ms,
owner,
owner_pid: std::process::id(),
note: None,
}
}
pub fn schedule(&self) -> Result<Schedule> {
Schedule::parse(&self.interval)
}
pub fn spec(&self) -> Result<Spec> {
Ok(Spec {
prompt: self.prompt.clone(),
schedule: self.schedule()?,
times: self.times,
until: self.until.clone(),
})
}
pub fn due(&self, now_ms: i64) -> bool {
self.status == Status::Running && now_ms >= self.next_due_ms
}
pub fn record(&mut self, now_ms: i64, outcome: Outcome) {
match outcome {
Outcome::Ran => {
self.fired = self.fired.saturating_add(1);
self.note = None;
if let Some(limit) = self.times {
if self.fired >= limit {
return self.end(Ended::Times);
}
}
}
Outcome::Skipped(why) => {
self.skipped = self.skipped.saturating_add(1);
self.note = Some(format!("skipped: {why}"));
}
Outcome::Failed(why) => {
self.note = Some(format!("failed: {why}"));
}
}
if self.status == Status::Running {
self.next_due_ms = self.arm(now_ms);
}
}
pub fn end(&mut self, why: Ended) {
self.status = Status::Ended;
self.ended = Some(why);
self.next_due_ms = 0;
}
pub fn pause(&mut self) {
if self.status == Status::Running {
self.status = Status::Paused;
}
}
fn arm(&self, now_ms: i64) -> i64 {
match self.schedule() {
Ok(schedule) => schedule.next_due(now_ms),
Err(_) => now_ms.saturating_add(60_000),
}
}
pub fn resume(&mut self, now_ms: i64) {
if self.status == Status::Paused {
self.status = Status::Running;
self.next_due_ms = self.arm(now_ms);
}
}
pub fn owner_alive(&self) -> bool {
if self.owner_pid == std::process::id() {
return true;
}
#[cfg(unix)]
{
let alive = unsafe { libc::kill(self.owner_pid as libc::pid_t, 0) } == 0;
alive || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(not(unix))]
{
true
}
}
pub fn tick_note(&self) -> Option<String> {
match self.status {
Status::Ended => Some(format!(
"loop ended — {}",
self.readout(crate::session::now_ms() as i64)
)),
_ => self.note.as_ref().map(|note| format!("loop tick {note}")),
}
}
pub fn readout(&self, now_ms: i64) -> String {
let mut line = match self.status {
Status::Running => {
if self.owner_alive() {
let left = (self.next_due_ms - now_ms).max(0) as u64;
format!(
"loop running · {} · {}/{} ticks · next in {}",
self.interval,
self.fired,
self.times
.map(|n| n.to_string())
.unwrap_or_else(|| "∞".to_string()),
duration(left / 1000)
)
} else {
format!(
"loop was running · {} · {}/{} ticks · the process that owned it (pid {}) \
has exited, so nothing is ticking",
self.interval,
self.fired,
self.times
.map(|n| n.to_string())
.unwrap_or_else(|| "∞".to_string()),
self.owner_pid
)
}
}
Status::Paused => format!(
"loop paused · {} · {}/{} ticks",
self.interval,
self.fired,
self.times
.map(|n| n.to_string())
.unwrap_or_else(|| "∞".to_string())
),
Status::Ended => format!(
"loop ended · {} · {} ticks — {}",
self.interval,
self.fired,
self.ended.map(|e| e.sentence()).unwrap_or("stopped")
),
};
if !self.prompt.is_empty() {
line.push_str(&format!(" · {:?}", ellipsis(&self.prompt, 48)));
}
if let Some(note) = &self.note {
line.push_str(&format!(" · {note}"));
}
line
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Ran,
Skipped(String),
Failed(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
Reached,
KeepGoing,
Unreadable,
}
impl Verdict {
pub fn as_str(self) -> &'static str {
match self {
Verdict::Reached => "reached",
Verdict::KeepGoing => "keep going",
Verdict::Unreadable => "unreadable",
}
}
}
pub fn verdict(answer: &str) -> Verdict {
let first = answer
.trim()
.trim_start_matches(['"', '\'', '`', '*', ' '])
.split(|c: char| c.is_whitespace() || matches!(c, ',' | '.' | '!' | '?' | ';' | ':'))
.find(|w| !w.is_empty())
.unwrap_or("")
.trim_end_matches(['"', '\'', '`', '*'])
.to_ascii_lowercase();
match first.as_str() {
"yes" | "y" | "true" | "reached" | "stop" | "done" => Verdict::Reached,
"no" | "n" | "false" | "continue" | "keep" | "going" => Verdict::KeepGoing,
_ => Verdict::Unreadable,
}
}
pub fn until_prompt(condition: &str, last_reply: Option<&str>) -> [crate::message::Message; 2] {
const SYSTEM: &str = "\
You judge one condition. You are given a condition and the reply the agent just produced. Answer \
with exactly one word: yes if the condition is met, no if it is not. Do not explain, do not add \
punctuation, do not answer anything else.";
let mut user = format!("CONDITION: {condition}");
match last_reply.map(str::trim).filter(|r| !r.is_empty()) {
Some(reply) => {
user.push_str("\n\nTHE REPLY JUST PRODUCED:\n");
user.push_str(&ellipsis(reply, 4_000));
}
None => user.push_str("\n\nTHE REPLY JUST PRODUCED: (the turn produced no text)"),
}
[
crate::message::Message::system(SYSTEM),
crate::message::Message::user(user),
]
}
pub fn parse(arg: &str) -> Result<Request> {
let text = arg.trim();
if text.is_empty() || text.eq_ignore_ascii_case("status") {
return Ok(Request::Status);
}
for (word, request) in [
("pause", Request::Pause),
("resume", Request::Resume),
("stop", Request::Stop),
] {
if text.eq_ignore_ascii_case(word) {
return Ok(request);
}
}
let mut words = text.split_whitespace().peekable();
let interval_word = words.next().expect("text is not empty");
let schedule = interval(interval_word)?;
let mut prompt: Vec<&str> = Vec::new();
let mut times: Option<u32> = None;
let mut until: Option<String> = None;
while let Some(word) = words.next() {
match word {
"--times" | "-n" => {
let raw = words.next().ok_or_else(|| {
Error::Config("`--times` needs a number: `/loop 2m <prompt> --times 3`".into())
})?;
let n: u32 = raw.parse().map_err(|_| {
Error::Config(format!(
"`--times {raw}` is not a count; write a whole number of ticks"
))
})?;
if n == 0 {
return Err(Error::Config(
"`--times 0` is a loop that never runs; drop the flag for no bound".into(),
));
}
if n > MAX_TIMES {
return Err(Error::Config(format!(
"`--times {n}` is more than {MAX_TIMES}; an unbounded loop is written by \
leaving the flag out"
)));
}
times = Some(n);
}
"--until" => {
let mut condition: Vec<&str> = Vec::new();
while let Some(next) = words.peek() {
if next.starts_with("--") {
break;
}
condition.push(words.next().expect("peeked"));
}
let condition = condition.join(" ");
if condition.trim().is_empty() {
return Err(Error::Config(
"`--until` needs a condition: `/loop 2m <prompt> --until the build is green`"
.into(),
));
}
until = Some(unquote(&condition));
}
other if other.starts_with("--") => {
return Err(Error::Config(format!(
"unknown flag {other:?}; the flags are `--times N` and `--until <condition>`"
)));
}
other => prompt.push(other),
}
}
let prompt = unquote(&prompt.join(" "));
if prompt.is_empty() {
return Err(Error::Config(
"a loop needs something to say: `/loop 2m <prompt>`".into(),
));
}
Ok(Request::Start(Spec {
prompt,
schedule,
times,
until,
}))
}
pub fn interval(text: &str) -> Result<Schedule> {
let t = text.trim();
if is_bare_interval(t) {
return Schedule::parse(&format!("every {t}"));
}
Schedule::parse(t).map_err(|_| {
Error::Config(format!(
"{t:?} is not an interval. Write `2m`, `90s`, `every 30m`, `hourly` or \
`daily 07:30` — the same grammar cron takes"
))
})
}
fn is_bare_interval(text: &str) -> bool {
let split = text
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(text.len());
let (number, unit) = text.split_at(split);
!number.is_empty() && matches!(unit, "s" | "m" | "h" | "d")
}
fn unquote(text: &str) -> String {
let t = text.trim();
for q in ['"', '\''] {
if t.len() >= 2 && t.starts_with(q) && t.ends_with(q) {
return t[1..t.len() - 1].trim().to_string();
}
}
t.to_string()
}
fn ellipsis(text: &str, max: usize) -> String {
let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.chars().count() <= max {
return flat;
}
let mut cut = flat
.char_indices()
.nth(max.saturating_sub(1))
.map(|(i, _)| i)
.unwrap_or(flat.len());
if let Some(space) = flat[..cut].rfind(' ') {
if space > max / 2 {
cut = space;
}
}
format!("{}…", flat[..cut].trim_end())
}
pub fn duration(secs: u64) -> String {
match secs {
0..=59 => format!("{secs}s"),
60..=3599 => {
let (m, s) = (secs / 60, secs % 60);
if s == 0 {
format!("{m}m")
} else {
format!("{m}m {s}s")
}
}
_ => {
let (h, m) = (secs / 3600, (secs % 3600) / 60);
if m == 0 {
format!("{h}h")
} else {
format!("{h}h {m}m")
}
}
}
}
pub fn manage(root: &Path, session: &str, arg: &str, owner: Owner, now_ms: i64) -> Result<String> {
match parse(arg)? {
Request::Start(spec) => {
if let Some(mut existing) = load(root, session)? {
if existing.status == Status::Running && existing.owner_alive() {
return Err(Error::Config(format!(
"this session already has a loop running ({}). `/loop status` shows it, \
`/loop stop` ends it",
existing.readout(now_ms)
)));
}
if existing.status == Status::Paused {
return Err(Error::Config(format!(
"this session's loop is paused ({}). `/loop resume` continues it, \
`/loop stop` ends it",
existing.readout(now_ms)
)));
}
existing.end(Ended::Stopped);
}
let state = State::start(session, spec, owner, now_ms);
let said = start_sentence(&state, now_ms);
save(root, &state)?;
Ok(said)
}
Request::Status => {
let Some(state) = load(root, session)? else {
return Ok(
"no loop in this session. `/loop 2m <prompt>` starts one (`/cron` is the \
timer that outlives this process)"
.to_string(),
);
};
Ok(state.readout(now_ms))
}
Request::Pause => {
let Some(mut state) = load(root, session)? else {
return Err(Error::Config("no loop in this session to pause".into()));
};
if state.status != Status::Running {
return Ok(state.readout(now_ms));
}
state.pause();
save(root, &state)?;
Ok(format!(
"loop paused — {} ticks so far; `/loop resume` picks it up one interval from then",
state.fired
))
}
Request::Resume => {
let Some(mut state) = load(root, session)? else {
return Err(Error::Config("no loop in this session to resume".into()));
};
if state.status == Status::Ended {
return Err(Error::Config(format!(
"this loop has ended — {}; start a new one with `/loop <interval> <prompt>`",
state.readout(now_ms)
)));
}
state.resume(now_ms);
let said = format!(
"loop resumed — next tick in {}",
duration(((state.next_due_ms - now_ms).max(0) / 1000) as u64)
);
save(root, &state)?;
Ok(said)
}
Request::Stop => {
let Some(mut state) = load(root, session)? else {
return Ok("no loop in this session".to_string());
};
let fired = state.fired;
state.end(Ended::Stopped);
save(root, &state)?;
Ok(format!("loop stopped after {fired} tick(s)"))
}
}
}
fn start_sentence(state: &State, now_ms: i64) -> String {
let wait = ((state.next_due_ms - now_ms).max(0) / 1000) as u64;
let bound = match (state.times, &state.until) {
(None, None) => String::new(),
(Some(n), None) => format!(", at most {n}"),
(None, Some(c)) => format!(", until {c}"),
(Some(n), Some(c)) => format!(", at most {n} or until {c}"),
};
format!(
"loop started · {} · first tick in {}{bound} — it runs in this session, so its ticks carry \
what the last one produced; it stops when this process exits (`/cron` is the timer that \
survives that)",
state.interval,
duration(wait)
)
}
pub fn load(root: &Path, session: &str) -> Result<Option<State>> {
let path = state_path(root, session)?;
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(Error::io(&path, e)),
};
let state: State = serde_json::from_str(&text).map_err(|e| {
Error::Config(format!(
"{} is not a loop record ({e}); `/loop stop` clears it",
path.display()
))
})?;
Ok(Some(state))
}
pub fn save(root: &Path, state: &State) -> Result<()> {
let path = state_path(root, &state.session)?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
}
let text = serde_json::to_string_pretty(state)
.map_err(|e| Error::Config(format!("could not encode the loop record: {e}")))?;
crate::atomic::write_file_atomically(&path, &text).map_err(|e| Error::io(&path, e))?;
Ok(())
}
pub fn clear(root: &Path, session: &str) -> Result<()> {
let path = state_path(root, session)?;
match std::fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(Error::io(&path, e)),
}
}
pub fn all(root: &Path) -> Result<Vec<State>> {
let dir = dir(root);
let entries = match std::fs::read_dir(&dir) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(Error::io(&dir, e)),
};
let mut found: Vec<State> = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
match std::fs::read_to_string(&path)
.ok()
.and_then(|text| serde_json::from_str::<State>(&text).ok())
{
Some(state) => found.push(state),
None => continue,
}
}
found.sort_by_key(|s| std::cmp::Reverse(s.created_ms));
Ok(found)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cron::Schedule;
fn root() -> tempfile::TempDir {
tempfile::tempdir().expect("temp dir")
}
#[test]
fn a_bare_interval_is_an_interval_and_the_word_every_is_optional() {
assert_eq!(interval("2m").unwrap(), Schedule::Every(120));
assert_eq!(interval("90s").unwrap(), Schedule::Every(90));
assert_eq!(interval("1h").unwrap(), Schedule::Every(3_600));
assert_eq!(interval("every 2m").unwrap(), Schedule::Every(120));
assert_eq!(interval("hourly").unwrap(), Schedule::Every(3_600));
assert!(matches!(
interval("daily 07:30").unwrap(),
Schedule::Daily { .. }
));
}
#[test]
fn an_interval_finer_than_a_minute_is_refused_in_the_parsers_own_words() {
let why = interval("5s").unwrap_err().to_string();
assert!(why.contains("finer than a minute"), "{why}");
assert!(interval("2").is_err());
assert!(interval("soon").is_err());
}
#[test]
fn a_loop_line_carries_a_prompt_and_both_bounds() {
let Request::Start(spec) =
parse("2m check the build --times 3 --until the build is green").unwrap()
else {
panic!("not a start");
};
assert_eq!(spec.prompt, "check the build");
assert_eq!(spec.schedule, Schedule::Every(120));
assert_eq!(spec.times, Some(3));
assert_eq!(spec.until.as_deref(), Some("the build is green"));
}
#[test]
fn a_quoted_prompt_loses_its_quotes_and_keeps_its_words() {
let Request::Start(spec) = parse("2m \"check whether the build is green\"").unwrap() else {
panic!("not a start");
};
assert_eq!(spec.prompt, "check whether the build is green");
assert_eq!(spec.times, None);
}
#[test]
fn the_managing_words_do_not_start_a_loop() {
assert_eq!(parse("").unwrap(), Request::Status);
assert_eq!(parse("status").unwrap(), Request::Status);
assert_eq!(parse("PAUSE").unwrap(), Request::Pause);
assert_eq!(parse("resume").unwrap(), Request::Resume);
assert_eq!(parse("stop").unwrap(), Request::Stop);
}
#[test]
fn a_line_with_no_interval_and_no_prompt_is_refused_rather_than_guessed() {
assert!(parse("check the build").is_err());
assert!(parse("2m")
.unwrap_err()
.to_string()
.contains("needs something"));
assert!(parse("2m x --times").is_err());
assert!(parse("2m x --times 0").is_err());
assert!(parse("2m x --times 999999999").is_err());
assert!(parse("2m x --every 2m").is_err());
assert!(parse("2m x --until").is_err());
}
#[test]
fn a_tick_is_due_only_after_its_interval_and_only_while_running() {
let spec = parse("2m go").unwrap();
let Request::Start(spec) = spec else {
unreachable!()
};
let mut state = State::start("s1", spec, Owner::Cli, 1_000);
assert_eq!(state.next_due_ms, 1_000 + 120_000);
assert!(!state.due(120_999));
assert!(state.due(121_000));
state.pause();
assert!(!state.due(999_999));
state.resume(999_999);
assert!(!state.due(999_999), "a resumed loop waits its interval");
assert!(state.due(999_999 + 120_000));
}
#[test]
fn a_run_counts_and_arms_the_next_tick_from_the_one_that_ran() {
let Request::Start(spec) = parse("2m go").unwrap() else {
panic!()
};
let mut state = State::start("s1", spec, Owner::Cli, 0);
state.record(120_000, Outcome::Ran);
assert_eq!(state.fired, 1);
assert_eq!(state.next_due_ms, 240_000);
assert_eq!(state.status, Status::Running);
}
#[test]
fn times_stops_the_loop_after_that_many_runs() {
let Request::Start(spec) = parse("2m go --times 2").unwrap() else {
panic!()
};
let mut state = State::start("s1", spec, Owner::Cli, 0);
state.record(120_000, Outcome::Ran);
assert_eq!(state.status, Status::Running);
state.record(240_000, Outcome::Ran);
assert_eq!(state.status, Status::Ended);
assert_eq!(state.ended, Some(Ended::Times));
assert_eq!(state.next_due_ms, 0);
assert!(!state.due(999_999));
}
#[test]
fn a_skipped_tick_is_recorded_and_does_not_consume_a_run() {
let Request::Start(spec) = parse("2m go --times 2").unwrap() else {
panic!()
};
let mut state = State::start("s1", spec, Owner::Cli, 0);
state.record(120_000, Outcome::Skipped("a run is in flight".into()));
assert_eq!(state.fired, 0);
assert_eq!(state.skipped, 1);
assert_eq!(state.next_due_ms, 240_000);
assert!(state.note.as_deref().unwrap().contains("in flight"));
assert_eq!(state.status, Status::Running);
}
#[test]
fn a_failed_tick_is_recorded_and_the_loop_goes_on() {
let Request::Start(spec) = parse("2m go").unwrap() else {
panic!()
};
let mut state = State::start("s1", spec, Owner::Cli, 0);
state.record(120_000, Outcome::Failed("the route refused".into()));
assert_eq!(state.status, Status::Running);
assert_eq!(state.next_due_ms, 240_000);
assert!(state.note.as_deref().unwrap().contains("the route refused"));
}
#[test]
fn a_yes_no_answer_is_read_strictly_and_an_explanation_is_not_an_answer() {
for yes in [
"yes",
"YES",
"yes.",
"\"yes\"",
"yes, the build is green",
"true",
] {
assert_eq!(verdict(yes), Verdict::Reached, "{yes:?}");
}
for no in ["no", "NO", "no.", "false", "continue", "keep going"] {
assert_eq!(verdict(no), Verdict::KeepGoing, "{no:?}");
}
for neither in ["", " ", "it depends", "probably", "maybe not"] {
assert_eq!(verdict(neither), Verdict::Unreadable, "{neither:?}");
}
}
#[test]
fn the_until_request_carries_the_condition_and_the_reply() {
let request = until_prompt("the build is green", Some("build is green now"));
assert!(request[0].content.as_deref().unwrap().contains("one word"));
let user = request[1].content.as_deref().unwrap();
assert!(user.contains("CONDITION: the build is green"), "{user}");
assert!(user.contains("build is green now"), "{user}");
let empty = until_prompt("x", None);
assert!(
empty[1].content.as_deref().unwrap().contains("no text"),
"a turn with no text is said, not left blank"
);
}
#[test]
fn a_record_round_trips_through_the_file() {
let dir = root();
let Request::Start(spec) = parse("2m go --until it is green").unwrap() else {
panic!()
};
let mut state = State::start("s1", spec, Owner::Gateway, 500);
state.record(120_500, Outcome::Ran);
save(dir.path(), &state).unwrap();
let back = load(dir.path(), "s1").unwrap().expect("saved");
assert_eq!(back, state);
assert_eq!(back.schedule().unwrap(), Schedule::Every(120));
assert_eq!(back.spec().unwrap().until.as_deref(), Some("it is green"));
clear(dir.path(), "s1").unwrap();
assert!(load(dir.path(), "s1").unwrap().is_none());
clear(dir.path(), "s1").unwrap();
}
#[test]
fn a_session_id_that_could_walk_out_of_the_directory_is_refused() {
let dir = root();
assert!(state_path(dir.path(), "../etc/passwd").is_err());
assert!(load(dir.path(), "../../x").is_err());
}
#[test]
fn all_lists_every_record_and_skips_a_broken_one() {
let dir = root();
for (id, at) in [("a", 1_000), ("b", 2_000)] {
let Request::Start(spec) = parse("1m go").unwrap() else {
panic!()
};
save(dir.path(), &State::start(id, spec, Owner::Cli, at)).unwrap();
}
std::fs::write(super::dir(dir.path()).join("broken.json"), "{not json").unwrap();
let found = all(dir.path()).unwrap();
assert_eq!(
found.iter().map(|s| s.session.as_str()).collect::<Vec<_>>(),
["b", "a"],
"newest first, and a file that does not parse is not a record"
);
}
#[test]
fn an_empty_install_has_no_loops_rather_than_an_error() {
let dir = root();
assert!(all(dir.path()).unwrap().is_empty());
assert!(load(dir.path(), "s1").unwrap().is_none());
}
#[test]
fn the_readout_names_the_state_the_counts_and_the_next_tick() {
let Request::Start(spec) = parse("2m write the report --times 5").unwrap() else {
panic!()
};
let mut state = State::start("s1", spec, Owner::Cli, 0);
state.record(120_000, Outcome::Ran);
let line = state.readout(150_000);
assert!(
line.starts_with("loop running · every 2m · 1/5 ticks · next in 1m 30s"),
"{line}"
);
assert!(line.contains("write the report"), "{line}");
state.end(Ended::Times);
let line = state.readout(150_000);
assert!(line.contains("loop ended") && line.contains("2m"), "{line}");
}
#[test]
fn a_record_whose_process_is_gone_says_so_instead_of_counting_down() {
let Request::Start(spec) = parse("2m go").unwrap() else {
panic!()
};
let mut state = State::start("s1", spec, Owner::Cli, 0);
state.owner_pid = 4_194_304;
assert!(!state.owner_alive());
let line = state.readout(150_000);
assert!(line.contains("has exited"), "{line}");
assert!(!line.contains("next in"), "{line}");
}
#[test]
fn the_summary_names_the_bound_it_was_given() {
let Request::Start(spec) = parse("2m go --times 2 --until it is green").unwrap() else {
panic!()
};
let summary = spec.summary();
assert!(summary.starts_with("every 2m: go"), "{summary}");
assert!(summary.contains("at most 2"), "{summary}");
assert!(summary.contains("until it is green"), "{summary}");
let unbounded = Spec {
prompt: "go".into(),
schedule: Schedule::Every(60),
times: None,
until: None,
};
assert!(
!unbounded.summary().contains("at most"),
"{}",
unbounded.summary()
);
}
#[test]
fn a_countdown_reads_the_way_a_person_says_it() {
assert_eq!(duration(0), "0s");
assert_eq!(duration(45), "45s");
assert_eq!(duration(60), "1m");
assert_eq!(duration(130), "2m 10s");
assert_eq!(duration(3_600), "1h");
assert_eq!(duration(3_900), "1h 5m");
}
}