eclipse-core 0.13.3

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
//! Background tasks: a run that outlives the prompt (#225).
//!
//! `/bg <prompt>` starts the same run `eclipse run` would — same workspace, same config, same
//! profile, same tool policy — in a detached process with its own session id, and returns to the
//! composer at once. Two verbs read one registry: `/tasks` lists it, and `eclipse doctor` looks at
//! it for entries whose process is gone.
//!
//! **The registry is one directory**: `<state>/tasks/`, one `<session>.json` per task, written by
//! the parent when it spawns (state `starting`, with the child's pid) and by the child at start and
//! after each turn. Beside it sits `<session>.log` — the child's own stdout and stderr, which is
//! where a failure explains itself without the registry having to guess.
//!
//! **The state is read through the pid, not trusted from the file.** A process that was killed
//! writes no final line, so a file that says `running` beside a pid that is gone is `died`: the
//! honest answer, and the one that stops a stale entry from claiming to be alive all day. The pid
//! is paired with the kernel's start time for that process so a recycled pid cannot make an old
//! entry look alive again.

use std::path::{Path, PathBuf};
use std::sync::Mutex;

use serde::{Deserialize, Serialize};

use crate::runtime::AgentEvent;
use crate::session::{ago_words, now_ms, validate_id};

/// The directory, under the state directory, that holds the registry.
pub const DIR: &str = "tasks";

/// The word that starts a background run.
pub const BG: &str = "/bg";

/// The word that lists them.
pub const TASKS: &str = "/tasks";

/// How much of a prompt a row carries. The whole prompt is in the file and in the session; a list
/// is for telling two rows apart, not for reading a paragraph.
const PROMPT_CHARS: usize = 60;

/// Where a task is.
///
/// `Starting` and `Running` are the two that are only true while a process is alive; everything
/// else is what the child wrote on its way out, and stays.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
    /// Spawned, and the child has not written its first line yet.
    Starting,
    /// The child is working.
    Running,
    /// The turn finished.
    Done,
    /// The run stopped with an error, or its process ended without saying why.
    Failed,
    /// Stopped on purpose — a signal, or a `Ctrl-C` in a terminal the person still had.
    Stopped,
    /// The run parked on an approval nobody was there to answer.
    Waiting,
    /// The file says it is running and the process is gone. Never written: always derived.
    Died,
}

impl State {
    /// The word the list and `/tasks` print.
    pub fn word(self) -> &'static str {
        match self {
            State::Starting => "starting",
            State::Running => "running",
            State::Done => "done",
            State::Failed => "failed",
            State::Stopped => "stopped",
            State::Waiting => "waiting",
            State::Died => "died",
        }
    }

    /// Whether the state is true only while a process is alive.
    ///
    /// This is the whole of the pid rule: a task in one of these two states has to have a live
    /// process behind it, and one that does not is [`State::Died`].
    pub fn alive_only(self) -> bool {
        matches!(self, State::Starting | State::Running)
    }
}

/// One background run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Task {
    /// The task is identified by the session it runs in: one run, one transcript, and
    /// `eclipse --plain -s <id>` opens it without a second id to remember.
    pub session: String,
    /// The process doing the work. Read through, never trusted: see [`Task::state_now`].
    pub pid: u32,
    /// The kernel's start time for that pid, in clock ticks since boot. With the pid this is
    /// what makes "the same process" a question with an answer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid_since: Option<u64>,
    /// When the task was spawned.
    pub started_ms: u64,
    /// The last write: when it started, what it last did, or how it ended.
    pub updated_ms: u64,
    /// The question it was given, cut to something a row can hold.
    pub prompt: String,
    pub state: State,
    /// The last thing it did, in one line: `tool shell`, `replied`, `turn 3 · 4.1K tok`.
    pub last: String,
    /// Why it ended, when ending needs a reason.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub detail: String,
}

impl Task {
    /// The entry the parent writes the moment the child is spawned.
    ///
    /// Written by the parent, not the child, so `/tasks` straight after `/bg` already has a row:
    /// a run that is invisible for its first hundred milliseconds is a run someone will ask
    /// twice about.
    pub fn spawned(session: &str, pid: u32, prompt: &str) -> Task {
        let now = now_ms();
        Task {
            session: session.to_string(),
            pid,
            pid_since: pid_since(pid),
            started_ms: now,
            updated_ms: now,
            prompt: clip_words(prompt, PROMPT_CHARS),
            state: State::Starting,
            last: "starting".to_string(),
            detail: String::new(),
        }
    }

    /// The entry the child writes for itself once it is running.
    pub fn begun(session: &str, prompt: &str) -> Task {
        let mut task = Task::spawned(session, std::process::id(), prompt);
        task.state = State::Running;
        task.last = "thinking".to_string();
        task
    }

    /// The state this entry is honestly in *now*.
    ///
    /// A stored `running` whose process is gone is [`State::Died`]. Everything else is what the
    /// child wrote, because a finished task has no process left to ask.
    pub fn state_now(&self) -> State {
        if self.state.alive_only() && !pid_live(self.pid, self.pid_since) {
            return State::Died;
        }
        self.state
    }

    /// `running · 2m ago`, or `died · 6h ago` — the two words a row is read for.
    pub fn headline(&self) -> String {
        format!(
            "{} · {}",
            self.state_now().word(),
            ago_words(self.updated_ms)
        )
    }

    /// Whether this entry is finished in any sense, including died.
    pub fn settled(&self) -> bool {
        !self.state_now().alive_only()
    }

    /// A died entry: its process is gone and no final line was written.
    pub fn died(&self) -> bool {
        self.state_now() == State::Died
    }
}

/// Cut `text` to `max` characters on a word boundary, with an ellipsis: a row, not a paragraph.
fn clip_words(text: &str, max: usize) -> String {
    let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
    if flat.chars().count() <= max {
        return flat;
    }
    let mut out: String = flat.chars().take(max).collect();
    if let Some(at) = out.rfind(' ') {
        out.truncate(at);
    }
    out.push('…');
    out
}

/// `/proc/<pid>/stat`, as (the process state, the kernel's start time in clock ticks since boot).
///
/// The comm field can hold spaces and parentheses, so the split starts after the *last* `)`.
/// Field 3 is the state and field 22 is the start time, which is index 0 and 19 after that split.
#[cfg(target_os = "linux")]
fn proc_stat(pid: u32) -> Option<(char, u64)> {
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    let mut fields = stat.rsplit_once(')')?.1.split_whitespace();
    let state = fields.next()?.chars().next()?;
    let since = fields.nth(18)?.parse().ok()?;
    Some((state, since))
}

/// The kernel's start time for `pid`. `None` when there is no `/proc` to read, or the process is
/// already gone.
#[cfg(target_os = "linux")]
fn pid_since(pid: u32) -> Option<u64> {
    proc_stat(pid).map(|(_, since)| since)
}

#[cfg(not(target_os = "linux"))]
fn pid_since(_pid: u32) -> Option<u64> {
    None
}

/// Whether the process has exited but not been reaped yet. A zombie still answers `kill(pid, 0)`
/// and is not running, so a task whose process is a zombie is `died`, not `running`.
#[cfg(target_os = "linux")]
fn uncollected(pid: u32) -> bool {
    matches!(proc_stat(pid), Some(('Z', _)))
}

#[cfg(not(target_os = "linux"))]
fn uncollected(_pid: u32) -> bool {
    false
}

/// Whether `pid` is that same process, still running.
///
/// A signal of 0 sends nothing and only tests for the process. `EPERM` means it exists and belongs
/// to somebody else, which is still alive. When both start times are known they have to agree: a
/// recycled pid with a different start time is a different process, and an entry that says
/// `running` about it would be the stale claim this whole module is written to avoid.
#[cfg(unix)]
fn pid_live(pid: u32, since: Option<u64>) -> bool {
    if pid == 0 {
        return false;
    }
    // SAFETY: signal 0 is a permission and existence probe; it delivers nothing.
    if unsafe { libc::kill(pid as libc::pid_t, 0) } != 0 {
        let err = std::io::Error::last_os_error().raw_os_error();
        if err != Some(libc::EPERM) {
            return false;
        }
    }
    if uncollected(pid) {
        return false;
    }
    match (since, pid_since(pid)) {
        (Some(wanted), Some(found)) => wanted == found,
        _ => true,
    }
}

#[cfg(not(unix))]
fn pid_live(pid: u32, _since: Option<u64>) -> bool {
    // There is no portable probe here, and pretending a process is gone is worse than a row that
    // waits for `/tasks` to say `died`: the file the child writes on the way out is the fallback.
    pid != 0
}

/// The registry: one directory, one file per task.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Registry {
    dir: PathBuf,
}

impl Registry {
    /// `state_dir` is the state directory itself (`~/.eclipse/state`), not the `tasks/` inside it:
    /// the caller already knows where its state lives, and this module owns the subdirectory name.
    pub fn new(state_dir: impl AsRef<Path>) -> Registry {
        Registry {
            dir: state_dir.as_ref().join(DIR),
        }
    }

    /// A registry that has never written anything, for a surface that must not care where the
    /// state directory is (`/tasks` before the first `/bg`).
    pub fn none() -> Registry {
        Registry {
            dir: PathBuf::new(),
        }
    }

    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// `<id>.json`.
    pub fn path(&self, id: &str) -> PathBuf {
        self.dir.join(format!("{id}.json"))
    }

    /// `<id>.log`: what the child printed. Kept beside the entry because a failure that only ever
    /// existed on a terminal that is gone is a failure nobody can read.
    pub fn log_path(&self, id: &str) -> PathBuf {
        self.dir.join(format!("{id}.log"))
    }

    /// Whether anything has ever been registered. `/tasks` says one line and stops when not.
    pub fn is_empty(&self) -> bool {
        self.list().is_empty()
    }

    /// Write an entry. Atomic (a sibling `.tmp` then a rename), because `/tasks` may be reading
    /// while a child is writing and half a JSON document is not a state.
    pub fn write(&self, task: &Task) -> std::io::Result<()> {
        validate_id(&task.session).map_err(|e| std::io::Error::other(e.to_string()))?;
        std::fs::create_dir_all(&self.dir)?;
        let path = self.path(&task.session);
        let tmp = self.dir.join(format!(".{}.json.tmp", task.session));
        let body = serde_json::to_string_pretty(task).map_err(std::io::Error::other)?;
        std::fs::write(&tmp, body + "\n")?;
        std::fs::rename(&tmp, &path)
    }

    /// One entry, as stored.
    pub fn load(&self, id: &str) -> Option<Task> {
        validate_id(id).ok()?;
        let text = std::fs::read_to_string(self.path(id)).ok()?;
        serde_json::from_str(&text).ok()
    }

    /// Every entry, newest activity first. A file that does not parse is skipped rather than
    /// reported: it is a half-written temp file at worst, and `/tasks` is not a JSON validator.
    pub fn list(&self) -> Vec<Task> {
        let Ok(entries) = std::fs::read_dir(&self.dir) else {
            return Vec::new();
        };
        let mut tasks: Vec<Task> = entries
            .flatten()
            .filter(|e| {
                e.path()
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| n.ends_with(".json") && !n.starts_with('.'))
            })
            .filter_map(|e| std::fs::read_to_string(e.path()).ok())
            .filter_map(|text| serde_json::from_str::<Task>(&text).ok())
            .collect();
        tasks.sort_by(|a, b| {
            b.updated_ms
                .cmp(&a.updated_ms)
                .then_with(|| a.session.cmp(&b.session))
        });
        tasks
    }

    /// What the last turn did, for the row. A no-op when nothing changed, so a long run does not
    /// rewrite the same line for every event it emits.
    pub fn touch(&self, id: &str, last: &str) -> std::io::Result<()> {
        let Some(mut task) = self.load(id) else {
            return Ok(());
        };
        if task.state != State::Running || task.last == last {
            return Ok(());
        }
        task.last = last.to_string();
        task.updated_ms = now_ms();
        self.write(&task)
    }

    /// How it ended. The one line a killed task never gets to write, which is why the pid is
    /// read instead of believed.
    pub fn finish(&self, id: &str, state: State, detail: &str) -> std::io::Result<()> {
        let Some(mut task) = self.load(id) else {
            return Ok(());
        };
        task.state = state;
        task.detail = detail.to_string();
        // An empty detail means the run simply ended: `last` keeps what it actually did
        // (`replied`), because a row that says `done` beside `done` says it twice.
        if !detail.is_empty() {
            task.last = detail.to_string();
        }
        task.updated_ms = now_ms();
        self.write(&task)
    }

    /// The rows `/tasks` prints: a header, then one line per task, or one line saying there are
    /// none. Shared by both front ends so the REPL and the interface cannot disagree about what a
    /// task is called.
    pub fn report(&self) -> String {
        let tasks = self.list();
        if tasks.is_empty() {
            return "no background tasks — `/bg <prompt>` starts one".to_string();
        }
        let id_width = tasks
            .iter()
            .map(|t| t.session.len())
            .max()
            .unwrap_or(0)
            .max("id".len());
        let state_width = tasks
            .iter()
            .map(|t| t.state_now().word().len())
            .max()
            .unwrap_or(0)
            .max("state".len());
        let mut lines = vec![format!(
            "{:<id_width$}  {:<state_width$}  {:<7}  {}",
            "id", "state", "age", "last"
        )];
        for t in &tasks {
            let state = t.state_now();
            let age = ago_words(t.updated_ms);
            let age = age.strip_suffix(" ago").map(str::to_string).unwrap_or(age);
            let last = if t.detail.is_empty() {
                t.last.clone()
            } else {
                format!("{} ({})", t.last, t.detail)
            };
            lines.push(format!(
                "{:<id_width$}  {:<state_width$}  {:<7}  {}",
                t.session,
                state.word(),
                age,
                clip_words(&last, 70)
            ));
            // The pid is printed while it means something: it is the handle for stopping a run
            // (`kill <pid>`), and once the task is finished the number may belong to anything.
            let under = if t.settled() {
                t.prompt.clone()
            } else {
                format!("pid {} · {}", t.pid, t.prompt)
            };
            lines.push(format!(
                "{:<id_width$}  {:<state_width$}  {:<7}  {}",
                "",
                "",
                "",
                clip_words(&under, 70)
            ));
        }
        lines.join("\n")
    }
}

/// The prompt behind a `/bg` line, or `None` when the line is not one.
///
/// `/bg` is a word, not a prefix: `/bgfoo` is a prompt for the model, the same way `fix!` is.
/// An empty answer is still `Some("")` — "you typed the word and nothing else" is a usage error
/// the caller can say out loud, not a question to send.
pub fn bg_prompt(line: &str) -> Option<&str> {
    let rest = line.trim_start().strip_prefix(BG)?;
    if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
        return None;
    }
    Some(rest.trim())
}

/// Why `/bg` is not a thing on `surface`.
///
/// The registry is a directory and the return-to-the-composer is a keyboard; a headless caller has
/// neither, and a scheduled job that spawns background jobs is a fork bomb with a schedule.
pub fn bg_refusal(surface: &str) -> String {
    format!(
        "`{BG}` starts a task that outlives the prompt, and {surface} has no prompt to return to — \
         the line was not run. Run it from `eclipse`, or send the question as a prompt."
    )
}

/// The one place a child turns an [`AgentEvent`] into the row's `last` line.
///
/// It lives here rather than in the loop because two things need the same words: the child writing
/// its own registry entry, and nothing else — but a second copy of this mapping would drift from
/// the states the list shows.
pub fn describe_event(event: &AgentEvent) -> Option<String> {
    match event {
        AgentEvent::ToolCall { name, .. } => Some(format!("tool {name}")),
        AgentEvent::ToolResult { name, is_error, .. } => Some(if *is_error {
            format!("tool {name} failed")
        } else {
            format!("tool {name} ok")
        }),
        AgentEvent::Message(_) => Some("replied".to_string()),
        _ => None,
    }
}

/// A task's entry, kept up to date by the process doing the work.
///
/// Cheap to clone (a path and an id) and safe to share: the last written line is compared under a
/// lock so a turn that emits twenty events writes the file once.
#[derive(Debug, Clone)]
pub struct Tracker {
    registry: Registry,
    id: String,
    wrote: std::sync::Arc<Mutex<String>>,
}

impl Tracker {
    pub fn new(registry: Registry, id: impl Into<String>) -> Tracker {
        Tracker {
            registry,
            id: id.into(),
            wrote: std::sync::Arc::new(Mutex::new(String::new())),
        }
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    /// Follow one event, if it says something a row can carry. Errors are nobody's business here:
    /// a registry that cannot be written must not stop the run it is describing.
    pub fn event(&self, event: &AgentEvent) {
        if let Some(line) = describe_event(event) {
            self.say(&line);
        }
    }

    /// Write `last`, once per distinct line.
    pub fn say(&self, line: &str) {
        let mut wrote = match self.wrote.lock() {
            Ok(w) => w,
            Err(e) => e.into_inner(),
        };
        if *wrote == line {
            return;
        }
        if self.registry.touch(&self.id, line).is_ok() {
            *wrote = line.to_string();
        }
    }

    /// How it ended. Always written when the process got this far.
    pub fn finish(&self, state: State, detail: &str) {
        let _ = self.registry.finish(&self.id, state, detail);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::Message;

    fn scratch() -> (tempfile::TempDir, Registry) {
        let dir = tempfile::tempdir().expect("a scratch directory");
        let registry = Registry::new(dir.path());
        (dir, registry)
    }

    fn task(id: &str, state: State) -> Task {
        let mut t = Task::spawned(id, std::process::id(), "count the files");
        t.state = state;
        t
    }

    #[test]
    fn an_entry_is_written_read_and_listed_newest_first() {
        let (_dir, registry) = scratch();
        assert!(registry.list().is_empty());
        assert!(registry.is_empty());

        let mut older = task("100-1-0", State::Done);
        older.updated_ms = 1_000;
        older.last = "replied".into();
        let mut newer = task("200-2-0", State::Running);
        newer.updated_ms = 2_000;
        newer.last = "tool shell".into();
        registry.write(&older).unwrap();
        registry.write(&newer).unwrap();

        let listed = registry.list();
        assert_eq!(
            listed
                .iter()
                .map(|t| t.session.as_str())
                .collect::<Vec<_>>(),
            ["200-2-0", "100-1-0"],
            "newest activity first"
        );
        assert_eq!(registry.load("100-1-0"), Some(older));
        assert_eq!(registry.load("nope"), None);
        assert!(!registry.is_empty());
    }

    #[test]
    fn a_running_entry_whose_process_is_gone_is_died_not_running() {
        let (_dir, registry) = scratch();
        // A pid that has certainly exited: a child of this test, waited for.
        let mut child = std::process::Command::new("true").spawn().expect("spawn");
        let pid = child.id();
        child.wait().expect("reap");
        assert!(
            pid_since(pid).is_none(),
            "the process is gone: nothing to read"
        );

        let mut entry = Task::spawned("300-3-0", pid, "a question");
        entry.state = State::Running;
        registry.write(&entry).unwrap();
        assert_eq!(
            registry.load("300-3-0").unwrap().state_now(),
            State::Died,
            "a pid that is gone cannot be running"
        );
        assert!(registry.list()[0].died());
        assert!(registry.list()[0].settled());

        // A finished entry stays finished: there is no process left to ask about.
        let done = task("400-4-0", State::Done);
        registry.write(&done).unwrap();
        assert_eq!(registry.load("400-4-0").unwrap().state_now(), State::Done);
    }

    /// The pid is paired with the kernel's start time, so a recycled pid cannot resurrect an old
    /// entry. Simulated by writing a start time that is not the live process's.
    #[test]
    fn a_recycled_pid_with_a_different_start_time_is_not_the_same_task() {
        let (_dir, registry) = scratch();
        let mut entry = task("500-5-0", State::Running);
        entry.pid = std::process::id();
        entry.pid_since = pid_since(std::process::id()).map(|ticks| ticks.wrapping_add(1));
        registry.write(&entry).unwrap();
        assert_eq!(
            registry.load("500-5-0").unwrap().state_now(),
            State::Died,
            "same number, different process"
        );

        let mut ours = task("600-6-0", State::Running);
        ours.pid = std::process::id();
        ours.pid_since = pid_since(std::process::id());
        registry.write(&ours).unwrap();
        assert_eq!(
            registry.load("600-6-0").unwrap().state_now(),
            State::Running,
            "the live process is the one this entry names"
        );
    }

    #[test]
    fn a_tracker_writes_each_distinct_line_once_and_finishes_with_a_reason() {
        let (_dir, registry) = scratch();
        let entry = Task::begun("700-7-0", "do the thing");
        registry.write(&entry).unwrap();
        let tracker = Tracker::new(registry.clone(), "700-7-0");

        tracker.event(&AgentEvent::ToolCall {
            call_id: "c1".into(),
            name: "shell".into(),
            arguments: "{}".into(),
        });
        assert_eq!(registry.load("700-7-0").unwrap().last, "tool shell");
        tracker.event(&AgentEvent::ToolResult {
            call_id: "c1".into(),
            name: "shell".into(),
            output: "ok".into(),
            is_error: true,
        });
        assert_eq!(
            registry.load("700-7-0").unwrap().last,
            "tool shell failed",
            "a failed tool says so"
        );
        tracker.event(&AgentEvent::Message("the answer".into()));
        assert_eq!(registry.load("700-7-0").unwrap().last, "replied");
        // Nothing to say about this one: the row keeps what it had.
        tracker.event(&AgentEvent::Delta("half".into()));
        assert_eq!(registry.load("700-7-0").unwrap().last, "replied");

        tracker.finish(State::Failed, "the model refused the shape");
        let ended = registry.load("700-7-0").unwrap();
        assert_eq!(ended.state, State::Failed);
        assert_eq!(ended.detail, "the model refused the shape");
        assert_eq!(ended.last, "the model refused the shape");

        // A clean finish keeps what the run last *did*: the row already says `done`, and
        // `done` beside `done` is the same word twice.
        let clean = Task::begun("701-7-1", "do the thing");
        registry.write(&clean).unwrap();
        Tracker::new(registry.clone(), "701-7-1").finish(State::Done, "");
        let finished = registry.load("701-7-1").unwrap();
        assert_eq!(finished.state, State::Done);
        assert_eq!(finished.last, "thinking", "what it was doing when it ended");
        assert!(finished.detail.is_empty());
    }

    #[test]
    fn the_report_names_the_state_the_age_and_what_it_last_did() {
        let (_dir, registry) = scratch();
        assert_eq!(
            registry.report(),
            "no background tasks — `/bg <prompt>` starts one"
        );

        let mut running = Task::begun("800-8-0", "summarise every issue");
        running.last = "tool search_files".into();
        registry.write(&running).unwrap();
        let report = registry.report();
        assert!(report.starts_with("id"), "{report}");
        assert!(report.contains("800-8-0"), "{report}");
        assert!(report.contains("running"), "{report}");
        assert!(report.contains("tool search_files"), "{report}");
        assert!(report.contains("summarise every issue"), "{report}");
        assert!(
            report.contains(&format!("pid {}", std::process::id())),
            "a live task prints the pid that stops it: {report}"
        );
        assert!(
            report.contains("just now") || report.contains("now"),
            "{report}"
        );
    }

    #[test]
    fn a_bg_line_is_the_word_and_the_question_behind_it() {
        assert_eq!(bg_prompt("/bg count the files"), Some("count the files"));
        assert_eq!(bg_prompt("  /bg   two  spaces "), Some("two  spaces"));
        assert_eq!(bg_prompt("/bg"), Some(""));
        assert_eq!(bg_prompt("/bgfoo"), None, "a prefix is not the word");
        assert_eq!(bg_prompt("what does /bg do?"), None, "not at the start");
        assert_eq!(bg_prompt("hello"), None);
    }

    #[test]
    fn the_refusal_says_where_it_does_work() {
        let said = bg_refusal("`eclipse run`");
        assert!(said.contains("/bg"), "{said}");
        assert!(said.contains("eclipse run"), "{said}");
        assert!(said.contains("from `eclipse`"), "{said}");
    }

    #[test]
    fn a_long_prompt_is_cut_on_a_word_boundary() {
        let long = "one two three four five six seven eight nine ten";
        let cut = clip_words(long, 20);
        assert!(cut.chars().count() <= 21, "{cut}");
        assert!(cut.ends_with('…'), "{cut}");
        assert!(!cut.contains("  "), "{cut}");
        assert_eq!(clip_words("short", 20), "short");
        // Whitespace in the prompt is flattened: a row is one line.
        assert_eq!(clip_words("a\n  b", 20), "a b");
    }

    #[test]
    fn the_two_live_states_are_the_only_ones_that_need_a_pid() {
        let live: Vec<State> = [State::Starting, State::Running]
            .into_iter()
            .filter(|s| s.alive_only())
            .collect();
        assert_eq!(live.len(), 2);
        for state in [
            State::Done,
            State::Failed,
            State::Stopped,
            State::Waiting,
            State::Died,
        ] {
            assert!(!state.alive_only(), "{state:?}");
        }
    }

    #[test]
    fn an_id_with_a_slash_in_it_is_refused() {
        let (_dir, registry) = scratch();
        let mut bad = task("../escape", State::Running);
        bad.session = "../escape".into();
        assert!(registry.write(&bad).is_err());
        assert!(registry.load("../escape").is_none());
    }

    #[test]
    fn a_file_that_does_not_parse_is_skipped_rather_than_reported() {
        let (dir, registry) = scratch();
        std::fs::create_dir_all(registry.dir()).unwrap();
        std::fs::write(registry.dir().join("broken.json"), "{ not json").unwrap();
        std::fs::write(registry.dir().join(".900.json.tmp"), "{}").unwrap();
        registry.write(&task("901-9-0", State::Done)).unwrap();
        let listed = registry.list();
        assert_eq!(listed.len(), 1, "only the real entry: {listed:?}");
        assert_eq!(listed[0].session, "901-9-0");
        assert!(dir.path().exists());
    }

    #[test]
    fn touching_an_entry_that_is_already_finished_changes_nothing() {
        let (_dir, registry) = scratch();
        let mut finished = task("902-9-0", State::Done);
        finished.last = "replied".into();
        finished.updated_ms = 5_000;
        registry.write(&finished).unwrap();
        registry.touch("902-9-0", "tool shell").unwrap();
        let after = registry.load("902-9-0").unwrap();
        assert_eq!(
            after.last, "replied",
            "a finished task does not start again"
        );
        assert_eq!(after.updated_ms, 5_000);
    }

    #[test]
    fn a_message_event_carries_no_prompt_text_into_the_registry() {
        // The row says what kind of thing happened, never what was said: the prompt is in the
        // session, and a registry that copies answers is a second place to leak them.
        let line = describe_event(&AgentEvent::Message("the secret is hunter2".into()));
        assert_eq!(line.as_deref(), Some("replied"));
        let _ = Message::user("x");
    }
}