Skip to main content

eclipse_core/
loops.rs

1//! `#173`: `/loop` — one prompt, re-entered into *this* session on an interval.
2//!
3//! Not cron, and the difference is the whole point. A cron job is its own session on its own
4//! timer, owned by the systemd unit, and it survives this CLI exiting. A loop is a prompt sent
5//! back into the conversation that is already open, so every tick carries the history the last
6//! one produced — the session id never changes, and history is free.
7//!
8//! Who owns the timer is therefore a fact about the process, not about the feature: whichever
9//! front is running the session drives it. In the full-screen interface and the dashboard the
10//! timer lives in that process's event loop or in the gateway, and it keeps firing while nobody
11//! is typing. In the plain REPL the line editor owns the terminal, so a tick lands between turns
12//! and the readout says so. A loop that stops because its process exited is not a bug; it is the
13//! shape of the thing, and `/help` says it in one line.
14//!
15//! Nothing here runs an agent and nothing here talks to a provider. [`parse`] turns a typed line
16//! into a request, [`State`] is the record of one session's loop, and [`State::due`] decides with
17//! a clock the caller supplies — so the interesting parts are testable without a model, a
18//! terminal or a sleep. The caller runs, and reports back through [`Outcome`].
19//!
20//! The record lives in `<root>/state/loops/<session>.json`, one file per session: the CLI and the
21//! dashboard read the same bytes, and a second process cannot keep a private copy of what the
22//! first one is doing.
23
24use crate::cron::Schedule;
25use crate::error::{Error, Result};
26use serde::{Deserialize, Serialize};
27use std::path::{Path, PathBuf};
28
29/// Where a loop's record lives: `<root>/state/loops`.
30pub fn dir(root: &Path) -> PathBuf {
31    root.join("state").join("loops")
32}
33
34/// The record for one session: `<root>/state/loops/<session>.json`.
35pub fn state_path(root: &Path, session: &str) -> Result<PathBuf> {
36    crate::session::validate_id(session)?;
37    Ok(dir(root).join(format!("{session}.json")))
38}
39
40/// A ceiling on `--times`, because a bound that large is a way of writing "forever" with a
41/// number that looks deliberate. An unbounded loop is spelled by saying nothing.
42pub const MAX_TIMES: u32 = 100_000;
43
44/// What one typed `/loop` line asked for.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum Request {
47    /// `/loop 2m <prompt>` — start one in this session.
48    Start(Spec),
49    /// `/loop` or `/loop status`.
50    Status,
51    Pause,
52    Resume,
53    Stop,
54}
55
56/// What a loop was told to do: the prompt, how often, and its two bounds.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Spec {
59    pub prompt: String,
60    /// One of cron's schedules. `Every` is the ordinary case; the named moments are accepted
61    /// because they come from the same parser and refusing them would be a second grammar.
62    pub schedule: Schedule,
63    /// Stop after this many ticks that actually ran. `None` is unbounded.
64    pub times: Option<u32>,
65    /// A yes/no question asked on the aux route after each tick. `None` never asks.
66    pub until: Option<String>,
67}
68
69impl Spec {
70    /// One line naming what this loop does, for a readout or a refusal.
71    pub fn summary(&self) -> String {
72        let bound = match (self.times, &self.until) {
73            (None, None) => String::new(),
74            (Some(n), None) => format!(", at most {n} time(s)"),
75            (None, Some(c)) => format!(", until {c}"),
76            (Some(n), Some(c)) => format!(", at most {n} time(s) or until {c}"),
77        };
78        format!("{}: {}{bound}", self.schedule.describe(), self.prompt)
79    }
80}
81
82/// Where a loop is. `Ended` keeps its reason rather than forgetting it: "it stopped" is never the
83/// answer someone wants, and a loop that ran out of `--times` is a different thing from one that
84/// was told to stop.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "lowercase")]
87pub enum Status {
88    Running,
89    Paused,
90    Ended,
91}
92
93/// Why a loop is over.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "snake_case")]
96pub enum Ended {
97    /// `--times` reached.
98    Times,
99    /// `--until` answered yes.
100    Until,
101    /// `/loop stop`.
102    Stopped,
103    /// The session could not be run at all, and retrying would repeat the same failure.
104    Failed,
105}
106
107impl Ended {
108    pub fn sentence(self) -> &'static str {
109        match self {
110            Ended::Times => "it reached the number of ticks it was given",
111            Ended::Until => "its condition was met",
112            Ended::Stopped => "it was stopped",
113            Ended::Failed => "it failed",
114        }
115    }
116}
117
118/// Which process is driving the timer. A loop is not resumable across processes by default: the
119/// front that started it owns it, and the record says whose it is so a reader can tell a
120/// running loop from a stale one left behind by a CLI that exited.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "lowercase")]
123pub enum Owner {
124    Cli,
125    Gateway,
126}
127
128/// One session's loop, as it is written to disk.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub struct State {
131    pub session: String,
132    pub prompt: String,
133    /// `Schedule::describe()`'s own words — the same text `/loop status` prints, re-parsed on
134    /// load, so the file cannot hold a schedule the parser would refuse.
135    pub interval: String,
136    #[serde(default)]
137    pub times: Option<u32>,
138    #[serde(default)]
139    pub until: Option<String>,
140    pub status: Status,
141    #[serde(default)]
142    pub ended: Option<Ended>,
143    /// Ticks that actually ran.
144    pub fired: u32,
145    /// Ticks that landed while a run was in flight. Recorded, never queued: a backlog of ticks
146    /// arriving at once is a busy loop with a schedule's name on it.
147    #[serde(default)]
148    pub skipped: u32,
149    /// When this tick's successor is due, in epoch ms. Zero when the loop has not started or has
150    /// ended.
151    pub next_due_ms: i64,
152    pub created_ms: i64,
153    pub owner: Owner,
154    pub owner_pid: u32,
155    /// The last thing worth saying about this loop: a skipped tick, a refused `--until` answer.
156    #[serde(default)]
157    pub note: Option<String>,
158}
159
160impl State {
161    /// A fresh loop, due one interval from now — not immediately, because starting something and
162    /// firing it in the same second is not what "every 2m" means.
163    pub fn start(session: &str, spec: Spec, owner: Owner, now_ms: i64) -> State {
164        State {
165            session: session.to_string(),
166            prompt: spec.prompt,
167            interval: spec.schedule.describe(),
168            times: spec.times,
169            until: spec.until,
170            status: Status::Running,
171            ended: None,
172            fired: 0,
173            skipped: 0,
174            // Armed from the schedule itself: for an interval that is `now + interval`, and for
175            // a `daily 07:30` it is the next 07:30 rather than "now plus a day's worth of
176            // milliseconds since the epoch", which is what multiplying an interval out would say.
177            next_due_ms: spec.schedule.next_due(now_ms),
178            created_ms: now_ms,
179            owner,
180            owner_pid: std::process::id(),
181            note: None,
182        }
183    }
184
185    /// The schedule this record names, or the parse error that says the file was edited badly.
186    pub fn schedule(&self) -> Result<Schedule> {
187        Schedule::parse(&self.interval)
188    }
189
190    pub fn spec(&self) -> Result<Spec> {
191        Ok(Spec {
192            prompt: self.prompt.clone(),
193            schedule: self.schedule()?,
194            times: self.times,
195            until: self.until.clone(),
196        })
197    }
198
199    /// Whether a tick is owed now.
200    pub fn due(&self, now_ms: i64) -> bool {
201        self.status == Status::Running && now_ms >= self.next_due_ms
202    }
203
204    /// Record what happened to the tick that was due, and arm the next one.
205    ///
206    /// The next moment is counted from *this* tick rather than from the one before it, so a tick
207    /// that ran for two intervals does not fire twice in a row to catch up. A skipped tick is
208    /// armed the same way: a busy session loses that tick and the schedule keeps its shape.
209    pub fn record(&mut self, now_ms: i64, outcome: Outcome) {
210        match outcome {
211            Outcome::Ran => {
212                self.fired = self.fired.saturating_add(1);
213                self.note = None;
214                if let Some(limit) = self.times {
215                    if self.fired >= limit {
216                        return self.end(Ended::Times);
217                    }
218                }
219            }
220            Outcome::Skipped(why) => {
221                self.skipped = self.skipped.saturating_add(1);
222                self.note = Some(format!("skipped: {why}"));
223            }
224            Outcome::Failed(why) => {
225                self.note = Some(format!("failed: {why}"));
226            }
227        }
228        if self.status == Status::Running {
229            self.next_due_ms = self.arm(now_ms);
230        }
231    }
232
233    pub fn end(&mut self, why: Ended) {
234        self.status = Status::Ended;
235        self.ended = Some(why);
236        self.next_due_ms = 0;
237    }
238
239    pub fn pause(&mut self) {
240        if self.status == Status::Running {
241            self.status = Status::Paused;
242        }
243    }
244
245    /// The moment this loop's next tick is due, counted from `now_ms`.
246    fn arm(&self, now_ms: i64) -> i64 {
247        match self.schedule() {
248            Ok(schedule) => schedule.next_due(now_ms),
249            // A record whose interval no longer parses cannot be armed; fall back to cron's floor
250            // so the loop keeps running and the readout carries the parse failure.
251            Err(_) => now_ms.saturating_add(60_000),
252        }
253    }
254
255    /// Resume, due one interval from now: a loop paused for an hour does not owe an hour of ticks.
256    pub fn resume(&mut self, now_ms: i64) {
257        if self.status == Status::Paused {
258            self.status = Status::Running;
259            self.next_due_ms = self.arm(now_ms);
260        }
261    }
262
263    /// Whether the process that owns this loop is still the one running it.
264    ///
265    /// This is the honest answer to "is my loop still going" after a CLI exited: the record is
266    /// still on disk, and it is still `Running`, but nobody is driving it. Unix asks the kernel;
267    /// elsewhere the answer is assumed to be yes rather than invented from nothing.
268    pub fn owner_alive(&self) -> bool {
269        if self.owner_pid == std::process::id() {
270            return true;
271        }
272        #[cfg(unix)]
273        {
274            // SAFETY: `kill` with signal 0 only performs the permission and existence check.
275            let alive = unsafe { libc::kill(self.owner_pid as libc::pid_t, 0) } == 0;
276            // EPERM means it exists and belongs to someone else, which is still alive.
277            alive || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
278        }
279        #[cfg(not(unix))]
280        {
281            true
282        }
283    }
284
285    /// One line after a tick, when there is something worth saying: an ending, a skip, a failure.
286    /// `None` when the tick simply ran — a loop that works should not narrate every minute.
287    pub fn tick_note(&self) -> Option<String> {
288        match self.status {
289            Status::Ended => Some(format!(
290                "loop ended — {}",
291                self.readout(crate::session::now_ms() as i64)
292            )),
293            _ => self.note.as_ref().map(|note| format!("loop tick {note}")),
294        }
295    }
296
297    /// The one line a front puts on screen for `/loop status`.
298    pub fn readout(&self, now_ms: i64) -> String {
299        let mut line = match self.status {
300            Status::Running => {
301                if self.owner_alive() {
302                    let left = (self.next_due_ms - now_ms).max(0) as u64;
303                    format!(
304                        "loop running · {} · {}/{} ticks · next in {}",
305                        self.interval,
306                        self.fired,
307                        self.times
308                            .map(|n| n.to_string())
309                            .unwrap_or_else(|| "∞".to_string()),
310                        duration(left / 1000)
311                    )
312                } else {
313                    // The record outlived the process that was driving it. Say so rather than
314                    // printing a countdown to a tick nobody is going to send.
315                    format!(
316                        "loop was running · {} · {}/{} ticks · the process that owned it (pid {}) \
317                         has exited, so nothing is ticking",
318                        self.interval,
319                        self.fired,
320                        self.times
321                            .map(|n| n.to_string())
322                            .unwrap_or_else(|| "∞".to_string()),
323                        self.owner_pid
324                    )
325                }
326            }
327            Status::Paused => format!(
328                "loop paused · {} · {}/{} ticks",
329                self.interval,
330                self.fired,
331                self.times
332                    .map(|n| n.to_string())
333                    .unwrap_or_else(|| "∞".to_string())
334            ),
335            Status::Ended => format!(
336                "loop ended · {} · {} ticks — {}",
337                self.interval,
338                self.fired,
339                self.ended.map(|e| e.sentence()).unwrap_or("stopped")
340            ),
341        };
342        if !self.prompt.is_empty() {
343            line.push_str(&format!(" · {:?}", ellipsis(&self.prompt, 48)));
344        }
345        if let Some(note) = &self.note {
346            line.push_str(&format!(" · {note}"));
347        }
348        line
349    }
350}
351
352/// What a tick turned out to be. The caller decides — this module only records it.
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub enum Outcome {
355    /// The run happened (whatever it answered).
356    Ran,
357    /// The tick landed while the session was busy, so it was dropped rather than queued.
358    Skipped(String),
359    /// The run itself could not be made to happen.
360    Failed(String),
361}
362
363/// What a `--until` answer means. Three answers, not two: an unreadable reply is not a "no", and
364/// treating it as one would end a loop because a model was verbose.
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub enum Verdict {
367    Reached,
368    KeepGoing,
369    Unreadable,
370}
371
372impl Verdict {
373    pub fn as_str(self) -> &'static str {
374        match self {
375            Verdict::Reached => "reached",
376            Verdict::KeepGoing => "keep going",
377            Verdict::Unreadable => "unreadable",
378        }
379    }
380}
381
382/// Read one yes/no answer strictly.
383///
384/// The first word decides, after trimming quotes and punctuation: `yes.` and `"yes"` are both yes,
385/// and `yes, but…` is still yes because the word that answers the question came first. Anything
386/// else is [`Verdict::Unreadable`] — an explanation is not an answer, and guessing which way it
387/// leans is how a loop stops on a model's rambling.
388pub fn verdict(answer: &str) -> Verdict {
389    let first = answer
390        .trim()
391        .trim_start_matches(['"', '\'', '`', '*', ' '])
392        .split(|c: char| c.is_whitespace() || matches!(c, ',' | '.' | '!' | '?' | ';' | ':'))
393        .find(|w| !w.is_empty())
394        .unwrap_or("")
395        .trim_end_matches(['"', '\'', '`', '*'])
396        .to_ascii_lowercase();
397    match first.as_str() {
398        "yes" | "y" | "true" | "reached" | "stop" | "done" => Verdict::Reached,
399        "no" | "n" | "false" | "continue" | "keep" | "going" => Verdict::KeepGoing,
400        _ => Verdict::Unreadable,
401    }
402}
403
404/// The exact request a `--until` check makes. One question, one word back.
405pub fn until_prompt(condition: &str, last_reply: Option<&str>) -> [crate::message::Message; 2] {
406    const SYSTEM: &str = "\
407You judge one condition. You are given a condition and the reply the agent just produced. Answer \
408with exactly one word: yes if the condition is met, no if it is not. Do not explain, do not add \
409punctuation, do not answer anything else.";
410    let mut user = format!("CONDITION: {condition}");
411    match last_reply.map(str::trim).filter(|r| !r.is_empty()) {
412        Some(reply) => {
413            user.push_str("\n\nTHE REPLY JUST PRODUCED:\n");
414            // Long enough for the part of the reply that answers a condition, short enough that
415            // the aux route's window is never the reason the check fails.
416            user.push_str(&ellipsis(reply, 4_000));
417        }
418        None => user.push_str("\n\nTHE REPLY JUST PRODUCED: (the turn produced no text)"),
419    }
420    [
421        crate::message::Message::system(SYSTEM),
422        crate::message::Message::user(user),
423    ]
424}
425
426/// Parse everything after the `/loop` word.
427///
428/// Grammar, in one place so `/help` and the parser cannot drift:
429///
430/// ```text
431/// /loop                                    status
432/// /loop status | pause | resume | stop     manage it without leaving the session
433/// /loop <interval> <prompt> [--times N] [--until <condition>]
434/// ```
435///
436/// `<interval>` is cron's grammar (`every 30m`, `hourly`, `daily 07:30`) **and** a bare interval
437/// (`2m`, `90s`, `1h`) meaning `every 2m`. Requiring the word "every" would make the one form
438/// everyone types the one form the parser refuses.
439pub fn parse(arg: &str) -> Result<Request> {
440    let text = arg.trim();
441    if text.is_empty() || text.eq_ignore_ascii_case("status") {
442        return Ok(Request::Status);
443    }
444    for (word, request) in [
445        ("pause", Request::Pause),
446        ("resume", Request::Resume),
447        ("stop", Request::Stop),
448    ] {
449        if text.eq_ignore_ascii_case(word) {
450            return Ok(request);
451        }
452    }
453    let mut words = text.split_whitespace().peekable();
454    let interval_word = words.next().expect("text is not empty");
455    let schedule = interval(interval_word)?;
456    // Flags are pulled out from anywhere after the interval, so `--times` before the prompt and
457    // `--times` after it both work. The prompt is what is left, in order.
458    let mut prompt: Vec<&str> = Vec::new();
459    let mut times: Option<u32> = None;
460    let mut until: Option<String> = None;
461    while let Some(word) = words.next() {
462        match word {
463            "--times" | "-n" => {
464                let raw = words.next().ok_or_else(|| {
465                    Error::Config("`--times` needs a number: `/loop 2m <prompt> --times 3`".into())
466                })?;
467                let n: u32 = raw.parse().map_err(|_| {
468                    Error::Config(format!(
469                        "`--times {raw}` is not a count; write a whole number of ticks"
470                    ))
471                })?;
472                if n == 0 {
473                    return Err(Error::Config(
474                        "`--times 0` is a loop that never runs; drop the flag for no bound".into(),
475                    ));
476                }
477                if n > MAX_TIMES {
478                    return Err(Error::Config(format!(
479                        "`--times {n}` is more than {MAX_TIMES}; an unbounded loop is written by \
480                         leaving the flag out"
481                    )));
482                }
483                times = Some(n);
484            }
485            "--until" => {
486                let mut condition: Vec<&str> = Vec::new();
487                while let Some(next) = words.peek() {
488                    if next.starts_with("--") {
489                        break;
490                    }
491                    condition.push(words.next().expect("peeked"));
492                }
493                let condition = condition.join(" ");
494                if condition.trim().is_empty() {
495                    return Err(Error::Config(
496                        "`--until` needs a condition: `/loop 2m <prompt> --until the build is green`"
497                            .into(),
498                    ));
499                }
500                until = Some(unquote(&condition));
501            }
502            other if other.starts_with("--") => {
503                return Err(Error::Config(format!(
504                    "unknown flag {other:?}; the flags are `--times N` and `--until <condition>`"
505                )));
506            }
507            other => prompt.push(other),
508        }
509    }
510    let prompt = unquote(&prompt.join(" "));
511    if prompt.is_empty() {
512        return Err(Error::Config(
513            "a loop needs something to say: `/loop 2m <prompt>`".into(),
514        ));
515    }
516    Ok(Request::Start(Spec {
517        prompt,
518        schedule,
519        times,
520        until,
521    }))
522}
523
524/// An interval: cron's grammar, or a bare one. `2m` is `every 2m`; `every 2m` is unchanged.
525pub fn interval(text: &str) -> Result<Schedule> {
526    let t = text.trim();
527    if is_bare_interval(t) {
528        // Through the same parser, so the floor, the overflow check and the error sentence are
529        // cron's and not a second set that can disagree with it.
530        return Schedule::parse(&format!("every {t}"));
531    }
532    Schedule::parse(t).map_err(|_| {
533        Error::Config(format!(
534            "{t:?} is not an interval. Write `2m`, `90s`, `every 30m`, `hourly` or \
535             `daily 07:30` — the same grammar cron takes"
536        ))
537    })
538}
539
540/// `<digits><unit>` with no space: the short form people type.
541fn is_bare_interval(text: &str) -> bool {
542    let split = text
543        .find(|c: char| !c.is_ascii_digit())
544        .unwrap_or(text.len());
545    let (number, unit) = text.split_at(split);
546    !number.is_empty() && matches!(unit, "s" | "m" | "h" | "d")
547}
548
549/// Strip one pair of matching surrounding quotes, so a quoted prompt arrives without them.
550fn unquote(text: &str) -> String {
551    let t = text.trim();
552    for q in ['"', '\''] {
553        if t.len() >= 2 && t.starts_with(q) && t.ends_with(q) {
554            return t[1..t.len() - 1].trim().to_string();
555        }
556    }
557    t.to_string()
558}
559
560/// `text` cut to `max` characters at a word boundary where there is one, on one line.
561fn ellipsis(text: &str, max: usize) -> String {
562    let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
563    if flat.chars().count() <= max {
564        return flat;
565    }
566    let mut cut = flat
567        .char_indices()
568        .nth(max.saturating_sub(1))
569        .map(|(i, _)| i)
570        .unwrap_or(flat.len());
571    if let Some(space) = flat[..cut].rfind(' ') {
572        if space > max / 2 {
573            cut = space;
574        }
575    }
576    format!("{}…", flat[..cut].trim_end())
577}
578
579/// A duration as a person reads a countdown: `45s`, `2m 10s`, `1h 5m`.
580pub fn duration(secs: u64) -> String {
581    match secs {
582        0..=59 => format!("{secs}s"),
583        60..=3599 => {
584            let (m, s) = (secs / 60, secs % 60);
585            if s == 0 {
586                format!("{m}m")
587            } else {
588                format!("{m}m {s}s")
589            }
590        }
591        _ => {
592            let (h, m) = (secs / 3600, (secs % 3600) / 60);
593            if m == 0 {
594                format!("{h}h")
595            } else {
596                format!("{h}h {m}m")
597            }
598        }
599    }
600}
601
602/// Answer one `/loop …` line, managing a loop that already exists.
603///
604/// Every verb but `start` reads and writes the record on disk, so a `/loop stop` typed into a
605/// session whose timer belongs to another process still lands: the record is the one copy. A
606/// `start` is the front's own business beyond the record, because it is the front that has to take
607/// on the timer — the terminal's interface ticks from its event loop, and the dashboard's gateway
608/// ticks from a task.
609pub fn manage(root: &Path, session: &str, arg: &str, owner: Owner, now_ms: i64) -> Result<String> {
610    match parse(arg)? {
611        Request::Start(spec) => {
612            if let Some(mut existing) = load(root, session)? {
613                // One loop per session: two timers into one conversation is a race with a nicer
614                // name, and the second one is nearly always a typo rather than an intent.
615                if existing.status == Status::Running && existing.owner_alive() {
616                    return Err(Error::Config(format!(
617                        "this session already has a loop running ({}). `/loop status` shows it, \
618                         `/loop stop` ends it",
619                        existing.readout(now_ms)
620                    )));
621                }
622                if existing.status == Status::Paused {
623                    return Err(Error::Config(format!(
624                        "this session's loop is paused ({}). `/loop resume` continues it, \
625                         `/loop stop` ends it",
626                        existing.readout(now_ms)
627                    )));
628                }
629                existing.end(Ended::Stopped);
630            }
631            let state = State::start(session, spec, owner, now_ms);
632            let said = start_sentence(&state, now_ms);
633            save(root, &state)?;
634            Ok(said)
635        }
636        Request::Status => {
637            let Some(state) = load(root, session)? else {
638                return Ok(
639                    "no loop in this session. `/loop 2m <prompt>` starts one (`/cron` is the \
640                     timer that outlives this process)"
641                        .to_string(),
642                );
643            };
644            Ok(state.readout(now_ms))
645        }
646        Request::Pause => {
647            let Some(mut state) = load(root, session)? else {
648                return Err(Error::Config("no loop in this session to pause".into()));
649            };
650            if state.status != Status::Running {
651                return Ok(state.readout(now_ms));
652            }
653            state.pause();
654            save(root, &state)?;
655            Ok(format!(
656                "loop paused — {} ticks so far; `/loop resume` picks it up one interval from then",
657                state.fired
658            ))
659        }
660        Request::Resume => {
661            let Some(mut state) = load(root, session)? else {
662                return Err(Error::Config("no loop in this session to resume".into()));
663            };
664            if state.status == Status::Ended {
665                return Err(Error::Config(format!(
666                    "this loop has ended — {}; start a new one with `/loop <interval> <prompt>`",
667                    state.readout(now_ms)
668                )));
669            }
670            state.resume(now_ms);
671            let said = format!(
672                "loop resumed — next tick in {}",
673                duration(((state.next_due_ms - now_ms).max(0) / 1000) as u64)
674            );
675            save(root, &state)?;
676            Ok(said)
677        }
678        Request::Stop => {
679            let Some(mut state) = load(root, session)? else {
680                return Ok("no loop in this session".to_string());
681            };
682            let fired = state.fired;
683            state.end(Ended::Stopped);
684            save(root, &state)?;
685            Ok(format!("loop stopped after {fired} tick(s)"))
686        }
687    }
688}
689
690/// The line `/loop <interval> <prompt>` answers with. It names what will happen *and* what will
691/// not: a loop dies with the process that owns it, and a person who is not told that finds out by
692/// being surprised.
693fn start_sentence(state: &State, now_ms: i64) -> String {
694    let wait = ((state.next_due_ms - now_ms).max(0) / 1000) as u64;
695    let bound = match (state.times, &state.until) {
696        (None, None) => String::new(),
697        (Some(n), None) => format!(", at most {n}"),
698        (None, Some(c)) => format!(", until {c}"),
699        (Some(n), Some(c)) => format!(", at most {n} or until {c}"),
700    };
701    format!(
702        "loop started · {} · first tick in {}{bound} — it runs in this session, so its ticks carry \
703         what the last one produced; it stops when this process exits (`/cron` is the timer that \
704         survives that)",
705        state.interval,
706        duration(wait)
707    )
708}
709
710/// Read a session's loop, if it has one.
711pub fn load(root: &Path, session: &str) -> Result<Option<State>> {
712    let path = state_path(root, session)?;
713    let text = match std::fs::read_to_string(&path) {
714        Ok(text) => text,
715        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
716        Err(e) => return Err(Error::io(&path, e)),
717    };
718    let state: State = serde_json::from_str(&text).map_err(|e| {
719        Error::Config(format!(
720            "{} is not a loop record ({e}); `/loop stop` clears it",
721            path.display()
722        ))
723    })?;
724    Ok(Some(state))
725}
726
727/// Write a session's loop. The write is atomic, so a reader never sees half a record.
728pub fn save(root: &Path, state: &State) -> Result<()> {
729    let path = state_path(root, &state.session)?;
730    if let Some(parent) = path.parent() {
731        std::fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
732    }
733    let text = serde_json::to_string_pretty(state)
734        .map_err(|e| Error::Config(format!("could not encode the loop record: {e}")))?;
735    crate::atomic::write_file_atomically(&path, &text).map_err(|e| Error::io(&path, e))?;
736    Ok(())
737}
738
739/// Forget a session's loop.
740pub fn clear(root: &Path, session: &str) -> Result<()> {
741    let path = state_path(root, session)?;
742    match std::fs::remove_file(&path) {
743        Ok(()) => Ok(()),
744        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
745        Err(e) => Err(Error::io(&path, e)),
746    }
747}
748
749/// Every loop this install has a record of, running or not — newest first.
750pub fn all(root: &Path) -> Result<Vec<State>> {
751    let dir = dir(root);
752    let entries = match std::fs::read_dir(&dir) {
753        Ok(entries) => entries,
754        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
755        Err(e) => return Err(Error::io(&dir, e)),
756    };
757    let mut found: Vec<State> = Vec::new();
758    for entry in entries.flatten() {
759        let path = entry.path();
760        if path.extension().and_then(|e| e.to_str()) != Some("json") {
761            continue;
762        }
763        match std::fs::read_to_string(&path)
764            .ok()
765            .and_then(|text| serde_json::from_str::<State>(&text).ok())
766        {
767            Some(state) => found.push(state),
768            // A half-written or hand-broken file is not this call's problem: the session that
769            // owns it reports the parse error when it reads its own record.
770            None => continue,
771        }
772    }
773    found.sort_by_key(|s| std::cmp::Reverse(s.created_ms));
774    Ok(found)
775}
776
777#[cfg(test)]
778mod tests {
779    use super::*;
780    use crate::cron::Schedule;
781
782    fn root() -> tempfile::TempDir {
783        tempfile::tempdir().expect("temp dir")
784    }
785
786    #[test]
787    fn a_bare_interval_is_an_interval_and_the_word_every_is_optional() {
788        assert_eq!(interval("2m").unwrap(), Schedule::Every(120));
789        assert_eq!(interval("90s").unwrap(), Schedule::Every(90));
790        assert_eq!(interval("1h").unwrap(), Schedule::Every(3_600));
791        assert_eq!(interval("every 2m").unwrap(), Schedule::Every(120));
792        assert_eq!(interval("hourly").unwrap(), Schedule::Every(3_600));
793        assert!(matches!(
794            interval("daily 07:30").unwrap(),
795            Schedule::Daily { .. }
796        ));
797    }
798
799    #[test]
800    fn an_interval_finer_than_a_minute_is_refused_in_the_parsers_own_words() {
801        let why = interval("5s").unwrap_err().to_string();
802        assert!(why.contains("finer than a minute"), "{why}");
803        assert!(interval("2").is_err());
804        assert!(interval("soon").is_err());
805    }
806
807    #[test]
808    fn a_loop_line_carries_a_prompt_and_both_bounds() {
809        let Request::Start(spec) =
810            parse("2m check the build --times 3 --until the build is green").unwrap()
811        else {
812            panic!("not a start");
813        };
814        assert_eq!(spec.prompt, "check the build");
815        assert_eq!(spec.schedule, Schedule::Every(120));
816        assert_eq!(spec.times, Some(3));
817        assert_eq!(spec.until.as_deref(), Some("the build is green"));
818    }
819
820    #[test]
821    fn a_quoted_prompt_loses_its_quotes_and_keeps_its_words() {
822        let Request::Start(spec) = parse("2m \"check whether the build is green\"").unwrap() else {
823            panic!("not a start");
824        };
825        assert_eq!(spec.prompt, "check whether the build is green");
826        assert_eq!(spec.times, None);
827    }
828
829    #[test]
830    fn the_managing_words_do_not_start_a_loop() {
831        assert_eq!(parse("").unwrap(), Request::Status);
832        assert_eq!(parse("status").unwrap(), Request::Status);
833        assert_eq!(parse("PAUSE").unwrap(), Request::Pause);
834        assert_eq!(parse("resume").unwrap(), Request::Resume);
835        assert_eq!(parse("stop").unwrap(), Request::Stop);
836    }
837
838    #[test]
839    fn a_line_with_no_interval_and_no_prompt_is_refused_rather_than_guessed() {
840        assert!(parse("check the build").is_err());
841        assert!(parse("2m")
842            .unwrap_err()
843            .to_string()
844            .contains("needs something"));
845        assert!(parse("2m x --times").is_err());
846        assert!(parse("2m x --times 0").is_err());
847        assert!(parse("2m x --times 999999999").is_err());
848        assert!(parse("2m x --every 2m").is_err());
849        assert!(parse("2m x --until").is_err());
850    }
851
852    #[test]
853    fn a_tick_is_due_only_after_its_interval_and_only_while_running() {
854        let spec = parse("2m go").unwrap();
855        let Request::Start(spec) = spec else {
856            unreachable!()
857        };
858        let mut state = State::start("s1", spec, Owner::Cli, 1_000);
859        assert_eq!(state.next_due_ms, 1_000 + 120_000);
860        assert!(!state.due(120_999));
861        assert!(state.due(121_000));
862        state.pause();
863        assert!(!state.due(999_999));
864        state.resume(999_999);
865        assert!(!state.due(999_999), "a resumed loop waits its interval");
866        assert!(state.due(999_999 + 120_000));
867    }
868
869    #[test]
870    fn a_run_counts_and_arms_the_next_tick_from_the_one_that_ran() {
871        let Request::Start(spec) = parse("2m go").unwrap() else {
872            panic!()
873        };
874        let mut state = State::start("s1", spec, Owner::Cli, 0);
875        state.record(120_000, Outcome::Ran);
876        assert_eq!(state.fired, 1);
877        // Counted from this tick, not from the one before it: a run that overran does not owe a
878        // backlog.
879        assert_eq!(state.next_due_ms, 240_000);
880        assert_eq!(state.status, Status::Running);
881    }
882
883    #[test]
884    fn times_stops_the_loop_after_that_many_runs() {
885        let Request::Start(spec) = parse("2m go --times 2").unwrap() else {
886            panic!()
887        };
888        let mut state = State::start("s1", spec, Owner::Cli, 0);
889        state.record(120_000, Outcome::Ran);
890        assert_eq!(state.status, Status::Running);
891        state.record(240_000, Outcome::Ran);
892        assert_eq!(state.status, Status::Ended);
893        assert_eq!(state.ended, Some(Ended::Times));
894        assert_eq!(state.next_due_ms, 0);
895        assert!(!state.due(999_999));
896    }
897
898    #[test]
899    fn a_skipped_tick_is_recorded_and_does_not_consume_a_run() {
900        let Request::Start(spec) = parse("2m go --times 2").unwrap() else {
901            panic!()
902        };
903        let mut state = State::start("s1", spec, Owner::Cli, 0);
904        state.record(120_000, Outcome::Skipped("a run is in flight".into()));
905        assert_eq!(state.fired, 0);
906        assert_eq!(state.skipped, 1);
907        // The schedule keeps its shape: the next tick is one interval after the skipped one.
908        assert_eq!(state.next_due_ms, 240_000);
909        assert!(state.note.as_deref().unwrap().contains("in flight"));
910        assert_eq!(state.status, Status::Running);
911    }
912
913    #[test]
914    fn a_failed_tick_is_recorded_and_the_loop_goes_on() {
915        let Request::Start(spec) = parse("2m go").unwrap() else {
916            panic!()
917        };
918        let mut state = State::start("s1", spec, Owner::Cli, 0);
919        state.record(120_000, Outcome::Failed("the route refused".into()));
920        assert_eq!(state.status, Status::Running);
921        assert_eq!(state.next_due_ms, 240_000);
922        assert!(state.note.as_deref().unwrap().contains("the route refused"));
923    }
924
925    #[test]
926    fn a_yes_no_answer_is_read_strictly_and_an_explanation_is_not_an_answer() {
927        for yes in [
928            "yes",
929            "YES",
930            "yes.",
931            "\"yes\"",
932            "yes, the build is green",
933            "true",
934        ] {
935            assert_eq!(verdict(yes), Verdict::Reached, "{yes:?}");
936        }
937        for no in ["no", "NO", "no.", "false", "continue", "keep going"] {
938            assert_eq!(verdict(no), Verdict::KeepGoing, "{no:?}");
939        }
940        for neither in ["", "   ", "it depends", "probably", "maybe not"] {
941            assert_eq!(verdict(neither), Verdict::Unreadable, "{neither:?}");
942        }
943    }
944
945    #[test]
946    fn the_until_request_carries_the_condition_and_the_reply() {
947        let request = until_prompt("the build is green", Some("build is green now"));
948        assert!(request[0].content.as_deref().unwrap().contains("one word"));
949        let user = request[1].content.as_deref().unwrap();
950        assert!(user.contains("CONDITION: the build is green"), "{user}");
951        assert!(user.contains("build is green now"), "{user}");
952        let empty = until_prompt("x", None);
953        assert!(
954            empty[1].content.as_deref().unwrap().contains("no text"),
955            "a turn with no text is said, not left blank"
956        );
957    }
958
959    #[test]
960    fn a_record_round_trips_through_the_file() {
961        let dir = root();
962        let Request::Start(spec) = parse("2m go --until it is green").unwrap() else {
963            panic!()
964        };
965        let mut state = State::start("s1", spec, Owner::Gateway, 500);
966        state.record(120_500, Outcome::Ran);
967        save(dir.path(), &state).unwrap();
968        let back = load(dir.path(), "s1").unwrap().expect("saved");
969        assert_eq!(back, state);
970        assert_eq!(back.schedule().unwrap(), Schedule::Every(120));
971        assert_eq!(back.spec().unwrap().until.as_deref(), Some("it is green"));
972        clear(dir.path(), "s1").unwrap();
973        assert!(load(dir.path(), "s1").unwrap().is_none());
974        // Clearing what is not there is not an error.
975        clear(dir.path(), "s1").unwrap();
976    }
977
978    #[test]
979    fn a_session_id_that_could_walk_out_of_the_directory_is_refused() {
980        let dir = root();
981        assert!(state_path(dir.path(), "../etc/passwd").is_err());
982        assert!(load(dir.path(), "../../x").is_err());
983    }
984
985    #[test]
986    fn all_lists_every_record_and_skips_a_broken_one() {
987        let dir = root();
988        for (id, at) in [("a", 1_000), ("b", 2_000)] {
989            let Request::Start(spec) = parse("1m go").unwrap() else {
990                panic!()
991            };
992            save(dir.path(), &State::start(id, spec, Owner::Cli, at)).unwrap();
993        }
994        std::fs::write(super::dir(dir.path()).join("broken.json"), "{not json").unwrap();
995        let found = all(dir.path()).unwrap();
996        assert_eq!(
997            found.iter().map(|s| s.session.as_str()).collect::<Vec<_>>(),
998            ["b", "a"],
999            "newest first, and a file that does not parse is not a record"
1000        );
1001    }
1002
1003    #[test]
1004    fn an_empty_install_has_no_loops_rather_than_an_error() {
1005        let dir = root();
1006        assert!(all(dir.path()).unwrap().is_empty());
1007        assert!(load(dir.path(), "s1").unwrap().is_none());
1008    }
1009
1010    #[test]
1011    fn the_readout_names_the_state_the_counts_and_the_next_tick() {
1012        let Request::Start(spec) = parse("2m write the report --times 5").unwrap() else {
1013            panic!()
1014        };
1015        let mut state = State::start("s1", spec, Owner::Cli, 0);
1016        state.record(120_000, Outcome::Ran);
1017        let line = state.readout(150_000);
1018        assert!(
1019            line.starts_with("loop running · every 2m · 1/5 ticks · next in 1m 30s"),
1020            "{line}"
1021        );
1022        assert!(line.contains("write the report"), "{line}");
1023        state.end(Ended::Times);
1024        let line = state.readout(150_000);
1025        assert!(line.contains("loop ended") && line.contains("2m"), "{line}");
1026    }
1027
1028    #[test]
1029    fn a_record_whose_process_is_gone_says_so_instead_of_counting_down() {
1030        let Request::Start(spec) = parse("2m go").unwrap() else {
1031            panic!()
1032        };
1033        let mut state = State::start("s1", spec, Owner::Cli, 0);
1034        // A pid that cannot be running: pid 1 is init and is not this process, so use a value
1035        // that the kernel will refuse. Linux's default pid_max is well under this.
1036        state.owner_pid = 4_194_304;
1037        assert!(!state.owner_alive());
1038        let line = state.readout(150_000);
1039        assert!(line.contains("has exited"), "{line}");
1040        assert!(!line.contains("next in"), "{line}");
1041    }
1042
1043    #[test]
1044    fn the_summary_names_the_bound_it_was_given() {
1045        let Request::Start(spec) = parse("2m go --times 2 --until it is green").unwrap() else {
1046            panic!()
1047        };
1048        let summary = spec.summary();
1049        assert!(summary.starts_with("every 2m: go"), "{summary}");
1050        assert!(summary.contains("at most 2"), "{summary}");
1051        assert!(summary.contains("until it is green"), "{summary}");
1052        let unbounded = Spec {
1053            prompt: "go".into(),
1054            schedule: Schedule::Every(60),
1055            times: None,
1056            until: None,
1057        };
1058        assert!(
1059            !unbounded.summary().contains("at most"),
1060            "{}",
1061            unbounded.summary()
1062        );
1063    }
1064
1065    #[test]
1066    fn a_countdown_reads_the_way_a_person_says_it() {
1067        assert_eq!(duration(0), "0s");
1068        assert_eq!(duration(45), "45s");
1069        assert_eq!(duration(60), "1m");
1070        assert_eq!(duration(130), "2m 10s");
1071        assert_eq!(duration(3_600), "1h");
1072        assert_eq!(duration(3_900), "1h 5m");
1073    }
1074}