blyte 0.92.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
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
use std::cell::RefCell;
use std::ffi::OsString;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread;
use std::time::Duration;

use blyte_agent::sandbox::surface_token_path_for_id;
use blyte_cli::surface_dir::{surface_dir, write_record_in, SurfaceRecord};
use blyte_cli::surface_registry::{entry_path, write_entry, RegistryEntry, SurfaceState};
use blyte_cli::surfaces_cmd::{run_open, run_stopped_surfaces, run_surfaces};

static ENV_MUTEX: Mutex<()> = Mutex::new(());

struct EnvGuard {
    _lock: MutexGuard<'static, ()>,
    prev_xdg: Option<OsString>,
    prev_blyte_state: Option<OsString>,
}

impl EnvGuard {
    fn set_state_root(state_root: &Path) -> Self {
        let lock = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        let prev_xdg = std::env::var_os("XDG_STATE_HOME");
        let prev_blyte_state = std::env::var_os("BLYTE_STATE_DIR");
        std::env::set_var("XDG_STATE_HOME", state_root);
        std::env::set_var("BLYTE_STATE_DIR", state_root.join("blyte"));
        Self {
            _lock: lock,
            prev_xdg,
            prev_blyte_state,
        }
    }
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        match &self.prev_xdg {
            Some(v) => std::env::set_var("XDG_STATE_HOME", v),
            None => std::env::remove_var("XDG_STATE_HOME"),
        }
        match &self.prev_blyte_state {
            Some(v) => std::env::set_var("BLYTE_STATE_DIR", v),
            None => std::env::remove_var("BLYTE_STATE_DIR"),
        }
    }
}

struct MockHealthServer {
    port: u16,
    stop: Arc<AtomicBool>,
    handle: Option<thread::JoinHandle<()>>,
    recorded_open_code_requests: Arc<Mutex<Vec<String>>>,
}

impl MockHealthServer {
    fn start(surface_id: &str) -> Self {
        Self::start_with_open_code(surface_id, Ok("mock-open-code-abc123".to_string()))
    }

    fn start_with_open_code(surface_id: &str, open_code_reply: Result<String, u16>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let stop = Arc::new(AtomicBool::new(false));
        let stop_bg = Arc::clone(&stop);
        let recorded = Arc::new(Mutex::new(Vec::new()));
        let recorded_bg = Arc::clone(&recorded);
        let health_body = format!(r#"{{"surface_id":"{surface_id}"}}"#);
        let handle = thread::spawn(move || {
            for stream in listener.incoming() {
                if stop_bg.load(Ordering::Relaxed) {
                    break;
                }
                let Ok(mut stream) = stream else {
                    break;
                };
                let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
                let mut req = Vec::new();
                let mut buf = [0u8; 512];
                while !req.windows(4).any(|w| w == b"\r\n\r\n") {
                    match stream.read(&mut buf) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => req.extend_from_slice(&buf[..n]),
                    }
                }
                let req_str = String::from_utf8_lossy(&req).to_string();
                let first_line = req_str.lines().next().unwrap_or("");
                let resp = if first_line.starts_with("POST /api/session/open-codes ") {
                    recorded_bg.lock().unwrap().push(req_str);
                    match &open_code_reply {
                        Ok(code) => {
                            let body = format!(r#"{{"code":"{code}"}}"#);
                            format!(
                                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                                body.len(),
                                body
                            )
                        }
                        Err(status) => {
                            let body = r#"{"error":"boom"}"#;
                            format!(
                                "HTTP/1.1 {status} Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                                body.len(),
                                body
                            )
                        }
                    }
                } else {
                    format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                        health_body.len(),
                        health_body
                    )
                };
                let _ = stream.write_all(resp.as_bytes());
                let _ = stream.flush();
            }
        });
        Self {
            port,
            stop,
            handle: Some(handle),
            recorded_open_code_requests: recorded,
        }
    }
}

impl Drop for MockHealthServer {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        let _ = TcpStream::connect(("127.0.0.1", self.port));
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

fn make_entry(
    id: &str,
    name: &str,
    root: &str,
    branch: &str,
    port: u16,
    started_at: u64,
    doing: &str,
) -> RegistryEntry {
    RegistryEntry {
        id: id.to_string(),
        name: name.to_string(),
        root: PathBuf::from(root),
        branch: Some(branch.to_string()),
        pid: std::process::id(),
        port,
        started_at,
        doing: doing.to_string(),
        state: SurfaceState::Idle,
        runtime: blyte_cli::surface_version::SurfaceRuntimeInfo::current().unwrap(),
    }
}

#[test]
fn run_surfaces_with_no_entries_prints_empty_message() {
    let tmp = tempfile::tempdir().unwrap();
    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_surfaces(tmp.path(), false, &mut out, &mut err);
    assert_eq!(code, 0);
    assert_eq!(String::from_utf8(out).unwrap(), "no surfaces are running\n");
    assert!(err.is_empty());
}

#[test]
fn run_surfaces_prints_aligned_table_in_started_at_order() {
    let tmp = tempfile::tempdir().unwrap();
    let server_a = MockHealthServer::start("s00000000000000aa");
    let server_b = MockHealthServer::start("s00000000000000bb");

    let mut later = make_entry(
        "s00000000000000bb",
        "payments-api",
        "/tmp/work/payments",
        "feat/webhooks",
        server_b.port,
        200,
        "add retry backoff",
    );
    later.state = SurfaceState::Working;
    let frontend_dir = tmp.path().join("frontend");
    std::fs::create_dir_all(&frontend_dir).unwrap();
    let earlier = make_entry(
        "s00000000000000aa",
        "web",
        frontend_dir.to_str().unwrap(),
        "main",
        server_a.port,
        100,
        "idle",
    );
    write_entry(tmp.path(), &later).unwrap();
    write_entry(tmp.path(), &earlier).unwrap();

    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_surfaces(tmp.path(), false, &mut out, &mut err);
    assert_eq!(code, 0);
    assert!(err.is_empty());

    let stdout = String::from_utf8(out).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    let version = blyte_cli::surface_version::CURRENT_VERSION;
    let ver_w = version.chars().count().max("VERSION".len());
    assert_eq!(lines.len(), 3, "{stdout}");
    assert_eq!(
        lines[0],
        format!(
            "NAME          REPOSITORY  BRANCH         {:<ver_w$}  STATE    DOING",
            "VERSION"
        )
    );
    assert_eq!(
        lines[1],
        format!("web           frontend    main           {version:<ver_w$}  idle     idle")
    );
    assert_eq!(
        lines[2],
        format!(
            "payments-api  payments    feat/webhooks  {version:<ver_w$}  working  add retry backoff"
        )
    );
}

#[test]
fn run_surfaces_table_prints_all_four_state_wordings() {
    let tmp = tempfile::tempdir().unwrap();
    let s1 = MockHealthServer::start("s00000000000000a1");
    let s2 = MockHealthServer::start("s00000000000000a2");
    let s3 = MockHealthServer::start("s00000000000000a3");
    let s4 = MockHealthServer::start("s00000000000000a4");

    let mut e1 = make_entry(
        "s00000000000000a1",
        "one",
        "/tmp/r1",
        "main",
        s1.port,
        100,
        "run deploy",
    );
    e1.state = SurfaceState::Approval;
    let mut e2 = make_entry(
        "s00000000000000a2",
        "two",
        "/tmp/r2",
        "main",
        s2.port,
        200,
        "idle",
    );
    e2.state = SurfaceState::Replied;
    let mut e3 = make_entry(
        "s00000000000000a3",
        "three",
        "/tmp/r3",
        "main",
        s3.port,
        300,
        "fix bug",
    );
    e3.state = SurfaceState::Working;
    let r4_dir = tmp.path().join("r4");
    std::fs::create_dir_all(&r4_dir).unwrap();
    let mut e4 = make_entry(
        "s00000000000000a4",
        "four",
        r4_dir.to_str().unwrap(),
        "main",
        s4.port,
        400,
        "idle",
    );
    e4.state = SurfaceState::Idle;

    for e in [&e1, &e2, &e3, &e4] {
        write_entry(tmp.path(), e).unwrap();
    }

    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_surfaces(tmp.path(), false, &mut out, &mut err);
    assert_eq!(code, 0);
    assert!(err.is_empty());

    let stdout = String::from_utf8(out).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    let version = blyte_cli::surface_version::CURRENT_VERSION;
    let ver_w = version.chars().count().max("VERSION".len());
    assert_eq!(lines.len(), 5, "{stdout}");
    assert_eq!(
        lines[0],
        format!(
            "NAME   REPOSITORY  BRANCH  {:<ver_w$}  STATE                      DOING",
            "VERSION"
        )
    );
    assert_eq!(
        lines[1],
        format!(
            "one    r1          main    {version:<ver_w$}  waiting on you (approval)  run deploy"
        )
    );
    assert_eq!(
        lines[2],
        format!("two    r2          main    {version:<ver_w$}  waiting on you (replied)   idle")
    );
    assert_eq!(
        lines[3],
        format!("three  r3          main    {version:<ver_w$}  working                    fix bug")
    );
    assert_eq!(
        lines[4],
        format!("four   r4          main    {version:<ver_w$}  idle                       idle")
    );
}

#[test]
fn run_surfaces_json_outputs_entries_and_empty_array() {
    let tmp = tempfile::tempdir().unwrap();

    let mut out_empty = Vec::new();
    let mut err_empty = Vec::new();
    let code_empty = run_surfaces(tmp.path(), true, &mut out_empty, &mut err_empty);
    assert_eq!(code_empty, 0);
    assert!(err_empty.is_empty());
    assert_eq!(String::from_utf8(out_empty).unwrap().trim(), "[]");

    let server_a = MockHealthServer::start("s00000000000000aa");
    let server_b = MockHealthServer::start("s00000000000000bb");
    let first = make_entry(
        "s00000000000000aa",
        "alpha",
        "/tmp/repo-a",
        "main",
        server_a.port,
        100,
        "idle",
    );
    let second = make_entry(
        "s00000000000000bb",
        "beta",
        "/tmp/repo-b",
        "dev",
        server_b.port,
        200,
        "refactor parser",
    );
    write_entry(tmp.path(), &second).unwrap();
    write_entry(tmp.path(), &first).unwrap();

    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_surfaces(tmp.path(), true, &mut out, &mut err);
    assert_eq!(code, 0);
    assert!(err.is_empty());
    let parsed: Vec<RegistryEntry> = serde_json::from_slice(&out).unwrap();
    assert_eq!(parsed, vec![first, second]);
}

#[test]
fn run_open_posts_for_open_code_with_token_header_and_opens_open_url() {
    let state = tempfile::tempdir().unwrap();
    let _guard = EnvGuard::set_state_root(state.path());

    let dir = tempfile::tempdir().unwrap();
    let server = MockHealthServer::start_with_open_code(
        "s00000000000000aa",
        Ok("one-time-code-777".to_string()),
    );
    let entry = make_entry(
        "s00000000000000aa",
        "alpha",
        "/tmp/repo-a",
        "main",
        server.port,
        100,
        "idle",
    );
    write_entry(dir.path(), &entry).unwrap();

    let token = "secret-token-xyz-9876";
    let token_path = surface_token_path_for_id(&entry.id).unwrap();
    std::fs::create_dir_all(token_path.parent().unwrap()).unwrap();
    std::fs::write(&token_path, format!("{token}\n")).unwrap();

    let opened: RefCell<Vec<String>> = RefCell::new(Vec::new());
    let opener = |url: &str| opened.borrow_mut().push(url.to_string());
    let mut out = Vec::new();
    let mut err = Vec::new();

    let code = run_open(dir.path(), "alpha", &opener, &mut out, &mut err);
    assert_eq!(code, 0);
    let expected_url = format!("http://127.0.0.1:{}/#open=one-time-code-777", server.port);
    assert_eq!(*opened.borrow(), vec![expected_url]);
    assert!(!opened.borrow()[0].contains(token));

    let reqs = server.recorded_open_code_requests.lock().unwrap();
    assert_eq!(reqs.len(), 1);
    assert!(
        reqs[0].contains(&format!("X-Blyte-Token: {token}")),
        "expected token header in request: {}",
        reqs[0]
    );

    let stdout = String::from_utf8(out).unwrap();
    let stderr = String::from_utf8(err).unwrap();
    assert_eq!(stdout, "blyte: opened surface alpha\n");
    assert!(stderr.is_empty());
    assert!(!stdout.contains(token));
    assert!(!stderr.contains(token));
}

#[test]
fn run_open_fails_with_surface_name_and_opens_nothing_when_server_returns_500() {
    let state = tempfile::tempdir().unwrap();
    let _guard = EnvGuard::set_state_root(state.path());

    let dir = tempfile::tempdir().unwrap();
    let server = MockHealthServer::start_with_open_code("s00000000000000aa", Err(500));
    let entry = make_entry(
        "s00000000000000aa",
        "payments",
        "/tmp/repo-a",
        "main",
        server.port,
        100,
        "idle",
    );
    write_entry(dir.path(), &entry).unwrap();

    let token = "secret-token-xyz-9876";
    let token_path = surface_token_path_for_id(&entry.id).unwrap();
    std::fs::create_dir_all(token_path.parent().unwrap()).unwrap();
    std::fs::write(&token_path, format!("{token}\n")).unwrap();

    let opened: RefCell<Vec<String>> = RefCell::new(Vec::new());
    let opener = |url: &str| opened.borrow_mut().push(url.to_string());
    let mut out = Vec::new();
    let mut err = Vec::new();

    let code = run_open(dir.path(), "payments", &opener, &mut out, &mut err);
    assert_eq!(code, 1);
    assert!(opened.borrow().is_empty());
    assert!(out.is_empty());
    let stderr = String::from_utf8(err).unwrap();
    assert!(stderr.contains("payments"), "stderr: {stderr}");
    assert!(!stderr.contains(token), "stderr must not leak token");
}

#[test]
fn run_open_unknown_name_returns_1_without_calling_opener() {
    let dir = tempfile::tempdir().unwrap();
    let opened: RefCell<Vec<String>> = RefCell::new(Vec::new());
    let opener = |url: &str| opened.borrow_mut().push(url.to_string());
    let mut out = Vec::new();
    let mut err = Vec::new();

    let code = run_open(dir.path(), "ghost", &opener, &mut out, &mut err);
    assert_eq!(code, 1);
    assert!(opened.borrow().is_empty());
    assert!(out.is_empty());
    let stderr = String::from_utf8(err).unwrap();
    assert!(
        stderr.contains("no running surface named ghost"),
        "{stderr}"
    );
}

#[test]
fn run_open_missing_or_unusable_token_returns_1_without_calling_opener() {
    let state = tempfile::tempdir().unwrap();
    let _guard = EnvGuard::set_state_root(state.path());

    let dir = tempfile::tempdir().unwrap();
    let server = MockHealthServer::start("s00000000000000aa");
    let entry = make_entry(
        "s00000000000000aa",
        "alpha",
        "/tmp/repo-a",
        "main",
        server.port,
        100,
        "idle",
    );
    write_entry(dir.path(), &entry).unwrap();

    let opened: RefCell<Vec<String>> = RefCell::new(Vec::new());
    let opener = |url: &str| opened.borrow_mut().push(url.to_string());

    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_open(dir.path(), "alpha", &opener, &mut out, &mut err);
    assert_eq!(code, 1);
    assert!(opened.borrow().is_empty());
    assert!(out.is_empty());
    let stderr = String::from_utf8(err).unwrap();
    assert!(stderr.contains("has no usable token"), "{stderr}");

    let token_path = surface_token_path_for_id(&entry.id).unwrap();
    std::fs::create_dir_all(token_path.parent().unwrap()).unwrap();
    std::fs::write(&token_path, "   \n  ").unwrap();
    let mut out2 = Vec::new();
    let mut err2 = Vec::new();
    let code2 = run_open(dir.path(), "alpha", &opener, &mut out2, &mut err2);
    assert_eq!(code2, 1);
    assert!(opened.borrow().is_empty());
    let stderr2 = String::from_utf8(err2).unwrap();
    assert!(stderr2.contains("has no usable token"), "{stderr2}");

    std::fs::write(&token_path, "line1\nline2\n").unwrap();
    let mut out3 = Vec::new();
    let mut err3 = Vec::new();
    let code3 = run_open(dir.path(), "alpha", &opener, &mut out3, &mut err3);
    assert_eq!(code3, 1);
    assert!(opened.borrow().is_empty());
    let stderr3 = String::from_utf8(err3).unwrap();
    assert!(stderr3.contains("has no usable token"), "{stderr3}");
}

#[test]
fn blyte_surfaces_binary_with_empty_state_dir_prints_no_surfaces() {
    let state = tempfile::tempdir().unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_blyte"))
        .arg("surfaces")
        .env("BLYTE_STATE_DIR", state.path())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        String::from_utf8(output.stdout).unwrap(),
        "no surfaces are running\n"
    );
}

#[test]
fn blyte_help_lists_surfaces_and_open() {
    let output = Command::new(env!("CARGO_BIN_EXE_blyte"))
        .arg("--help")
        .output()
        .unwrap();
    assert!(output.status.success());
    let help = String::from_utf8(output.stdout).unwrap();
    assert!(help.contains("surfaces"), "{help}");
    assert!(
        help.contains("List the surfaces running on this machine"),
        "{help}"
    );
    assert!(help.contains("open"), "{help}");
    assert!(
        help.contains("Open a running surface's page by name"),
        "{help}"
    );
}

#[test]
fn run_surfaces_lists_valid_surface_and_prints_skipped_line_on_stderr() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();
    let server = MockHealthServer::start("s00000000000000aa");
    let valid = make_entry(
        "s00000000000000aa",
        "alpha",
        "/tmp/repo-a",
        "main",
        server.port,
        100,
        "idle",
    );
    write_entry(dir, &valid).unwrap();

    let bad_path = entry_path(dir, "s00000000000000bb");
    std::fs::write(
        &bad_path,
        r#"{"id":"s00000000000000bb","name":"legacy","root":"/tmp/old","branch":"main","pid":1,"port":18081,"started_at":200,"doing":"idle"}"#,
    )
    .unwrap();

    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_surfaces(dir, false, &mut out, &mut err);
    assert_eq!(code, 0);
    let stdout = String::from_utf8(out).unwrap();
    let stderr = String::from_utf8(err).unwrap();
    assert!(stdout.contains("alpha"), "{stdout}");
    let expected_prefix = format!("blyte: skipped surface record {}: ", bad_path.display());
    assert!(stderr.starts_with(&expected_prefix), "{stderr}");
    assert!(stderr.contains("missing field `state`"), "{stderr}");
    assert_eq!(stderr.lines().count(), 1, "{stderr}");
    assert!(bad_path.exists());

    let mut json_out = Vec::new();
    let mut json_err = Vec::new();
    let json_code = run_surfaces(dir, true, &mut json_out, &mut json_err);
    assert_eq!(json_code, 0);
    let parsed: Vec<RegistryEntry> = serde_json::from_slice(&json_out).unwrap();
    assert_eq!(parsed, vec![valid]);
    let json_stderr = String::from_utf8(json_err).unwrap();
    assert!(json_stderr.starts_with(&expected_prefix), "{json_stderr}");
    assert!(
        json_stderr.contains("missing field `state`"),
        "{json_stderr}"
    );
    assert!(bad_path.exists());
}

#[test]
fn run_stopped_surfaces_lists_valid_surface_and_prints_skipped_line_on_stderr() {
    let state = tempfile::tempdir().unwrap();
    let repo = tempfile::tempdir().unwrap();
    assert!(Command::new("git")
        .args(["init", "-q"])
        .current_dir(repo.path())
        .status()
        .unwrap()
        .success());

    let valid_id = "s00000000000000aa";
    write_record_in(
        &surface_dir(repo.path(), valid_id),
        &SurfaceRecord {
            id: valid_id.to_string(),
            name: "alpha".to_string(),
            pid: 999_999,
            port: 0,
            started_at: 1_700_000_100,
            session_id: format!("sess-{valid_id}"),
        },
    )
    .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 canonical_bad_path = bad_path.canonicalize().unwrap();

    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_stopped_surfaces(repo.path(), state.path(), false, &mut out, &mut err);
    assert_eq!(code, 0);
    let stdout = String::from_utf8(out).unwrap();
    let stderr = String::from_utf8(err).unwrap();
    assert!(stdout.contains("alpha"), "{stdout}");
    let expected_prefix = format!(
        "blyte: skipped surface record {}: ",
        canonical_bad_path.display()
    );
    assert!(
        stderr.contains(&expected_prefix),
        "expected {expected_prefix:?} in stderr: {stderr}"
    );
    assert!(bad_path.exists());
}

#[test]
fn run_open_works_for_valid_and_names_unreadable_when_unknown() {
    let state = tempfile::tempdir().unwrap();
    let _guard = EnvGuard::set_state_root(state.path());

    let dir = tempfile::tempdir().unwrap();
    let server =
        MockHealthServer::start_with_open_code("s00000000000000aa", Ok("open-code-ok".to_string()));
    let valid = make_entry(
        "s00000000000000aa",
        "alpha",
        "/tmp/repo-a",
        "main",
        server.port,
        100,
        "idle",
    );
    write_entry(dir.path(), &valid).unwrap();

    let bad_path = entry_path(dir.path(), "s00000000000000bb");
    std::fs::write(
        &bad_path,
        r#"{"id":"s00000000000000bb","name":"legacy","root":"/tmp/old","branch":"main","pid":1,"port":18081,"started_at":200,"doing":"idle"}"#,
    )
    .unwrap();

    let token_path = surface_token_path_for_id(&valid.id).unwrap();
    std::fs::create_dir_all(token_path.parent().unwrap()).unwrap();
    std::fs::write(&token_path, "secret-token\n").unwrap();

    let opened: RefCell<Vec<String>> = RefCell::new(Vec::new());
    let opener = |url: &str| opened.borrow_mut().push(url.to_string());
    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_open(dir.path(), "alpha", &opener, &mut out, &mut err);
    assert_eq!(code, 0);
    assert_eq!(opened.borrow().len(), 1);
    assert!(bad_path.exists());

    let mut out_missing = Vec::new();
    let mut err_missing = Vec::new();
    let code_missing = run_open(
        dir.path(),
        "ghost",
        &opener,
        &mut out_missing,
        &mut err_missing,
    );
    assert_eq!(code_missing, 1);
    let stderr_missing = String::from_utf8(err_missing).unwrap();
    assert!(
        stderr_missing.contains("no running surface named ghost"),
        "{stderr_missing}"
    );
    assert!(
        stderr_missing.contains(&bad_path.display().to_string()),
        "{stderr_missing}"
    );
    assert!(bad_path.exists());
}

#[test]
fn starting_a_surface_skips_unreadable_record_and_prints_stderr_line() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("demo-repo");
    let state = tmp.path().join("state");
    let reg_dir = state.join("surfaces");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::create_dir_all(&reg_dir).unwrap();

    assert!(Command::new("git")
        .args(["init", "-q"])
        .current_dir(&repo)
        .status()
        .unwrap()
        .success());

    let bad_path = entry_path(&reg_dir, "s00000000000000bb");
    std::fs::write(
        &bad_path,
        r#"{"id":"s00000000000000bb","name":"legacy","root":"/tmp/old","branch":"main","pid":1,"port":18081,"started_at":200,"doing":"idle"}"#,
    )
    .unwrap();

    let mut child = Command::new(env!("CARGO_BIN_EXE_blyte"))
        .args(["--foreground", "--no-open", "--port", "0"])
        .current_dir(&repo)
        .env("BLYTE_STATE_DIR", &state)
        .env("BLYTE_ENV_FILE", "")
        .env("BLYTE_NO_UPDATE_CHECK", "1")
        .env("BLYTE_NO_KEEP_AWAKE", "1")
        .env("BLYTE_USAGE_LOG", "off")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    let stdout = child.stdout.take().unwrap();
    let mut stderr = child.stderr.take().unwrap();
    let mut reader = BufReader::new(stdout);
    let mut line = String::new();
    let started = loop {
        line.clear();
        let n = reader.read_line(&mut line).unwrap();
        if n == 0 {
            break false;
        }
        if line.contains("http://127.0.0.1:") {
            break true;
        }
    };

    let _ = child.kill();
    let _ = child.wait();

    let mut stderr_text = String::new();
    let _ = stderr.read_to_string(&mut stderr_text);

    assert!(started, "surface failed to start; stderr={stderr_text}");
    let expected_prefix = format!("blyte: skipped surface record {}: ", bad_path.display());
    assert!(
        stderr_text.contains(&expected_prefix),
        "stderr={stderr_text}"
    );
    assert!(
        stderr_text.contains("missing field `state`"),
        "stderr={stderr_text}"
    );
    assert!(bad_path.exists());
}