blyte 0.89.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
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
use std::ffi::OsStr;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::Path;
use std::process::Command;
use std::thread;
use std::time::Duration;

use blyte_agent::sandbox::validate_surface_id;
use blyte_cli::surface_dir::{
    folder_store, in_place_lock_path, is_running, list_records_for_root, list_records_in,
    new_surface_id, pick_name, read_record, run_store, surface_dir, surfaces_dir, tasks_dir,
    validate_surface_name, write_record_in, SurfaceRecord,
};

fn sample_record(id: &str, name: &str, port: u16, started_at: u64) -> SurfaceRecord {
    SurfaceRecord {
        id: id.to_string(),
        name: name.to_string(),
        pid: std::process::id(),
        port,
        session_id: format!("sess-{id}"),
        started_at,
    }
}

fn spawn_health_server(body: String) -> (u16, thread::JoinHandle<()>) {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    let handle = thread::spawn(move || {
        let (mut stream, _) = listener.accept().unwrap();
        stream
            .set_read_timeout(Some(Duration::from_secs(30)))
            .unwrap();
        let mut req_bytes = Vec::new();
        let mut buf = [0u8; 1024];
        while !req_bytes.windows(4).any(|w| w == b"\r\n\r\n") {
            let n = stream.read(&mut buf).unwrap();
            if n == 0 {
                break;
            }
            req_bytes.extend_from_slice(&buf[..n]);
        }
        let resp = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        );
        stream.write_all(resp.as_bytes()).unwrap();
        stream.flush().unwrap();

        let request = String::from_utf8(req_bytes).unwrap();
        let (head, _) = request
            .split_once("\r\n\r\n")
            .unwrap_or_else(|| panic!("incomplete HTTP request: {request:?}"));
        let mut lines = head.split("\r\n");
        assert_eq!(
            lines.next(),
            Some("GET /api/health HTTP/1.1"),
            "unexpected request: {request:?}"
        );
        let headers: Vec<(String, String)> = lines
            .filter_map(|line| line.split_once(':'))
            .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string()))
            .collect();
        let expected_host = format!("127.0.0.1:{port}");
        assert!(
            headers
                .iter()
                .any(|(k, v)| k == "host" && *v == expected_host),
            "missing or unexpected Host header in request: {request:?}"
        );
        assert!(
            headers
                .iter()
                .any(|(k, v)| k == "connection" && v.eq_ignore_ascii_case("close")),
            "missing Connection: close header in request: {request:?}"
        );
    });
    (port, handle)
}

#[test]
fn new_surface_id_generates_distinct_valid_ids() {
    let id1 = new_surface_id().unwrap();
    let id2 = new_surface_id().unwrap();
    assert_ne!(id1, id2);
    validate_surface_id(&id1).unwrap();
    validate_surface_id(&id2).unwrap();
}

#[test]
fn validate_surface_name_accepts_valid_and_rejects_invalid() {
    for ok in ["blyte", "blyte-2", "a.b_c", "9", &"a".repeat(64)] {
        assert!(validate_surface_name(ok).is_ok(), "expected ok for {ok:?}");
    }

    let too_long = "a".repeat(65);
    for bad in ["", "-x", ".x", "a b", "a/b", too_long.as_str()] {
        let err = validate_surface_name(bad).unwrap_err();
        assert_eq!(
            err,
            format!(
                "invalid surface name: {bad} (use letters, digits, '.', '_' and '-', starting with a letter or digit)"
            )
        );
    }
}

#[test]
fn path_helpers_build_expected_paths() {
    let checkout = Path::new("/tmp/example-checkout");
    let id = "s0123456789abcdef";
    assert_eq!(surfaces_dir(checkout), checkout.join(".wt/surfaces"));
    assert_eq!(
        surface_dir(checkout, id),
        checkout.join(".wt/surfaces/s0123456789abcdef")
    );
}

#[test]
fn write_record_then_read_record_round_trips_with_no_temp_files() {
    let tmp = tempfile::tempdir().unwrap();
    let rec = sample_record("s0123456789abcdef", "blyte", 18080, 1_700_000_000);
    let dir = surface_dir(tmp.path(), &rec.id);
    write_record_in(&dir, &rec).unwrap();

    let got = read_record(tmp.path(), &rec.id).unwrap();
    assert_eq!(got, rec);

    let mut names: Vec<String> = std::fs::read_dir(&dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    assert_eq!(names, vec!["surface.json".to_string()]);

    let raw = std::fs::read_to_string(dir.join("surface.json")).unwrap();
    assert!(raw.ends_with('\n'));
}

#[test]
fn read_record_errors_when_inner_id_differs() {
    let tmp = tempfile::tempdir().unwrap();
    let dir_id = "s0123456789abcdef";
    let inner_id = "sfedcba9876543210";
    let dir = surface_dir(tmp.path(), dir_id);
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("surface.json");
    let rec = sample_record(inner_id, "blyte", 18080, 1_700_000_000);
    std::fs::write(&path, serde_json::to_string_pretty(&rec).unwrap()).unwrap();

    let err = read_record(tmp.path(), dir_id).unwrap_err();
    assert_eq!(
        err,
        format!(
            "surface record {} has id {inner_id}, expected {dir_id}",
            path.display()
        )
    );
}

#[test]
fn list_records_handles_missing_dir_sorting_stray_files_and_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let sdir = surfaces_dir(tmp.path());
    assert_eq!(list_records_in(&sdir).unwrap().records, Vec::new());

    let r_later = sample_record("s0000000000000002", "blyte-2", 18082, 200);
    let r_earlier = sample_record("s0000000000000001", "blyte", 18081, 100);
    let r_tie_b = sample_record("s000000000000000b", "blyte-b", 18084, 150);
    let r_tie_a = sample_record("s000000000000000a", "blyte-a", 18083, 150);
    write_record_in(&surface_dir(tmp.path(), &r_later.id), &r_later).unwrap();
    write_record_in(&surface_dir(tmp.path(), &r_tie_b.id), &r_tie_b).unwrap();
    write_record_in(&surface_dir(tmp.path(), &r_earlier.id), &r_earlier).unwrap();
    write_record_in(&surface_dir(tmp.path(), &r_tie_a.id), &r_tie_a).unwrap();

    std::fs::write(sdir.join("stray.txt"), "ignore me\n").unwrap();

    let listed: Vec<SurfaceRecord> = list_records_in(&sdir)
        .unwrap()
        .records
        .into_iter()
        .map(|l| l.record)
        .collect();
    assert_eq!(listed, vec![r_earlier, r_tie_a, r_tie_b, r_later]);

    let missing_json_dir = surface_dir(tmp.path(), "s0000000000000003");
    std::fs::create_dir_all(&missing_json_dir).unwrap();
    let err = list_records_in(&sdir).unwrap_err();
    assert!(
        err.contains(&missing_json_dir.display().to_string()),
        "{err}"
    );
    std::fs::remove_dir_all(&missing_json_dir).unwrap();

    let bad_dir = sdir.join("not-a-surface-id");
    std::fs::create_dir_all(&bad_dir).unwrap();
    let err = list_records_in(&sdir).unwrap_err();
    assert!(err.contains(&bad_dir.display().to_string()), "{err}");
}

#[test]
fn is_running_matches_surface_id_and_rejects_mismatch_or_closed_port() {
    let body = r#"{"surface_id":"s0123456789abcdef","session_id":"x"}"#.to_string();

    let (port, handle) = spawn_health_server(body.clone());
    let matching = sample_record("s0123456789abcdef", "blyte", port, 100);
    assert!(is_running(&matching));
    handle.join().unwrap();

    let (port2, handle2) = spawn_health_server(body);
    let other_id = sample_record("sfedcba9876543210", "blyte", port2, 100);
    assert!(!is_running(&other_id));
    handle2.join().unwrap();

    let unused_listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let closed_port = unused_listener.local_addr().unwrap().port();
    drop(unused_listener);
    let closed = sample_record("s0123456789abcdef", "blyte", closed_port, 100);
    assert!(!is_running(&closed));
}

#[test]
fn pick_name_handles_defaults_suffixes_conflicts_and_invalid_bases() {
    assert_eq!(pick_name("blyte", None, &[]).unwrap(), "blyte");
    assert_eq!(
        pick_name("blyte", None, &["blyte".to_string(), "blyte-2".to_string()]).unwrap(),
        "blyte-3"
    );

    let err = pick_name("blyte", Some("x"), &["x".to_string()]).unwrap_err();
    assert_eq!(
        err,
        "a running surface is already named x; pass a different --name"
    );

    let err = pick_name("my repo", None, &[]).unwrap_err();
    assert_eq!(
        err,
        "the repository directory name my repo cannot be a surface name; pass --name"
    );

    assert_eq!(pick_name("my repo", Some("ok"), &[]).unwrap(), "ok");
}

fn init_git_repo(dir: &Path) {
    let status = Command::new("git")
        .args(["init", "-q"])
        .current_dir(dir)
        .status()
        .unwrap();
    assert!(status.success(), "git init failed in {}", dir.display());
}

fn dir_entries(dir: &Path) -> Vec<String> {
    let mut names: Vec<String> = std::fs::read_dir(dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    names
}

#[test]
fn run_store_of_a_repository_is_its_wt_folder() {
    let state = tempfile::tempdir().unwrap();
    let repo = tempfile::tempdir().unwrap();
    init_git_repo(repo.path());

    let got = run_store(state.path(), repo.path()).unwrap();
    assert_eq!(got, repo.path().join(".wt"));
    assert!(!got.exists());
    assert!(dir_entries(state.path()).is_empty());
}

#[test]
fn run_store_of_a_plain_folder_is_in_the_state_directory() {
    let state = tempfile::tempdir().unwrap();
    let folder = tempfile::tempdir().unwrap();
    std::fs::write(folder.path().join("note.txt"), "hello\n").unwrap();
    let before = dir_entries(folder.path());

    let got = run_store(state.path(), folder.path()).unwrap();
    let folders_root = state.path().join("folders");
    assert!(got.starts_with(&folders_root), "{}", got.display());
    assert_eq!(got.file_name(), Some(OsStr::new("runs")));
    assert_eq!(
        got.parent().and_then(|p| p.parent()),
        Some(folders_root.as_path())
    );
    assert!(got.is_dir());
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&got).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o700, "expected 0700, got {:o}", mode);
    }
    assert_eq!(dir_entries(folder.path()), before);
}

#[test]
fn two_plain_folders_get_different_run_stores() {
    let state = tempfile::tempdir().unwrap();
    let folder_a = tempfile::tempdir().unwrap();
    let folder_b = tempfile::tempdir().unwrap();

    let store_a = run_store(state.path(), folder_a.path()).unwrap();
    let store_b = run_store(state.path(), folder_b.path()).unwrap();
    assert_ne!(store_a, store_b);
}

#[test]
fn tasks_dir_of_a_plain_folder_is_in_the_state_directory() {
    let state = tempfile::tempdir().unwrap();
    let folder = tempfile::tempdir().unwrap();
    std::fs::write(folder.path().join("note.txt"), "hello\n").unwrap();
    let before = dir_entries(folder.path());

    let got = tasks_dir(state.path(), folder.path()).unwrap();
    let expected_store = folder_store(state.path(), folder.path()).unwrap();
    assert_eq!(got, expected_store.join("tasks"));
    assert!(got.is_dir());
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&got).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o700, "expected 0700, got {:o}", mode);
    }
    assert_eq!(dir_entries(folder.path()), before);
}

#[test]
fn tasks_dir_of_a_repository_is_wt_tasks() {
    let state = tempfile::tempdir().unwrap();
    let repo = tempfile::tempdir().unwrap();
    init_git_repo(repo.path());

    let got = tasks_dir(state.path(), repo.path()).unwrap();
    assert_eq!(got, repo.path().join(".wt").join("tasks"));
    assert!(!repo.path().join(".wt").exists());
    assert!(dir_entries(state.path()).is_empty());
}

#[test]
fn in_place_lock_path_is_refused_for_a_repository() {
    let state = tempfile::tempdir().unwrap();
    let repo = tempfile::tempdir().unwrap();
    init_git_repo(repo.path());

    let err = in_place_lock_path(state.path(), repo.path()).unwrap_err();
    assert!(err.contains(&repo.path().display().to_string()), "{err}");
    assert!(dir_entries(state.path()).is_empty());
}

#[test]
fn in_place_lock_path_of_a_plain_folder_is_in_its_store() {
    let state = tempfile::tempdir().unwrap();
    let folder = tempfile::tempdir().unwrap();
    std::fs::write(folder.path().join("note.txt"), "hello\n").unwrap();
    let before = dir_entries(folder.path());

    let got = in_place_lock_path(state.path(), folder.path()).unwrap();
    let expected_store = folder_store(state.path(), folder.path()).unwrap();
    assert_eq!(got, expected_store.join("in-place.lock"));
    assert!(!got.exists());
    assert_eq!(dir_entries(folder.path()), before);
}

#[test]
fn run_store_of_a_missing_folder_is_an_error_naming_it() {
    let state = tempfile::tempdir().unwrap();
    let parent = tempfile::tempdir().unwrap();
    let missing = parent.path().join("does-not-exist");

    let err = run_store(state.path(), &missing).unwrap_err();
    assert!(err.contains(&missing.display().to_string()), "{err}");
}

#[test]
fn list_records_skips_unreadable_record_and_names_it() {
    let state = tempfile::tempdir().unwrap();
    let repo = tempfile::tempdir().unwrap();
    init_git_repo(repo.path());

    let valid = sample_record("s00000000000000aa", "valid", 18081, 100);
    write_record_in(&surface_dir(repo.path(), &valid.id), &valid).unwrap();

    let bad_dir = surface_dir(repo.path(), "s00000000000000bb");
    std::fs::create_dir_all(&bad_dir).unwrap();
    let bad_path = bad_dir.join("surface.json");
    std::fs::write(&bad_path, "not json").unwrap();

    let listing = list_records_for_root(repo.path(), Some(state.path())).unwrap();
    assert_eq!(listing.records.len(), 1);
    assert_eq!(listing.records[0].record, valid);
    assert_eq!(listing.unreadable.len(), 1);
    assert_eq!(listing.unreadable[0].path, bad_path);
    assert!(!listing.unreadable[0].reason.is_empty());
    assert!(
        !listing.unreadable[0]
            .reason
            .contains(&bad_path.display().to_string()),
        "reason repeated path: {}",
        listing.unreadable[0].reason
    );
}

#[test]
fn list_records_reports_id_mismatch_as_unreadable() {
    let state = tempfile::tempdir().unwrap();
    let repo = tempfile::tempdir().unwrap();
    init_git_repo(repo.path());

    let dir_id = "s00000000000000aa";
    let inner_id = "s00000000000000bb";
    let bad_dir = surface_dir(repo.path(), dir_id);
    std::fs::create_dir_all(&bad_dir).unwrap();
    let bad_path = bad_dir.join("surface.json");
    let rec = sample_record(inner_id, "wrong-dir", 18081, 100);
    std::fs::write(&bad_path, serde_json::to_string_pretty(&rec).unwrap()).unwrap();

    let listing = list_records_for_root(repo.path(), Some(state.path())).unwrap();
    assert!(listing.records.is_empty());
    assert_eq!(listing.unreadable.len(), 1);
    assert_eq!(listing.unreadable[0].path, bad_path);
    assert!(
        listing.unreadable[0].reason.contains("expected"),
        "reason={}",
        listing.unreadable[0].reason
    );
}