eclipse-core 0.14.0

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
//! `#173`: `/loop` — one prompt, re-entered into *this* session on an interval.
//!
//! Not cron, and the difference is the whole point. A cron job is its own session on its own
//! timer, owned by the systemd unit, and it survives this CLI exiting. A loop is a prompt sent
//! back into the conversation that is already open, so every tick carries the history the last
//! one produced — the session id never changes, and history is free.
//!
//! Who owns the timer is therefore a fact about the process, not about the feature: whichever
//! front is running the session drives it. In the full-screen interface and the dashboard the
//! timer lives in that process's event loop or in the gateway, and it keeps firing while nobody
//! is typing. In the plain REPL the line editor owns the terminal, so a tick lands between turns
//! and the readout says so. A loop that stops because its process exited is not a bug; it is the
//! shape of the thing, and `/help` says it in one line.
//!
//! Nothing here runs an agent and nothing here talks to a provider. [`parse`] turns a typed line
//! into a request, [`State`] is the record of one session's loop, and [`State::due`] decides with
//! a clock the caller supplies — so the interesting parts are testable without a model, a
//! terminal or a sleep. The caller runs, and reports back through [`Outcome`].
//!
//! The record lives in `<root>/state/loops/<session>.json`, one file per session: the CLI and the
//! dashboard read the same bytes, and a second process cannot keep a private copy of what the
//! first one is doing.

use crate::cron::Schedule;
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Where a loop's record lives: `<root>/state/loops`.
pub fn dir(root: &Path) -> PathBuf {
    root.join("state").join("loops")
}

/// The record for one session: `<root>/state/loops/<session>.json`.
pub fn state_path(root: &Path, session: &str) -> Result<PathBuf> {
    crate::session::validate_id(session)?;
    Ok(dir(root).join(format!("{session}.json")))
}

/// A ceiling on `--times`, because a bound that large is a way of writing "forever" with a
/// number that looks deliberate. An unbounded loop is spelled by saying nothing.
pub const MAX_TIMES: u32 = 100_000;

/// What one typed `/loop` line asked for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Request {
    /// `/loop 2m <prompt>` — start one in this session.
    Start(Spec),
    /// `/loop` or `/loop status`.
    Status,
    Pause,
    Resume,
    Stop,
}

/// What a loop was told to do: the prompt, how often, and its two bounds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Spec {
    pub prompt: String,
    /// One of cron's schedules. `Every` is the ordinary case; the named moments are accepted
    /// because they come from the same parser and refusing them would be a second grammar.
    pub schedule: Schedule,
    /// Stop after this many ticks that actually ran. `None` is unbounded.
    pub times: Option<u32>,
    /// A yes/no question asked on the aux route after each tick. `None` never asks.
    pub until: Option<String>,
}

impl Spec {
    /// One line naming what this loop does, for a readout or a refusal.
    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)
    }
}

/// Where a loop is. `Ended` keeps its reason rather than forgetting it: "it stopped" is never the
/// answer someone wants, and a loop that ran out of `--times` is a different thing from one that
/// was told to stop.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    Running,
    Paused,
    Ended,
}

/// Why a loop is over.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Ended {
    /// `--times` reached.
    Times,
    /// `--until` answered yes.
    Until,
    /// `/loop stop`.
    Stopped,
    /// The session could not be run at all, and retrying would repeat the same failure.
    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",
        }
    }
}

/// Which process is driving the timer. A loop is not resumable across processes by default: the
/// front that started it owns it, and the record says whose it is so a reader can tell a
/// running loop from a stale one left behind by a CLI that exited.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Owner {
    Cli,
    Gateway,
}

/// One session's loop, as it is written to disk.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct State {
    pub session: String,
    pub prompt: String,
    /// `Schedule::describe()`'s own words — the same text `/loop status` prints, re-parsed on
    /// load, so the file cannot hold a schedule the parser would refuse.
    pub interval: String,
    #[serde(default)]
    pub times: Option<u32>,
    #[serde(default)]
    pub until: Option<String>,
    pub status: Status,
    #[serde(default)]
    pub ended: Option<Ended>,
    /// Ticks that actually ran.
    pub fired: u32,
    /// Ticks that landed while a run was in flight. Recorded, never queued: a backlog of ticks
    /// arriving at once is a busy loop with a schedule's name on it.
    #[serde(default)]
    pub skipped: u32,
    /// When this tick's successor is due, in epoch ms. Zero when the loop has not started or has
    /// ended.
    pub next_due_ms: i64,
    pub created_ms: i64,
    pub owner: Owner,
    pub owner_pid: u32,
    /// The last thing worth saying about this loop: a skipped tick, a refused `--until` answer.
    #[serde(default)]
    pub note: Option<String>,
}

impl State {
    /// A fresh loop, due one interval from now — not immediately, because starting something and
    /// firing it in the same second is not what "every 2m" means.
    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,
            // Armed from the schedule itself: for an interval that is `now + interval`, and for
            // a `daily 07:30` it is the next 07:30 rather than "now plus a day's worth of
            // milliseconds since the epoch", which is what multiplying an interval out would say.
            next_due_ms: spec.schedule.next_due(now_ms),
            created_ms: now_ms,
            owner,
            owner_pid: std::process::id(),
            note: None,
        }
    }

    /// The schedule this record names, or the parse error that says the file was edited badly.
    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(),
        })
    }

    /// Whether a tick is owed now.
    pub fn due(&self, now_ms: i64) -> bool {
        self.status == Status::Running && now_ms >= self.next_due_ms
    }

    /// Record what happened to the tick that was due, and arm the next one.
    ///
    /// The next moment is counted from *this* tick rather than from the one before it, so a tick
    /// that ran for two intervals does not fire twice in a row to catch up. A skipped tick is
    /// armed the same way: a busy session loses that tick and the schedule keeps its shape.
    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;
        }
    }

    /// The moment this loop's next tick is due, counted from `now_ms`.
    fn arm(&self, now_ms: i64) -> i64 {
        match self.schedule() {
            Ok(schedule) => schedule.next_due(now_ms),
            // A record whose interval no longer parses cannot be armed; fall back to cron's floor
            // so the loop keeps running and the readout carries the parse failure.
            Err(_) => now_ms.saturating_add(60_000),
        }
    }

    /// Resume, due one interval from now: a loop paused for an hour does not owe an hour of ticks.
    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);
        }
    }

    /// Whether the process that owns this loop is still the one running it.
    ///
    /// This is the honest answer to "is my loop still going" after a CLI exited: the record is
    /// still on disk, and it is still `Running`, but nobody is driving it. Unix asks the kernel;
    /// elsewhere the answer is assumed to be yes rather than invented from nothing.
    pub fn owner_alive(&self) -> bool {
        if self.owner_pid == std::process::id() {
            return true;
        }
        #[cfg(unix)]
        {
            // SAFETY: `kill` with signal 0 only performs the permission and existence check.
            let alive = unsafe { libc::kill(self.owner_pid as libc::pid_t, 0) } == 0;
            // EPERM means it exists and belongs to someone else, which is still alive.
            alive || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
        }
        #[cfg(not(unix))]
        {
            true
        }
    }

    /// One line after a tick, when there is something worth saying: an ending, a skip, a failure.
    /// `None` when the tick simply ran — a loop that works should not narrate every minute.
    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}")),
        }
    }

    /// The one line a front puts on screen for `/loop status`.
    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 {
                    // The record outlived the process that was driving it. Say so rather than
                    // printing a countdown to a tick nobody is going to send.
                    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
    }
}

/// What a tick turned out to be. The caller decides — this module only records it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// The run happened (whatever it answered).
    Ran,
    /// The tick landed while the session was busy, so it was dropped rather than queued.
    Skipped(String),
    /// The run itself could not be made to happen.
    Failed(String),
}

/// What a `--until` answer means. Three answers, not two: an unreadable reply is not a "no", and
/// treating it as one would end a loop because a model was verbose.
#[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",
        }
    }
}

/// Read one yes/no answer strictly.
///
/// The first word decides, after trimming quotes and punctuation: `yes.` and `"yes"` are both yes,
/// and `yes, but…` is still yes because the word that answers the question came first. Anything
/// else is [`Verdict::Unreadable`] — an explanation is not an answer, and guessing which way it
/// leans is how a loop stops on a model's rambling.
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,
    }
}

/// The exact request a `--until` check makes. One question, one word back.
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");
            // Long enough for the part of the reply that answers a condition, short enough that
            // the aux route's window is never the reason the check fails.
            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),
    ]
}

/// Parse everything after the `/loop` word.
///
/// Grammar, in one place so `/help` and the parser cannot drift:
///
/// ```text
/// /loop                                    status
/// /loop status | pause | resume | stop     manage it without leaving the session
/// /loop <interval> <prompt> [--times N] [--until <condition>]
/// ```
///
/// `<interval>` is cron's grammar (`every 30m`, `hourly`, `daily 07:30`) **and** a bare interval
/// (`2m`, `90s`, `1h`) meaning `every 2m`. Requiring the word "every" would make the one form
/// everyone types the one form the parser refuses.
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)?;
    // Flags are pulled out from anywhere after the interval, so `--times` before the prompt and
    // `--times` after it both work. The prompt is what is left, in order.
    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,
    }))
}

/// An interval: cron's grammar, or a bare one. `2m` is `every 2m`; `every 2m` is unchanged.
pub fn interval(text: &str) -> Result<Schedule> {
    let t = text.trim();
    if is_bare_interval(t) {
        // Through the same parser, so the floor, the overflow check and the error sentence are
        // cron's and not a second set that can disagree with it.
        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"
        ))
    })
}

/// `<digits><unit>` with no space: the short form people type.
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")
}

/// Strip one pair of matching surrounding quotes, so a quoted prompt arrives without them.
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()
}

/// `text` cut to `max` characters at a word boundary where there is one, on one line.
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())
}

/// A duration as a person reads a countdown: `45s`, `2m 10s`, `1h 5m`.
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")
            }
        }
    }
}

/// Answer one `/loop …` line, managing a loop that already exists.
///
/// Every verb but `start` reads and writes the record on disk, so a `/loop stop` typed into a
/// session whose timer belongs to another process still lands: the record is the one copy. A
/// `start` is the front's own business beyond the record, because it is the front that has to take
/// on the timer — the terminal's interface ticks from its event loop, and the dashboard's gateway
/// ticks from a task.
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)? {
                // One loop per session: two timers into one conversation is a race with a nicer
                // name, and the second one is nearly always a typo rather than an intent.
                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)"))
        }
    }
}

/// The line `/loop <interval> <prompt>` answers with. It names what will happen *and* what will
/// not: a loop dies with the process that owns it, and a person who is not told that finds out by
/// being surprised.
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)
    )
}

/// Read a session's loop, if it has one.
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))
}

/// Write a session's loop. The write is atomic, so a reader never sees half a record.
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(())
}

/// Forget a session's loop.
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)),
    }
}

/// Every loop this install has a record of, running or not — newest first.
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),
            // A half-written or hand-broken file is not this call's problem: the session that
            // owns it reports the parse error when it reads its own record.
            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);
        // Counted from this tick, not from the one before it: a run that overran does not owe a
        // backlog.
        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);
        // The schedule keeps its shape: the next tick is one interval after the skipped one.
        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());
        // Clearing what is not there is not an error.
        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);
        // A pid that cannot be running: pid 1 is init and is not this process, so use a value
        // that the kernel will refuse. Linux's default pid_max is well under this.
        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");
    }
}