blyte 0.88.1

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
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::{mpsc, Arc, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use blyte_agent::sandbox::surface_token_path_for_id;
use blyte_agent::tools::PeerTools;
use blyte_cli::http::Request;
use blyte_cli::serve::{generate_token, route, OpenCodes, Surface, TOKEN_HEADER};
use blyte_cli::session::{EntryBody, PromptRunner, Session};
use blyte_cli::surface_dir::{
    list_records_in, read_record_in, surfaces_dir, write_record_in, SurfaceRecord,
};
use blyte_cli::surface_registry::{
    entry_path, read_entries, write_entry, RegistryEntry, SurfaceState,
};
use blyte_cli::surface_version::{BinaryFingerprint, SurfaceRuntimeInfo, CURRENT_VERSION};
use blyte_cli::surfaces_cmd::{run_surfaces, surfaces_payload};
use blyte_cli::tell::SurfacePeerTools;

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 NoopRunner;

impl PromptRunner for NoopRunner {
    fn run(
        &mut self,
        _prompt: &str,
        _model: &str,
        _emit: &(dyn Fn(EntryBody) + Sync),
    ) -> Result<(), String> {
        Ok(())
    }
}

struct MockHealthServer {
    port: u16,
    stop: Arc<AtomicBool>,
    handle: Option<JoinHandle<()>>,
}

impl MockHealthServer {
    fn start(surface_id: &str) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        listener.set_nonblocking(true).unwrap();
        let stop = Arc::new(AtomicBool::new(false));
        let stop_flag = Arc::clone(&stop);
        let id = surface_id.to_string();
        let handle = std::thread::spawn(move || {
            while !stop_flag.load(Ordering::Relaxed) {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
                        let mut buf = [0u8; 1024];
                        let _ = stream.read(&mut buf);
                        let body = format!(r#"{{"surface_id":"{id}"}}"#);
                        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
                        );
                        let _ = stream.write_all(resp.as_bytes());
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(Duration::from_millis(10));
                    }
                    Err(_) => break,
                }
            }
        });
        Self {
            port,
            stop,
            handle: Some(handle),
        }
    }
}

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: PathBuf,
    port: u16,
    started_at: u64,
    runtime: SurfaceRuntimeInfo,
) -> RegistryEntry {
    RegistryEntry {
        id: id.to_string(),
        name: name.to_string(),
        root,
        branch: Some("main".to_string()),
        pid: std::process::id(),
        port,
        started_at,
        doing: "idle".to_string(),
        state: SurfaceState::Idle,
        runtime,
    }
}

fn make_surface(root: PathBuf, runtime: SurfaceRuntimeInfo) -> Surface {
    let session = Session::start(Box::new(NoopRunner), "m1".to_string());
    let mcp = Arc::new(blyte_cli::mcp::McpManager::empty_in(&root));
    Surface {
        surface_id: "s00000000000000aa".to_string(),
        surface_name: "alpha".to_string(),
        root,
        repo: "alpha".to_string(),
        session,
        session_id: "sess-version-test".to_string(),
        started_at: 1_700_000_000,
        runtime,
        days: 14,
        token: generate_token().unwrap(),
        message_credential: generate_token().unwrap(),
        open_codes: OpenCodes::new(),
        requests: Arc::new(blyte_cli::requests::RequestsState::new()),
        publisher: Arc::new(blyte_cli::requests::RealPublisher),
        mcp,
        reconcile_lock: Mutex::new(()),
        reconcile_requested: AtomicBool::new(false),
    }
}

fn make_get_request(path: &str, token: &str) -> Request {
    Request {
        method: "GET".to_string(),
        path: path.to_string(),
        query: Vec::new(),
        headers: vec![(TOKEN_HEADER.to_string(), token.to_string())],
        body: Vec::new(),
    }
}

fn write_token(id: &str, token: &str) {
    let token_path = surface_token_path_for_id(id).unwrap();
    std::fs::create_dir_all(token_path.parent().unwrap()).unwrap();
    std::fs::write(&token_path, format!("{token}\n")).unwrap();
}

fn init_repo_with_commit(repo: &Path) {
    std::fs::create_dir_all(repo).unwrap();
    let run = |args: &[&str]| {
        let out = Command::new("git")
            .args(args)
            .current_dir(repo)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&out.stderr)
        );
    };
    run(&["init", "-b", "main"]);
    run(&["config", "user.name", "Test"]);
    run(&["config", "user.email", "test@example.com"]);
    std::fs::write(repo.join("README.md"), "hello\n").unwrap();
    run(&["add", "README.md"]);
    run(&["commit", "-m", "initial"]);
}

#[test]
fn binary_fingerprint_detects_unchanged_modified_replaced_and_missing_binary() {
    let tmp = tempfile::tempdir().unwrap();
    let bin = tmp.path().join("blyte-bin");
    std::fs::write(&bin, b"version-1-bytes").unwrap();

    let fp = BinaryFingerprint::from_path(&bin).unwrap();
    assert_eq!(fp.path, bin);
    assert_eq!(fp.size, b"version-1-bytes".len() as u64);
    assert!(!fp.is_stale().unwrap());

    std::fs::write(&bin, b"version-2-longer-bytes").unwrap();
    assert!(fp.is_stale().unwrap());

    let fp2 = BinaryFingerprint::from_path(&bin).unwrap();
    assert!(!fp2.is_stale().unwrap());

    let replacement = tmp.path().join("blyte-bin.new");
    std::fs::write(&replacement, b"version-3-replaced-bin").unwrap();
    std::fs::rename(&replacement, &bin).unwrap();
    assert!(fp2.is_stale().unwrap());

    std::fs::remove_file(&bin).unwrap();
    let err = fp2.is_stale().unwrap_err();
    assert!(
        err.contains(&bin.display().to_string()),
        "error should name the missing binary: {err}"
    );
}

#[test]
fn surface_runtime_info_generates_distinct_boot_ids_and_validates() {
    let a = SurfaceRuntimeInfo::current().unwrap();
    let b = SurfaceRuntimeInfo::current().unwrap();
    assert_eq!(a.version, CURRENT_VERSION);
    assert_eq!(b.version, CURRENT_VERSION);
    assert!(!a.boot_id.is_empty());
    assert!(!b.boot_id.is_empty());
    assert_ne!(a.boot_id, b.boot_id);
    assert!(!a.is_stale().unwrap());
    assert!(!b.is_stale().unwrap());

    let tmp = tempfile::tempdir().unwrap();
    let bin = tmp.path().join("blyte");
    std::fs::write(&bin, b"bin").unwrap();
    assert!(SurfaceRuntimeInfo::from_binary("", &bin, "boot-1").is_err());
    assert!(SurfaceRuntimeInfo::from_binary("0.83.0", &bin, "   ").is_err());
    assert!(SurfaceRuntimeInfo::from_binary("0.83.0", &tmp.path().join("missing"), "b1").is_err());
}

#[test]
fn surface_record_omits_runtime_and_registry_entry_requires_it() {
    let tmp = tempfile::tempdir().unwrap();
    let fake_bin = tmp.path().join("blyte");
    std::fs::write(&fake_bin, b"fake-blyte-binary").unwrap();
    let runtime =
        SurfaceRuntimeInfo::from_binary("0.83.0 (abc1234)", &fake_bin, "boot-rt-1").unwrap();

    let sdir = tmp.path().join("s00000000000000a1");
    let record = SurfaceRecord {
        id: "s00000000000000a1".to_string(),
        name: "alpha".to_string(),
        pid: std::process::id(),
        port: 4321,
        session_id: "sess-1".to_string(),
        started_at: 1_700_000_000,
    };
    write_record_in(&sdir, &record).unwrap();
    let raw_record: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sdir.join("surface.json")).unwrap()).unwrap();
    assert!(raw_record.get("version").is_none());
    assert!(raw_record.get("boot_id").is_none());
    assert!(raw_record.get("binary_fingerprint").is_none());
    let loaded_record = read_record_in(&sdir, &record.id).unwrap();
    assert_eq!(loaded_record, record);

    let legacy_dir = tmp.path().join("s00000000000000a2");
    std::fs::create_dir_all(&legacy_dir).unwrap();
    std::fs::write(
        legacy_dir.join("surface.json"),
        r#"{"id":"s00000000000000a2","name":"legacy","pid":123,"port":0,"session_id":"s","started_at":1}"#,
    )
    .unwrap();
    let legacy_record = read_record_in(&legacy_dir, "s00000000000000a2").unwrap();
    assert_eq!(legacy_record.name, "legacy");
    assert_eq!(legacy_record.pid, 123);
    assert_eq!(legacy_record.session_id, "s");
    assert_eq!(legacy_record.started_at, 1);

    let newer_dir = tmp.path().join("s00000000000000a3");
    std::fs::create_dir_all(&newer_dir).unwrap();
    std::fs::write(
        newer_dir.join("surface.json"),
        r#"{"id":"s00000000000000a3","name":"newer","pid":7,"port":0,"session_id":"s3","started_at":2,"version":"0.85.0 (055df959)","binary_fingerprint":{"path":"/x/blyte","size":1,"modified_secs":1,"modified_nanos":0},"boot_id":"b"}"#,
    )
    .unwrap();
    let newer_record = read_record_in(&newer_dir, "s00000000000000a3").unwrap();
    assert_eq!(newer_record.name, "newer");
    assert_eq!(newer_record.pid, 7);

    let reg_dir = tmp.path().join("registry");
    let entry = make_entry(
        "s00000000000000a1",
        "alpha",
        tmp.path().join("repo"),
        4321,
        1_700_000_000,
        runtime.clone(),
    );
    write_entry(&reg_dir, &entry).unwrap();
    let raw_entry: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(entry_path(&reg_dir, &entry.id)).unwrap())
            .unwrap();
    assert_eq!(raw_entry["version"], "0.83.0 (abc1234)");
    assert_eq!(raw_entry["boot_id"], "boot-rt-1");
    assert_eq!(
        raw_entry["binary_fingerprint"]["path"],
        fake_bin.to_string_lossy().as_ref()
    );

    let legacy_reg_path = entry_path(&reg_dir, "s00000000000000a2");
    std::fs::write(
        &legacy_reg_path,
        r#"{"id":"s00000000000000a2","name":"legacy","root":"/tmp/r","branch":"main","pid":1,"port":0,"started_at":1,"doing":"idle","state":"idle"}"#,
    )
    .unwrap();
    let listing = read_entries(&reg_dir).unwrap();
    assert_eq!(listing.entries, vec![entry]);
    assert_eq!(listing.unreadable.len(), 1);
    assert_eq!(listing.unreadable[0].path, legacy_reg_path);
    assert!(
        listing.unreadable[0].reason.contains("missing field"),
        "unexpected unreadable reason: {}",
        listing.unreadable[0].reason
    );
    assert!(
        legacy_reg_path.exists(),
        "unreadable registry entry must not be deleted"
    );
}

#[test]
fn surfaces_cli_peer_tool_and_switcher_payload_report_version_and_staleness() {
    let tmp = tempfile::tempdir().unwrap();
    let _env_guard = EnvGuard::set_state_root(tmp.path());
    let state_dir = tmp.path().join("blyte");
    let reg_dir = state_dir.join("surfaces");
    let repo_a = tmp.path().join("repo-current");
    let repo_b = tmp.path().join("repo-stale");
    let repo_c = tmp.path().join("repo-missing-bin");
    std::fs::create_dir_all(&repo_a).unwrap();
    std::fs::create_dir_all(&repo_b).unwrap();
    std::fs::create_dir_all(&repo_c).unwrap();

    let bin_current = tmp.path().join("blyte-current");
    let bin_stale = tmp.path().join("blyte-stale");
    let bin_missing = tmp.path().join("blyte-missing");
    std::fs::write(&bin_current, b"current-binary").unwrap();
    std::fs::write(&bin_stale, b"old-binary").unwrap();
    std::fs::write(&bin_missing, b"vanishing-binary").unwrap();

    let rt_current =
        SurfaceRuntimeInfo::from_binary("0.83.0 (aaaaaaa)", &bin_current, "boot-cur").unwrap();
    let rt_stale =
        SurfaceRuntimeInfo::from_binary("0.82.0 (bbbbbbb)", &bin_stale, "boot-old").unwrap();
    let rt_missing =
        SurfaceRuntimeInfo::from_binary("0.81.0 (ccccccc)", &bin_missing, "boot-gone").unwrap();

    std::fs::write(&bin_stale, b"rebuilt-newer-binary-bytes").unwrap();
    std::fs::remove_file(&bin_missing).unwrap();

    let srv_a = MockHealthServer::start("s00000000000000b1");
    let srv_b = MockHealthServer::start("s00000000000000b2");
    let srv_c = MockHealthServer::start("s00000000000000b3");

    let entry_a = make_entry(
        "s00000000000000b1",
        "current-surf",
        repo_a,
        srv_a.port,
        100,
        rt_current,
    );
    let entry_b = make_entry(
        "s00000000000000b2",
        "stale-surf",
        repo_b,
        srv_b.port,
        200,
        rt_stale,
    );
    let entry_c = make_entry(
        "s00000000000000b3",
        "missing-bin-surf",
        repo_c,
        srv_c.port,
        300,
        rt_missing,
    );
    write_entry(&reg_dir, &entry_a).unwrap();
    write_entry(&reg_dir, &entry_b).unwrap();
    write_entry(&reg_dir, &entry_c).unwrap();
    write_token(&entry_a.id, "tok-a");
    write_token(&entry_b.id, "tok-b");
    write_token(&entry_c.id, "tok-c");

    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = run_surfaces(&reg_dir, false, &mut out, &mut err);
    assert_eq!(code, 0);
    assert!(
        err.is_empty(),
        "unexpected stderr: {:?}",
        String::from_utf8_lossy(&err)
    );
    let table = String::from_utf8(out).unwrap();
    let lines: Vec<&str> = table.lines().collect();
    assert_eq!(lines.len(), 4, "{table}");
    assert!(lines[0].contains("VERSION"), "{table}");
    assert!(lines[1].contains("0.83.0 (aaaaaaa)"), "{table}");
    assert!(!lines[1].contains("(stale)"), "{table}");
    assert!(lines[2].contains("0.82.0 (bbbbbbb) (stale)"), "{table}");
    assert!(
        lines[3].contains("0.81.0 (ccccccc) (stale unknown:"),
        "{table}"
    );

    let mut json_out = Vec::new();
    let mut json_err = Vec::new();
    let json_code = run_surfaces(&reg_dir, true, &mut json_out, &mut json_err);
    assert_eq!(json_code, 0);
    assert!(json_err.is_empty());
    let parsed: Vec<serde_json::Value> = serde_json::from_slice(&json_out).unwrap();
    assert_eq!(parsed.len(), 3);
    assert_eq!(parsed[0]["version"], "0.83.0 (aaaaaaa)");
    assert_eq!(parsed[0]["boot_id"], "boot-cur");
    assert_eq!(parsed[0]["stale"], false);
    assert!(parsed[0].get("stale_error").is_none());
    assert_eq!(parsed[1]["version"], "0.82.0 (bbbbbbb)");
    assert_eq!(parsed[1]["boot_id"], "boot-old");
    assert_eq!(parsed[1]["stale"], true);
    assert!(parsed[1].get("stale_error").is_none());
    assert_eq!(parsed[2]["version"], "0.81.0 (ccccccc)");
    assert_eq!(parsed[2]["boot_id"], "boot-gone");
    assert!(parsed[2]["stale"].is_null());
    assert!(
        parsed[2]["stale_error"]
            .as_str()
            .unwrap()
            .contains(&bin_missing.display().to_string()),
        "{:?}",
        parsed[2]
    );

    let peer_tools = SurfacePeerTools {
        registry_dir: reg_dir.clone(),
        surface_id: entry_a.id.clone(),
        surface_name: entry_a.name.clone(),
        repository: "repo-current".to_string(),
    };
    let tool_out = peer_tools.surfaces().unwrap();
    let tool_lines: Vec<&str> = tool_out.lines().collect();
    assert_eq!(tool_lines.len(), 4, "{tool_out}");
    assert!(tool_lines[0].contains("VERSION"), "{tool_out}");
    assert!(
        tool_lines[1].contains("current-surf (this surface)"),
        "{tool_out}"
    );
    assert!(tool_lines[1].contains("0.83.0 (aaaaaaa)"), "{tool_out}");
    assert!(!tool_lines[1].contains("(stale)"), "{tool_out}");
    assert!(
        tool_lines[2].contains("0.82.0 (bbbbbbb) (stale)"),
        "{tool_out}"
    );
    assert!(
        tool_lines[3].contains("0.81.0 (ccccccc) (stale unknown:"),
        "{tool_out}"
    );

    let payload = surfaces_payload(&reg_dir, &state_dir, &entry_a.id, &[]).unwrap();
    let surfaces = payload["surfaces"].as_array().unwrap();
    assert_eq!(surfaces.len(), 3);
    let by_name = |name: &str| {
        surfaces
            .iter()
            .find(|s| s["name"].as_str() == Some(name))
            .unwrap()
    };
    let cur = by_name("current-surf");
    assert_eq!(cur["version"], "0.83.0 (aaaaaaa)");
    assert_eq!(cur["boot_id"], "boot-cur");
    assert_eq!(cur["stale"], false);
    assert!(cur["stale_error"].is_null());

    let stale = by_name("stale-surf");
    assert_eq!(stale["version"], "0.82.0 (bbbbbbb)");
    assert_eq!(stale["boot_id"], "boot-old");
    assert_eq!(stale["stale"], true);
    assert!(stale["stale_error"].is_null());

    let missing = by_name("missing-bin-surf");
    assert_eq!(missing["version"], "0.81.0 (ccccccc)");
    assert_eq!(missing["boot_id"], "boot-gone");
    assert!(missing["stale"].is_null());
    assert!(
        missing["stale_error"]
            .as_str()
            .unwrap()
            .contains(&bin_missing.display().to_string()),
        "{missing:?}"
    );
}

#[test]
fn session_http_api_exposes_version_boot_id_and_stale_status() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    let fake_bin = tmp.path().join("blyte-exe");
    std::fs::write(&fake_bin, b"initial-binary").unwrap();

    let runtime =
        SurfaceRuntimeInfo::from_binary("0.83.0 (deadbee)", &fake_bin, "boot-http-1").unwrap();
    let surface = make_surface(repo, runtime);

    let req = make_get_request("/api/session", &surface.token);
    let resp = route(&surface, &req, 1_700_000_010);
    assert_eq!(resp.status, 200);
    let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
    assert_eq!(body["version"], "0.83.0 (deadbee)");
    assert_eq!(body["boot_id"], "boot-http-1");
    assert_eq!(body["stale"], false);

    std::fs::write(&fake_bin, b"updated-binary-content").unwrap();
    let resp_stale = route(&surface, &req, 1_700_000_020);
    assert_eq!(resp_stale.status, 200);
    let body_stale: serde_json::Value = serde_json::from_slice(&resp_stale.body).unwrap();
    assert_eq!(body_stale["version"], "0.83.0 (deadbee)");
    assert_eq!(body_stale["boot_id"], "boot-http-1");
    assert_eq!(body_stale["stale"], true);

    std::fs::remove_file(&fake_bin).unwrap();
    let resp_err = route(&surface, &req, 1_700_000_030);
    assert_eq!(resp_err.status, 500);
    let body_err: serde_json::Value = serde_json::from_slice(&resp_err.body).unwrap();
    assert!(
        body_err["error"]
            .as_str()
            .unwrap()
            .contains(&fake_bin.display().to_string()),
        "expected missing binary path in 500 error, got: {body_err:?}"
    );
}

#[cfg(unix)]
#[test]
fn real_surface_startup_records_version_fingerprint_and_boot_id_everywhere() {
    struct ChildGuard(Option<std::process::Child>);
    impl Drop for ChildGuard {
        fn drop(&mut self) {
            if let Some(mut child) = self.0.take() {
                let _ = child.kill();
                let _ = child.wait();
            }
        }
    }

    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("demo-repo");
    let home = tmp.path().join("home");
    let state_dir = tmp.path().join("state");
    std::fs::create_dir_all(&home).unwrap();
    init_repo_with_commit(&repo);

    let bin_path = PathBuf::from(env!("CARGO_BIN_EXE_blyte"));
    let mut child = Command::new(&bin_path)
        .args(["--foreground", "--no-open", "--port", "0"])
        .current_dir(&repo)
        .env("HOME", &home)
        .env("XDG_CONFIG_HOME", home.join(".config"))
        .env("BLYTE_STATE_DIR", &state_dir)
        .env("BLYTE_ENV_FILE", "")
        .env("BLYTE_NO_UPDATE_CHECK", "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 guard = ChildGuard(Some(child));

    let stderr_handle = std::thread::spawn(move || {
        let mut buf = String::new();
        let _ = stderr.read_to_string(&mut buf);
        buf
    });
    let (tx, rx) = mpsc::channel::<String>();
    let stdout_handle = std::thread::spawn(move || {
        for line in BufReader::new(stdout).lines().map_while(Result::ok) {
            if tx.send(line).is_err() {
                break;
            }
        }
    });

    let deadline = Instant::now() + Duration::from_secs(15);
    let mut url: Option<String> = None;
    let mut seen = Vec::new();
    while Instant::now() < deadline {
        let remaining = deadline.saturating_duration_since(Instant::now());
        match rx.recv_timeout(remaining.min(Duration::from_millis(100))) {
            Ok(line) => {
                if let Some((_, rest)) = line.split_once(" at http://127.0.0.1:") {
                    url = Some(format!("http://127.0.0.1:{rest}"));
                    break;
                }
                seen.push(line);
            }
            Err(mpsc::RecvTimeoutError::Timeout) => {}
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
        }
    }

    let url = match url {
        Some(u) => u,
        None => {
            if let Some(mut c) = guard.0.take() {
                let _ = c.kill();
                let _ = c.wait();
            }
            let err_text = stderr_handle.join().unwrap_or_default();
            drop(rx);
            let _ = stdout_handle.join();
            panic!(
                "surface did not print url\nstdout:\n{}\nstderr:\n{err_text}",
                seen.join("\n")
            );
        }
    };

    let (base, token) = url.split_once("/#token=").unwrap();
    let port: u16 = base
        .strip_prefix("http://127.0.0.1:")
        .unwrap()
        .parse()
        .unwrap();

    let records = list_records_in(&surfaces_dir(&repo)).unwrap().records;
    assert_eq!(records.len(), 1);
    let rec = &records[0].record;

    let reg = read_entries(&state_dir.join("surfaces")).unwrap();
    assert!(reg.unreadable.is_empty(), "{:?}", reg.unreadable);
    assert_eq!(reg.entries.len(), 1);
    let entry = &reg.entries[0];
    assert_eq!(entry.id, rec.id);
    assert_eq!(entry.runtime.version, CURRENT_VERSION);
    assert!(!entry.runtime.boot_id.is_empty());
    assert!(!entry.runtime.is_stale().unwrap());

    let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
    stream
        .set_read_timeout(Some(Duration::from_secs(5)))
        .unwrap();
    let req = format!(
        "GET /api/session HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nConnection: close\r\n\r\n"
    );
    stream.write_all(req.as_bytes()).unwrap();
    let mut raw = String::new();
    stream.read_to_string(&mut raw).unwrap();
    let (_, resp_body) = raw.split_once("\r\n\r\n").unwrap();
    let session_json: serde_json::Value = serde_json::from_str(resp_body).unwrap();
    assert_eq!(session_json["version"], entry.runtime.version);
    assert_eq!(session_json["boot_id"], entry.runtime.boot_id);
    assert_eq!(session_json["stale"], false);

    let pid = guard.0.as_ref().unwrap().id().to_string();
    let _ = Command::new("kill").args(["-TERM", &pid]).status();
    if let Some(mut c) = guard.0.take() {
        let _ = c.wait();
    }
    drop(rx);
    let _ = stdout_handle.join();
    let _ = stderr_handle.join();
}