eclipse-core 0.13.1

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
//! `MEMORY.md`: the durable facts the agent learned, and the budget that keeps them honest.
//!
//! The file is a flat list of entries separated by a line holding `§`:
//!
//! ```text
//! the model server is on the LAN
//! §
//! Max prefers local inference over cloud
//! §
//! Max prefers local inference over cloud
//! ```
//!
//! Nothing here is clever. An entry is free text, it may span lines, and a memory that needs
//! a date carries it in the text — no timestamps are stored, because the file is also meant
//! to be read and edited by hand.
//!
//! Two writers (the CLI and the dashboard) can be alive at once, so every mutation takes an
//! advisory `flock` on `<file>.lock` and replaces the file atomically (`write` to a temp file
//! in the same directory, then `rename`). A reader therefore never sees half a file, and a
//! crash cannot leave one.

use crate::error::{Error, Result};
use std::path::{Path, PathBuf};

/// Ceiling on the rendered file, in characters, unless the config says otherwise.
pub const DEFAULT_BUDGET_CHARS: usize = 3000;
/// The line that separates two entries.
pub const SEPARATOR: &str = "§";
/// How long a writer waits for a concurrent one before giving up.
const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(40);

/// What a mutation did, in words worth showing the person watching.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// The file changed: the entry, and the room left afterwards.
    Changed {
        entry: String,
        chars: usize,
        budget: usize,
    },
    /// The change would not fit. The current entries come back so the next attempt can prune
    /// instead of guessing.
    Full {
        chars: usize,
        budget: usize,
        entries: Vec<String>,
    },
    /// Nothing matched, so nothing changed.
    NotFound(String),
    /// Nothing to do: the text is already there.
    Unchanged(String),
}

impl Outcome {
    pub fn changed(&self) -> bool {
        matches!(self, Outcome::Changed { .. })
    }

    /// One line for the CLI and for the model.
    pub fn describe(&self) -> String {
        match self {
            Outcome::Changed {
                entry,
                chars,
                budget,
            } => format!(
                "memory: {} — {char_chars} chars used of {budget}",
                clip(entry, 80),
                char_chars = chars
            ),
            Outcome::Full {
                chars,
                budget,
                entries,
            } => format!(
                "memory is full ({chars} of {budget} chars): remove or shorten an entry first. \
                 Current entries:\n{}",
                entries
                    .iter()
                    .enumerate()
                    .map(|(i, e)| format!("{}. {}", i + 1, clip(e, 120)))
                    .collect::<Vec<_>>()
                    .join("\n")
            ),
            Outcome::NotFound(text) => format!("no memory entry matches {:?}", clip(text, 60)),
            Outcome::Unchanged(entry) => {
                format!("memory already says {:?}", clip(entry, 60))
            }
        }
    }
}

fn clip(text: &str, max: usize) -> String {
    let first_line = text.lines().next().unwrap_or("").trim();
    let mut out: String = first_line.chars().take(max).collect();
    if first_line.chars().count() > max || text.lines().count() > 1 {
        out.push('…');
    }
    out
}

/// One profile's memory file.
#[derive(Debug, Clone)]
pub struct Memory {
    path: PathBuf,
    budget_chars: usize,
}

impl Memory {
    pub fn new(path: impl Into<PathBuf>, budget_chars: usize) -> Self {
        Self {
            path: path.into(),
            budget_chars,
        }
    }

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

    pub fn budget(&self) -> usize {
        self.budget_chars
    }

    fn lock_path(&self) -> PathBuf {
        let mut name = self.path.clone().into_os_string();
        name.push(".lock");
        PathBuf::from(name)
    }

    /// The entries, in file order. A missing file is an empty memory, not an error.
    pub fn read(&self) -> Result<Vec<String>> {
        match std::fs::read_to_string(&self.path) {
            Ok(text) => Ok(parse(&text)),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
            Err(e) => Err(Error::io(&self.path, e)),
        }
    }

    /// Characters the rendered file occupies — what the budget actually measures.
    pub fn size(&self) -> Result<usize> {
        Ok(render(&self.read()?).chars().count())
    }

    /// Append an entry, refusing past the budget.
    pub fn add(&self, text: &str) -> Result<Outcome> {
        let entry = text.trim();
        if entry.is_empty() {
            return Ok(Outcome::NotFound("(empty)".into()));
        }
        self.mutate(|entries| {
            if entries.iter().any(|e| same(e, entry)) {
                return Ok(Change::Keep(Outcome::Unchanged(entry.to_string())));
            }
            let mut next = entries.to_vec();
            next.push(entry.to_string());
            Ok(Change::Write(next))
        })
    }

    /// Rewrite the first entry that contains `old`, keeping everything else.
    pub fn patch(&self, old: &str, new: &str) -> Result<Outcome> {
        let new = new.trim();
        if old.trim().is_empty() {
            return Ok(Outcome::NotFound("(empty)".into()));
        }
        if new.is_empty() {
            return self.remove(old);
        }
        self.mutate(|entries| {
            let Some(at) = entries.iter().position(|e| e.contains(old.trim())) else {
                return Ok(Change::Keep(Outcome::NotFound(old.to_string())));
            };
            let mut next = entries.to_vec();
            next[at] = new.to_string();
            Ok(Change::Write(next))
        })
    }

    /// Drop the first entry that contains `text`.
    pub fn remove(&self, text: &str) -> Result<Outcome> {
        let needle = text.trim().to_string();
        if needle.is_empty() {
            return Ok(Outcome::NotFound("(empty)".into()));
        }
        self.mutate(|entries| {
            let Some(at) = entries.iter().position(|e| e.contains(&needle)) else {
                return Ok(Change::Keep(Outcome::NotFound(needle.clone())));
            };
            let mut next = entries.to_vec();
            next.remove(at);
            Ok(Change::Write(next))
        })
    }

    /// Put the entries back as they were — for `eclipse memory prune`, which decides what to
    /// drop itself.
    pub fn replace(&self, entries: Vec<String>) -> Result<Outcome> {
        self.mutate(|_old| Ok(Change::Write(entries.clone())))
    }

    /// The one path every mutation goes through: lock, read, decide, check the budget, write
    /// atomically, unlock.
    fn mutate(&self, decide: impl FnOnce(&[String]) -> Result<Change>) -> Result<Outcome> {
        let _guard = self.lock()?;
        let entries = self.read()?;
        let next = match decide(&entries)? {
            Change::Keep(outcome) => return Ok(outcome),
            Change::Write(next) => next,
        };
        let text = render(&next);
        let chars = text.chars().count();
        if self.budget_chars > 0 && chars > self.budget_chars {
            return Ok(Outcome::Full {
                chars,
                budget: self.budget_chars,
                entries,
            });
        }
        self.write_atomically(&text, &next)?;
        Ok(Outcome::Changed {
            entry: next.last().cloned().unwrap_or_default(),
            chars,
            budget: self.budget_chars,
        })
    }

    fn write_atomically(&self, text: &str, entries: &[String]) -> Result<()> {
        crate::atomic::write_file_atomically(&self.path, text)
            .map_err(|e| Error::io(&self.path, e))?;
        // A memory tool that wrote nothing would look like a bug in the transcript.
        if entries.is_empty() {
            std::fs::remove_file(&self.path).ok();
        }
        Ok(())
    }

    fn lock(&self) -> Result<LockGuard> {
        let path = self.lock_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
        }
        let mut opts = std::fs::OpenOptions::new();
        opts.create(true).read(true).write(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let file = opts.open(&path).map_err(|e| Error::io(&path, e))?;
        let deadline = std::time::Instant::now() + LOCK_WAIT;
        loop {
            match try_lock(&file) {
                Ok(true) => return Ok(LockGuard { _file: file }),
                Ok(false) if std::time::Instant::now() < deadline => {
                    std::thread::sleep(LOCK_POLL);
                }
                Ok(false) => {
                    return Err(Error::Config(format!(
                        "another eclipse is writing {} (waited {}s); try again",
                        self.path.display(),
                        LOCK_WAIT.as_secs()
                    )))
                }
                Err(e) => return Err(Error::io(&path, e)),
            }
        }
    }
}

enum Change {
    /// Nothing to write, and what to say about it.
    Keep(Outcome),
    Write(Vec<String>),
}

struct LockGuard {
    _file: std::fs::File,
}

#[cfg(unix)]
fn try_lock(file: &std::fs::File) -> std::io::Result<bool> {
    use std::os::unix::io::AsRawFd;
    // SAFETY: `file` owns a valid descriptor for the duration of the call.
    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    if rc == 0 {
        return Ok(true);
    }
    let err = std::io::Error::last_os_error();
    match err.raw_os_error() {
        Some(libc::EWOULDBLOCK) => Ok(false),
        _ => Err(err),
    }
}

#[cfg(not(unix))]
fn try_lock(_file: &std::fs::File) -> std::io::Result<bool> {
    // No portable advisory lock without another dependency; the atomic rename is what keeps
    // the file whole here (documented in the limits).
    Ok(true)
}

fn same(a: &str, b: &str) -> bool {
    a.trim().eq_ignore_ascii_case(b.trim())
}

/// Entries out of the file text: a line holding `§` separates them, blank lines around it and
/// at the ends are dropped, and anything else (including blank lines inside an entry) is kept.
pub fn parse(text: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut current: Vec<&str> = Vec::new();
    for line in text.lines() {
        if line.trim() == SEPARATOR || line.trim() == "§§" {
            push_entry(&mut out, &mut current);
            continue;
        }
        current.push(line);
    }
    push_entry(&mut out, &mut current);
    out
}

fn push_entry(out: &mut Vec<String>, current: &mut Vec<&str>) {
    let text = current.join("\n").trim().to_string();
    current.clear();
    if !text.is_empty() {
        out.push(text);
    }
}

/// Entries back into the file text, ending with a newline so appends stay one-per-block.
pub fn render(entries: &[String]) -> String {
    if entries.is_empty() {
        return String::new();
    }
    let mut out = String::new();
    for (i, entry) in entries.iter().enumerate() {
        if i > 0 {
            out.push_str(SEPARATOR);
            out.push('\n');
        }
        out.push_str(entry.trim());
        out.push('\n');
    }
    out
}

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

    fn memory(dir: &Path, budget: usize) -> Memory {
        Memory::new(dir.join("MEMORY.md"), budget)
    }

    #[test]
    fn entries_round_trip_through_the_separator() {
        let entries = vec![
            "one line".to_string(),
            "two\nlines in one entry".to_string(),
            "third".to_string(),
        ];
        let text = render(&entries);
        assert_eq!(text, "one line\n§\ntwo\nlines in one entry\n§\nthird\n");
        assert_eq!(parse(&text), entries);
        assert_eq!(parse(""), Vec::<String>::new());
        assert_eq!(parse("§\n§\n"), Vec::<String>::new());
    }

    #[test]
    fn add_read_patch_remove_round_trip() {
        let tmp = tempfile::tempdir().unwrap();
        let m = memory(tmp.path(), 1000);
        assert!(m.add("the fleet is two servers").unwrap().changed());
        assert!(m.add("Max prefers local inference").unwrap().changed());
        assert_eq!(m.read().unwrap().len(), 2);

        // Adding the same thing twice is not a change.
        assert_eq!(
            m.add("  the fleet is two servers ").unwrap(),
            Outcome::Unchanged("the fleet is two servers".into())
        );

        assert!(m
            .patch("two servers", "the fleet is a server and two desktops")
            .unwrap()
            .changed());
        assert_eq!(
            m.read().unwrap()[0],
            "the fleet is a server and two desktops"
        );

        assert!(m.remove("prefers local").unwrap().changed());
        assert_eq!(
            m.read().unwrap(),
            ["the fleet is a server and two desktops"]
        );

        assert_eq!(
            m.remove("nothing like this").unwrap(),
            Outcome::NotFound("nothing like this".into())
        );
    }

    #[test]
    fn the_budget_refuses_the_write_and_hands_back_what_is_there() {
        let tmp = tempfile::tempdir().unwrap();
        let m = memory(tmp.path(), 60);
        assert!(m.add(&"a".repeat(30)).unwrap().changed());
        let outcome = m.add(&"b".repeat(30)).unwrap();
        match outcome {
            Outcome::Full {
                chars,
                budget,
                entries,
            } => {
                assert_eq!(budget, 60);
                assert!(chars > 60, "{chars}");
                assert_eq!(
                    entries.len(),
                    1,
                    "the current entries, so the next try can prune"
                );
            }
            other => panic!("expected Full, got {other:?}"),
        }
        // Nothing was written.
        assert_eq!(m.read().unwrap().len(), 1);
        // ...and the refusal says how to fix it.
        assert!(m
            .add(&"b".repeat(30))
            .unwrap()
            .describe()
            .contains("memory is full"));
    }

    #[test]
    fn a_zero_budget_means_no_ceiling() {
        let tmp = tempfile::tempdir().unwrap();
        let m = memory(tmp.path(), 0);
        assert!(m.add(&"x".repeat(5000)).unwrap().changed());
        assert_eq!(m.size().unwrap(), 5001);
    }

    #[test]
    fn the_file_is_replaced_atomically_and_reads_as_a_whole() {
        let tmp = tempfile::tempdir().unwrap();
        let m = memory(tmp.path(), 1000);
        m.add("first").unwrap();
        // No temp files are left behind.
        let leftovers: Vec<_> = std::fs::read_dir(tmp.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().to_string())
            .filter(|n| n.contains("tmp"))
            .collect();
        assert!(leftovers.is_empty(), "{leftovers:?}");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(m.path()).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode, 0o600);
        }
    }

    #[test]
    fn two_writers_in_a_row_never_lose_an_entry() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("MEMORY.md");
        let a = Memory::new(&path, 10_000);
        let b = Memory::new(&path, 10_000);
        for i in 0..10 {
            a.add(&format!("a{i}")).unwrap();
            b.add(&format!("b{i}")).unwrap();
        }
        let entries = a.read().unwrap();
        assert_eq!(entries.len(), 20, "{entries:?}");
        assert!(entries.iter().any(|e| e == "a9"));
        assert!(entries.iter().any(|e| e == "b9"));
    }

    #[test]
    fn a_missing_file_is_an_empty_memory() {
        let tmp = tempfile::tempdir().unwrap();
        let m = memory(tmp.path(), 100);
        assert_eq!(m.read().unwrap(), Vec::<String>::new());
        assert_eq!(m.size().unwrap(), 0);
    }

    #[test]
    fn removing_the_last_entry_removes_the_file() {
        let tmp = tempfile::tempdir().unwrap();
        let m = memory(tmp.path(), 100);
        m.add("only").unwrap();
        assert!(m.path().exists());
        m.remove("only").unwrap();
        assert!(
            !m.path().exists(),
            "an empty MEMORY.md is not worth keeping"
        );
        assert_eq!(m.read().unwrap(), Vec::<String>::new());
    }

    #[test]
    fn a_multi_line_entry_survives_the_separator_format() {
        let tmp = tempfile::tempdir().unwrap();
        let m = memory(tmp.path(), 1000);
        m.add("first line\nsecond line").unwrap();
        m.add("another").unwrap();
        assert_eq!(m.read().unwrap(), ["first line\nsecond line", "another"]);
    }
}