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
//! `#173` end to end: a real config, a real `Agent`, a loop record on disk, and a local server
//! standing in for the model.
//!
//! The interesting claim in the issue is not that a prompt is sent twice — it is that the second
//! tick's **request** carries the first tick's history. That is a property of the request body, so
//! that is where it is asserted: the stub keeps every body it was sent, and the test compares the
//! bytes rather than the screen.
//!
//! The clock is the test's. `State::next_due_ms` is a field, so a two-minute interval fires twice
//! in a millisecond and nothing here waits.

use eclipse_core::cancel::Cancel;
use eclipse_core::config::Config;
use eclipse_core::loops::{self, Ended, Outcome, Owner, Status};
use eclipse_core::runtime::RunOptions;
use eclipse_core::tools::AllowAll;
use eclipse_core::Agent;
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

/// What the model says when it is asked a question, and what it says when it is asked whether a
/// condition holds. The second sentence is the one the test looks for in the next request.
const TICK_REPLY: &str = "the build is green and nothing changed";
const CONDITION_ANSWER: &str = "yes";

fn answer(text: &str) -> String {
    serde_json::json!({"choices": [{"message": {"role": "assistant", "content": text}}]})
        .to_string()
}

/// A stub endpoint that records every request body. A body carrying a `CONDITION:` (the `--until`
/// check) is answered with [`CONDITION_ANSWER`]; anything else with [`TICK_REPLY`].
async fn serve() -> (String, Arc<Mutex<Vec<String>>>) {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let seen = Arc::new(Mutex::new(Vec::<String>::new()));
    let log = Arc::clone(&seen);
    tokio::spawn(async move {
        loop {
            let Ok((mut s, _)) = listener.accept().await else {
                break;
            };
            let log = Arc::clone(&log);
            tokio::spawn(async move {
                let mut buf = Vec::new();
                let body = loop {
                    let mut chunk = [0u8; 8192];
                    let read = s.read(&mut chunk).await.unwrap_or(0);
                    buf.extend_from_slice(&chunk[..read]);
                    let text = String::from_utf8_lossy(&buf).to_string();
                    let Some(idx) = text.find("\r\n\r\n") else {
                        if read == 0 {
                            return;
                        }
                        continue;
                    };
                    let len = text[..idx]
                        .to_lowercase()
                        .lines()
                        .find_map(|l| l.strip_prefix("content-length: ")?.trim().parse().ok())
                        .unwrap_or(0usize);
                    if buf.len() >= idx + 4 + len {
                        break text[idx + 4..].to_string();
                    }
                };
                let is_check = body.contains("CONDITION:");
                log.lock().unwrap().push(body);
                let reply = if is_check {
                    answer(CONDITION_ANSWER)
                } else {
                    answer(TICK_REPLY)
                };
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\
                     connection: close\r\n\r\n{reply}",
                    reply.len()
                );
                let _ = s.write_all(resp.as_bytes()).await;
            });
        }
    });
    (base, seen)
}

struct Fixture {
    agent: Agent,
    root: std::path::PathBuf,
    dir: tempfile::TempDir,
    seen: Arc<Mutex<Vec<String>>>,
}

/// An install with a session in it, and an `aux` route on the same stub so the `--until` check has
/// somewhere to go.
async fn fixture(aux: bool) -> Fixture {
    let (base, seen) = serve().await;
    let dir = tempfile::tempdir().unwrap();
    let home = dir.path().join("home");
    let ws = dir.path().join("ws");
    let eclipse = home.join(".eclipse");
    std::fs::create_dir_all(&eclipse).unwrap();
    std::fs::create_dir_all(&ws).unwrap();
    let routes = if aux {
        format!(
            "\n[[provider.route]]\nname = \"aux\"\nbase_url = \"{base}\"\nmodel = \"m\"\n\
             max_retries = 0"
        )
    } else {
        String::new()
    };
    let aux_key = if aux { "aux = \"aux\"\n" } else { "" };
    std::fs::write(
        eclipse.join("config.toml"),
        format!(
            "[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\nstream = false\nmax_retries = 0\n\
             {aux_key}[tools]\nworkspace_root = \"{}\"\n[sessions]\nautotitle = false\n{routes}",
            ws.display()
        ),
    )
    .unwrap();
    let env = [("HOME".to_string(), home.display().to_string())];
    let lookup = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
    let cfg = Config::load_with_profile(None, None, &lookup).expect("config loads");
    let agent = Agent::from_config_with_env(&cfg, &lookup).expect("agent builds");
    Fixture {
        agent,
        root: eclipse,
        dir,
        seen,
    }
}

/// One tick, exactly as a front does it: probe, run, record. The clock is the record's own
/// `next_due_ms` forced to "now", so the interval never has to elapse.
async fn tick(fx: &Fixture, state: &mut loops::State, now: i64) -> bool {
    state.next_due_ms = now;
    if !state.due(now) {
        return false;
    }
    if !fx.agent.loop_tick_begin(&fx.root, state, now).unwrap() {
        return false;
    }
    let prompt = state.prompt.clone();
    let cancel = Cancel::new();
    let run = fx
        .agent
        .run_cancellable_with(
            Some(&state.session),
            &prompt,
            &AllowAll,
            &|_| {},
            &cancel,
            &RunOptions::default(),
        )
        .await;
    let result = run
        .map(|_| Some(TICK_REPLY.to_string()))
        .map_err(|e| e.to_string());
    fx.agent
        .loop_tick_end(&fx.root, state, now, result)
        .await
        .unwrap();
    true
}

fn start(root: &std::path::Path, session: &str, line: &str, now: i64) -> loops::State {
    loops::manage(root, session, line, Owner::Cli, now).unwrap();
    loops::load(root, session).unwrap().expect("a record")
}

#[tokio::test]
async fn the_second_tick_carries_the_first_ticks_history_in_its_request() {
    let fx = fixture(false).await;
    let mut state = start(&fx.root, "s1", "2m check the build --times 2", 0);

    assert!(tick(&fx, &mut state, 120_000).await);
    assert_eq!(state.fired, 1);
    assert!(tick(&fx, &mut state, 240_000).await);
    assert_eq!(state.fired, 2);
    assert_eq!(state.status, Status::Ended);
    assert_eq!(state.ended, Some(Ended::Times));

    let bodies = fx.seen.lock().unwrap().clone();
    assert_eq!(bodies.len(), 2, "two ticks, two requests: {bodies:?}");
    assert!(
        !bodies[0].contains(TICK_REPLY),
        "the first request cannot carry a reply that has not happened yet"
    );
    assert!(
        bodies[0].contains("check the build"),
        "the first request carries the prompt: {}",
        bodies[0]
    );
    assert!(
        bodies[1].contains(TICK_REPLY),
        "the second request carries the first tick's answer, which is what \"same session\" \
         buys: {}",
        bodies[1]
    );
    assert!(
        bodies[1].contains("check the build"),
        "and the prompt is asked again: {}",
        bodies[1]
    );
    // The record is the file, not a copy: what a second process reads is what this wrote.
    let reread = loops::load(&fx.root, "s1").unwrap().expect("still there");
    assert_eq!(reread, state);
    drop(fx.dir);
}

#[tokio::test]
async fn a_tick_that_lands_on_a_run_in_flight_is_recorded_as_skipped_and_not_queued() {
    let fx = fixture(false).await;
    let mut state = start(&fx.root, "s1", "2m check the build", 0);

    // Somebody is running this session: the lock the run takes for a turn, taken here and held.
    let held = fx.agent.store().try_lock("s1").unwrap();
    assert!(held.is_some(), "nothing else holds it yet");
    let outcome = fx
        .agent
        .loop_tick_begin(&fx.root, &mut state, 120_000)
        .unwrap();
    assert!(!outcome, "a busy session loses the tick");
    assert_eq!(state.fired, 0);
    assert_eq!(state.skipped, 1);
    assert_eq!(state.status, Status::Running);
    assert_eq!(
        state.next_due_ms, 240_000,
        "the schedule keeps its shape: the next tick is one interval from the one that was dropped"
    );
    assert!(
        state.note.as_deref().unwrap().contains("in flight"),
        "{:?}",
        state.note
    );

    // Released, the next tick runs and the record says so.
    drop(held);
    assert!(tick(&fx, &mut state, 240_000).await);
    assert_eq!(state.fired, 1);
    assert_eq!(state.skipped, 1);
    assert!(state.note.is_none(), "a tick that ran clears the note");
    drop(fx.dir);
}

#[tokio::test]
async fn an_until_check_that_answers_yes_ends_the_loop_without_waiting_for_the_next_tick() {
    let fx = fixture(true).await;
    let mut state = start(
        &fx.root,
        "s1",
        "2m is the deploy done --until the deploy is green",
        0,
    );

    assert!(tick(&fx, &mut state, 120_000).await);
    assert_eq!(state.status, Status::Ended);
    assert_eq!(state.ended, Some(Ended::Until));
    assert_eq!(state.fired, 1);
    assert_eq!(state.next_due_ms, 0);

    let bodies = fx.seen.lock().unwrap().clone();
    assert_eq!(bodies.len(), 2, "one turn and one check: {bodies:?}");
    assert!(
        bodies[1].contains("CONDITION: the deploy is green"),
        "the check is asked the condition: {}",
        bodies[1]
    );
    assert!(
        bodies[1].contains(TICK_REPLY),
        "and it is given the reply it judges: {}",
        bodies[1]
    );
    drop(fx.dir);
}

#[tokio::test]
async fn a_stopped_loop_does_not_fire_and_a_paused_one_keeps_its_count() {
    let fx = fixture(false).await;
    let mut state = start(&fx.root, "s1", "2m go", 0);
    assert!(tick(&fx, &mut state, 120_000).await);

    loops::manage(&fx.root, "s1", "pause", Owner::Cli, 130_000).unwrap();
    let mut paused = loops::load(&fx.root, "s1").unwrap().unwrap();
    paused.next_due_ms = 240_000;
    assert!(!paused.due(240_000), "a paused loop is never due");
    assert_eq!(paused.fired, 1);

    loops::manage(&fx.root, "s1", "stop", Owner::Cli, 250_000).unwrap();
    let stopped = loops::load(&fx.root, "s1").unwrap().unwrap();
    assert_eq!(stopped.status, Status::Ended);
    assert_eq!(stopped.ended, Some(Ended::Stopped));
    assert_eq!(stopped.fired, 1, "the count survives the ending");
    drop(fx.dir);
}

#[tokio::test]
async fn an_unreadable_until_answer_keeps_the_loop_going_and_is_recorded() {
    // An aux route that answers with an explanation instead of a word: the case where treating
    // "no" and "unclear" as the same thing would end a loop on a model's rambling.
    let (base, _seen) = {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let seen = Arc::new(Mutex::new(Vec::<String>::new()));
        let log = Arc::clone(&seen);
        tokio::spawn(async move {
            loop {
                let Ok((mut s, _)) = listener.accept().await else {
                    break;
                };
                let log = Arc::clone(&log);
                tokio::spawn(async move {
                    let mut buf = Vec::new();
                    let body = loop {
                        let mut chunk = [0u8; 8192];
                        let read = s.read(&mut chunk).await.unwrap_or(0);
                        buf.extend_from_slice(&chunk[..read]);
                        let text = String::from_utf8_lossy(&buf).to_string();
                        let Some(idx) = text.find("\r\n\r\n") else {
                            if read == 0 {
                                return;
                            }
                            continue;
                        };
                        let len = text[..idx]
                            .to_lowercase()
                            .lines()
                            .find_map(|l| l.strip_prefix("content-length: ")?.trim().parse().ok())
                            .unwrap_or(0usize);
                        if buf.len() >= idx + 4 + len {
                            break text[idx + 4..].to_string();
                        }
                    };
                    let is_check = body.contains("CONDITION:");
                    log.lock().unwrap().push(body);
                    let reply = if is_check {
                        answer("It depends on what you mean by green.")
                    } else {
                        answer(TICK_REPLY)
                    };
                    let resp = format!(
                        "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
                         content-length: {}\r\nconnection: close\r\n\r\n{reply}",
                        reply.len()
                    );
                    let _ = s.write_all(resp.as_bytes()).await;
                });
            }
        });
        (base, seen)
    };
    let dir = tempfile::tempdir().unwrap();
    let home = dir.path().join("home");
    let ws = dir.path().join("ws");
    let eclipse = home.join(".eclipse");
    std::fs::create_dir_all(&eclipse).unwrap();
    std::fs::create_dir_all(&ws).unwrap();
    std::fs::write(
        eclipse.join("config.toml"),
        format!(
            "[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\nstream = false\nmax_retries = 0\n\
             aux = \"aux\"\n[tools]\nworkspace_root = \"{}\"\n[sessions]\nautotitle = false\n\
             \n[[provider.route]]\nname = \"aux\"\nbase_url = \"{base}\"\nmodel = \"m\"\n\
             max_retries = 0",
            ws.display()
        ),
    )
    .unwrap();
    let env = [("HOME".to_string(), home.display().to_string())];
    let lookup = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
    let cfg = Config::load_with_profile(None, None, &lookup).expect("config loads");
    let agent = Agent::from_config_with_env(&cfg, &lookup).expect("agent builds");
    let root = eclipse.clone();

    let mut state = loops::manage(&root, "s1", "2m go --until it is green", Owner::Cli, 0)
        .map(|_| loops::load(&root, "s1").unwrap().unwrap())
        .unwrap();
    state.next_due_ms = 120_000;
    assert!(agent.loop_tick_begin(&root, &mut state, 120_000).unwrap());
    agent
        .run_cancellable_with(
            Some("s1"),
            "go",
            &AllowAll,
            &|_| {},
            &Cancel::new(),
            &RunOptions::default(),
        )
        .await
        .unwrap();
    agent
        .loop_tick_end(&root, &mut state, 120_000, Ok(Some(TICK_REPLY.into())))
        .await
        .unwrap();

    assert_eq!(
        state.status,
        Status::Running,
        "an unreadable answer is not a yes"
    );
    assert!(state
        .note
        .as_deref()
        .unwrap_or_default()
        .contains("not yes or no"));
    assert_eq!(state.skipped, 0);
    drop(dir);
}

#[tokio::test]
async fn the_record_is_written_before_the_until_check_so_a_crash_still_counts_the_tick() {
    let fx = fixture(true).await;
    let mut state = start(&fx.root, "s1", "2m go --until it is green", 0);
    state.next_due_ms = 120_000;
    assert!(fx
        .agent
        .loop_tick_begin(&fx.root, &mut state, 120_000)
        .unwrap());
    // The tick ran; the check has not been asked yet. What is on disk is what a reader finds.
    state.record(120_000, Outcome::Ran);
    loops::save(&fx.root, &state).unwrap();
    let reread = loops::load(&fx.root, "s1").unwrap().unwrap();
    assert_eq!(reread.fired, 1);
    assert_eq!(reread.status, Status::Running);
    drop(fx.dir);
}