croft-software 0.2.182

VSCode-style TUI written in Rust
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
//! The files behind local persistent sessions: the per-workspace socket
//! paths (mux, legacy dtach, collab relay, hook, pair records), the sidecar
//! that records when a session started, the liveness probe, and the
//! owner-only socket bind. The session host, the collab relay, the web view
//! and the agent hooks all share these, so this module stays below them;
//! the `croft attach` and `croft ls` commands that drive them live in
//! [`crate::session_cli`].

use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::session_state::dirs_cache_croft;

/// Directory holding one `<hash>.sock` dtach control socket per persistent
/// workspace, each with a `<hash>.json` sidecar recording which workspace it
/// belongs to. Same `$HOME/.cache/croft/sessions` path the remote wrapper uses.
pub(crate) fn sessions_dir() -> PathBuf {
    dirs_cache_croft().join("sessions")
}

/// Fixed-seed hash of the canonical workspace path, so a reattach finds the
/// same session (mirrors `remote::dtach_socket_path`; `DefaultHasher` uses
/// fixed SipHash keys, so the name is stable across croft processes).
fn socket_name(workspace: &Path) -> String {
    use std::hash::Hasher;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    hasher.write(workspace.to_string_lossy().as_bytes());
    format!("{:016x}", hasher.finish())
}

pub(crate) fn socket_path(workspace: &Path) -> PathBuf {
    sessions_dir().join(format!("{}.sock", socket_name(workspace)))
}

/// Socket for a mux (session-host) session. A distinct name from the legacy
/// dtach socket, so a client never speaks croft's frame protocol at a live
/// dtach server (which would feed the frames into the PTY as input).
pub(crate) fn mux_socket_path(workspace: &Path) -> PathBuf {
    sessions_dir().join(format!("{}.mux.sock", socket_name(workspace)))
}

/// Socket carrying Phase D collab ops between independent-viewport
/// participants (never PTY bytes), sibling to the mux socket with the same
/// keying (see docs/MULTIPLAYER.md).
pub(crate) fn collab_socket_path(workspace: &Path) -> PathBuf {
    sessions_dir().join(format!("{}.collab.sock", socket_name(workspace)))
}

/// Socket a running croft answers agent edit approvals on (#346): `croft
/// hook claude-code` connects here for the workspace enclosing its cwd.
/// Same keying as the other workspace sockets.
pub(crate) fn hook_socket_path(workspace: &Path) -> PathBuf {
    sessions_dir().join(format!("{}.hook.sock", socket_name(workspace)))
}

/// Whether a file in the sessions folder is a session's socket: the mux
/// `<hash>.mux.sock` or the legacy dtach `<hash>.sock`, where `<hash>` is a
/// [`socket_name`]. An allowlist, so the next socket that moves into the
/// folder can't show up in `croft ls` as a phantom session.
pub(crate) fn is_session_socket(file_name: &str) -> bool {
    file_name
        .strip_suffix(".mux.sock")
        .or_else(|| file_name.strip_suffix(".sock"))
        .is_some_and(|hash| {
            hash.len() == 16 && hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
        })
}

pub(crate) fn meta_path(socket: &Path) -> PathBuf {
    socket.with_extension("json")
}

/// Sidecar recording the resident navigator's activation for a workspace:
/// `croft pair` writes it and exits; a running croft notices it (or reads it
/// at startup) and seats the pilot in-process. Same keying as the other
/// workspace sidecars.
pub(crate) fn pair_record_path(workspace: &Path) -> PathBuf {
    sessions_dir().join(format!("{}.pair.json", socket_name(workspace)))
}

/// Advisory lock guarding self-appointed navigator ownership for a workspace:
/// exactly one plain croft may host the pilot (and claim collab owner site 1)
/// per workspace. The lock is held for the App's lifetime and released by the
/// OS on exit, so a crashed host hands off to the next croft automatically.
pub(crate) fn pair_host_lock_path(workspace: &Path) -> PathBuf {
    sessions_dir().join(format!("{}.pair-host.lock", socket_name(workspace)))
}

/// Holds the workspace's pair-host lock; the flock releases when this (and its
/// file) drop.
#[derive(Debug)]
pub(crate) struct PairHostLock {
    _file: std::fs::File,
}

/// Why the single-host lock could not be taken. The two are kept apart
/// because they call for opposite remedies: `Busy` means close the other
/// window, `Io` means there is no other window and the lock file itself
/// (its directory, its permissions, the fd table) needs fixing. Folding them
/// together reported a missing config directory as contention (#337).
#[derive(Debug)]
pub(crate) enum PairHostLockError {
    /// Another croft holds the lock.
    Busy,
    /// The lock file could not be created or opened.
    Io(std::io::Error),
}

/// Try to claim the single-host lock at `path` without blocking. `Ok` means
/// this croft may self-appoint owner; `Busy` means another croft already holds
/// it and this one must not host (else two owners would both claim site 1 and
/// corrupt the shared buffer); `Io` means the lock could not be opened at all.
pub(crate) fn try_acquire_pair_host_lock(path: &Path) -> Result<PairHostLock, PairHostLockError> {
    let file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(path)
        .map_err(PairHostLockError::Io)?;
    #[cfg(unix)]
    {
        use std::os::unix::io::AsRawFd;
        // flock is per open-file-description, so two independent opens contend
        // even within one process — the mutual exclusion we want across croft
        // instances. LOCK_NB: fail fast instead of blocking the tick.
        // errno is read in the same breath as the call: anything run in
        // between could overwrite it and turn a Busy into a spurious Io.
        // EINTR carries no information for the user (nothing at the path
        // to fix), so it is retried like every other syscall site here.
        let e = loop {
            let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
            let e = std::io::Error::last_os_error();
            if rc == 0 {
                return Ok(PairHostLock { _file: file });
            }
            if e.kind() != std::io::ErrorKind::Interrupted {
                break e;
            }
        };
        // EWOULDBLOCK is contention; anything else (ENOLCK, EROFS) is the
        // environment, not another window.
        Err(if e.kind() == std::io::ErrorKind::WouldBlock {
            PairHostLockError::Busy
        } else {
            PairHostLockError::Io(e)
        })
    }
    #[cfg(not(unix))]
    Ok(PairHostLock { _file: file })
}

/// What `croft pair` records for the workspace's resident navigator.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct PairRecord {
    /// Model handed to the claude CLI (None = its default).
    pub(crate) model: Option<String>,
    /// The caret name the navigator sits under.
    pub(crate) name: String,
    /// False = explicitly deactivated (`croft pair --off` / palette toggle).
    pub(crate) enabled: bool,
    /// Vestigial: older records may carry a start task, but resident seating
    /// never replays it (a persisted task would re-fire on every launch, and
    /// an @file task would freeze the UI thread on seat). Instructions come
    /// from Cmd+K Q; the --repl driver still takes a one-shot task directly.
    #[serde(default)]
    pub(crate) task: Option<String>,
    /// Which backend seats the pilot: None or "claude" = the claude CLI;
    /// "ollama" = a local Anthropic-compatible endpoint (absent on 0.1.635
    /// records, which are all claude).
    #[serde(default)]
    pub(crate) provider: Option<String>,
    /// The local endpoint, e.g. http://localhost:11434. Never a token — auth
    /// for keyed gateways stays in the environment (ANTHROPIC_AUTH_TOKEN).
    #[serde(default)]
    pub(crate) base_url: Option<String>,
}

pub(crate) fn write_pair_record(path: &Path, record: &PairRecord) -> Result<()> {
    let mut v = serde_json::to_value(record).context("serializing pair record")?;
    // Every write is observable: the App re-arms a downed navigator when
    // the record CHANGES, and an enabled→enabled rewrite (`croft pair`
    // after a failed seat) would otherwise be byte-identical — and mtime
    // alone misses a same-grain rewrite on coarse-timestamp filesystems.
    // The read path ignores the stamp (serde skips unknown fields).
    v["written_at_nanos"] = serde_json::Value::from(
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0),
    );
    // The clock alone cannot guarantee distinct bytes (SystemTime can
    // repeat for rapid writes under coarse granularity): pid + a
    // process-local counter differs on every call, in every process.
    static WRITE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    v["write_nonce"] = serde_json::Value::from(
        (u64::from(std::process::id()) << 32)
            | (WRITE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xffff_ffff),
    );
    std::fs::write(path, v.to_string()).with_context(|| format!("writing {}", path.display()))
}

pub(crate) fn read_pair_record(path: &Path) -> Option<PairRecord> {
    let json = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&json).ok()
}

/// Sidecar recorded next to a socket: the socket name is only a hash, so `ls`
/// reads this to show the real workspace path and the session's age.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct SessionMeta {
    pub(crate) workspace: PathBuf,
    pub(crate) created_unix: u64,
}

pub(crate) fn now_unix() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

pub(crate) fn write_meta(socket: &Path, meta: &SessionMeta) -> Result<()> {
    let json = serde_json::to_string(meta).context("serializing session meta")?;
    let path = meta_path(socket);
    std::fs::write(&path, json).with_context(|| format!("writing {}", path.display()))
}

pub(crate) fn read_meta(socket: &Path) -> Option<SessionMeta> {
    let json = std::fs::read_to_string(meta_path(socket)).ok()?;
    serde_json::from_str(&json).ok()
}

/// Remove a socket's meta sidecar (best effort). Called by the session host on
/// clean exit so a later server for the same workspace starts a fresh uptime.
pub(crate) fn remove_meta(socket: &Path) {
    let _ = std::fs::remove_file(meta_path(socket));
}

/// Record the workspace sidecar for a session socket, keeping the original
/// creation time across reattaches so `ls` uptime reflects the session's
/// real start. Used by the session host when it takes ownership of a socket.
pub(crate) fn write_meta_preserving_created(socket: &Path, workspace: &Path) -> Result<()> {
    let created_unix = read_meta(socket)
        .map(|m| m.created_unix)
        .unwrap_or_else(now_unix);
    write_meta(
        socket,
        &SessionMeta {
            workspace: workspace.to_path_buf(),
            created_unix,
        },
    )
}

/// A dtach server holds an open listening socket; a crashed server leaves a
/// stale socket file behind (unix sockets aren't auto-unlinked), so existence
/// isn't liveness — probe by connecting.
// ponytail: the connect registers as a fleeting client attach, costing the
// detached croft one WINCH repaint; fine for a handful of sessions, swap for an
// lsof/peer check if the session count ever grows large.
#[cfg(unix)]
pub(crate) fn is_alive(socket: &Path) -> bool {
    match std::os::unix::net::UnixStream::connect(socket) {
        Ok(_) => true,
        // "Nothing is listening" and "the probe itself could not run" are
        // different answers (#30): a box out of file descriptors must not
        // read as a dead session — a false "dead" sends ensure_relay /
        // attach_or_create down the spawn path against a live server.
        // Resource exhaustion reports alive (the conservative side: worst
        // case the caller attaches and gets a clean connect error), every
        // true refusal reports dead.
        Err(e) => matches!(
            e.raw_os_error(),
            Some(libc::EMFILE) | Some(libc::ENFILE) | Some(libc::EAGAIN) | Some(libc::ENOMEM)
        ),
    }
}

#[cfg(not(unix))]
pub(crate) fn is_alive(_socket: &Path) -> bool {
    false
}

/// Bind a unix listener at `socket`, owner-only (0600) with no window in
/// which anyone else could connect. Possession of the account is the trust
/// boundary for every croft socket (the session mux, the collab relay):
/// another user must never be able to connect. Shared by both binders so the
/// permission discipline lives in exactly one place.
pub fn bind_socket_0600(socket: &Path) -> std::io::Result<std::os::unix::net::UnixListener> {
    use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
    use std::os::unix::io::AsRawFd;
    // Creation is serialized per target through an owner-only lock file held
    // across the liveness probe, the stale-file removal, the bind and the
    // publication. Without it, two attach-or-create racers could both probe
    // "nobody alive", both publish, and the later publisher replaced the
    // earlier one's directory entry - a live but pathless listener, i.e. a
    // stranded session host invisible to every future client. The loser now
    // finds the winner alive under the lock and is told to attach instead
    // (`AddrInUse`). The flock releases on drop (or on crash, by the OS).
    // The socket's folder, owner-only, on a machine that has never had one
    // (#1368): without it the lock file cannot open, and a plain `croft .`
    // never serves its agent hook.
    if let Some(parent) = socket.parent().filter(|p| !p.as_os_str().is_empty()) {
        std::fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(parent)?;
    }
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .mode(0o600)
        .open(socket.with_extension("bind.lock"))?;
    if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    if is_alive(socket) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::AddrInUse,
            format!("a listener is already serving {}", socket.display()),
        ));
    }
    // Proven dead under the lock: a crashed owner's stale file (unix sockets
    // are not auto-unlinked) must not block the next creator.
    let _ = std::fs::remove_file(socket);
    // `bind` starts accepting connections the instant it returns, and the
    // socket file's mode comes from the process umask. A save/restore umask
    // dance around the bind is process-global state: two concurrent binds
    // interleaving their restores corrupted the mask for the rest of the
    // process's life, and one of the sockets got created under the loose
    // caller mask. Instead, bind inside a fresh 0700 staging dir next to
    // the target (same filesystem; the short `.s` name keeps the AF_UNIX
    // path-length budget), fix the socket's own mode to 0600 while nobody
    // can traverse to it, then rename(2) it into place atomically. No
    // process-global state anywhere.
    static STAGE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let n = STAGE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let parent = socket.parent().unwrap_or(Path::new("."));
    let stage = parent.join(format!(".s{}-{n}", std::process::id()));
    // A crash can strand a same-named staging dir (the counter restarts
    // with the process and pids recycle); it is ours by construction.
    let _ = std::fs::remove_dir_all(&stage);
    std::fs::DirBuilder::new().mode(0o700).create(&stage)?;
    let result = (|| {
        let tmp = stage.join("s");
        let listener = std::os::unix::net::UnixListener::bind(&tmp)?;
        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))?;
        std::fs::rename(&tmp, socket)?;
        Ok(listener)
    })();
    let _ = std::fs::remove_dir_all(&stage);
    result
}

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

    /// An enabled→enabled rewrite must NEVER serialize byte-identically:
    /// the App re-arms a downed navigator on record-content change, and the
    /// clock alone cannot carry that guarantee (SystemTime can repeat for
    /// rapid writes under coarse clock granularity). A per-write nonce
    /// (pid + process-local counter) differs even when the clock stands
    /// still.
    #[test]
    fn every_pair_record_write_serializes_differently() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pair.json");
        let record = PairRecord {
            model: None,
            name: String::from("nav"),
            enabled: true,
            task: None,
            provider: None,
            base_url: None,
        };
        write_pair_record(&path, &record).unwrap();
        let a = std::fs::read(&path).unwrap();
        write_pair_record(&path, &record).unwrap();
        let b = std::fs::read(&path).unwrap();
        assert_ne!(a, b, "identical records must still write distinct bytes");
        let va: serde_json::Value = serde_json::from_slice(&a).unwrap();
        let vb: serde_json::Value = serde_json::from_slice(&b).unwrap();
        assert!(
            va["write_nonce"].is_u64(),
            "the nonce is part of the record"
        );
        assert_ne!(
            va["write_nonce"], vb["write_nonce"],
            "the nonce differs even when the clock stands still"
        );
        // The stamp fields stay invisible to the typed read path.
        assert_eq!(read_pair_record(&path).as_ref(), Some(&record));
    }

    /// The `ls` filter accepts exactly what the session binders produce and
    /// none of the other per-workspace sockets.
    #[test]
    fn only_the_session_socket_names_count_as_sessions() {
        let ws = Path::new("/work/repo");
        let name = |p: PathBuf| p.file_name().unwrap().to_string_lossy().into_owned();
        assert!(is_session_socket(&name(mux_socket_path(ws))));
        assert!(is_session_socket(&name(socket_path(ws))));
        assert!(!is_session_socket(&name(collab_socket_path(ws))));
        assert!(!is_session_socket(&name(hook_socket_path(ws))));
        assert!(!is_session_socket(&name(crate::pane_host::socket_for(
            &crate::pane_host::new_pane_id()
        ))));
    }

    /// Two attach-or-create racers for the SAME target must never both
    /// publish: before creation was serialized, the later publisher replaced
    /// the earlier one's directory entry, leaving a live but pathless
    /// listener (a stranded session host, invisible to every future client).
    /// Exactly one racer may win; the loser is told the address is in use so
    /// it attaches to the winner instead.
    #[test]
    fn racing_binds_on_one_target_produce_exactly_one_listener() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("same.sock");
        let outcomes: Vec<std::io::Result<std::os::unix::net::UnixListener>> =
            std::thread::scope(|s| {
                let handles: Vec<_> = (0..2)
                    .map(|_| {
                        let sock = sock.clone();
                        s.spawn(move || bind_socket_0600(&sock))
                    })
                    .collect();
                handles.into_iter().map(|h| h.join().unwrap()).collect()
            });
        let winners = outcomes.iter().filter(|o| o.is_ok()).count();
        assert_eq!(
            winners, 1,
            "exactly one racer may publish a listener on one target"
        );
        for o in &outcomes {
            if let Err(e) = o {
                assert_eq!(
                    e.kind(),
                    std::io::ErrorKind::AddrInUse,
                    "the loser must be told to attach, got {e:?}"
                );
            }
        }
        // And the published listener is the live one: a client reaches it.
        let l = outcomes.into_iter().find_map(|o| o.ok()).unwrap();
        let _c = std::os::unix::net::UnixStream::connect(&sock)
            .expect("the surviving pathname must reach the winning listener");
        drop(l);
    }

    /// #1368: on a machine where croft never made its sessions folder, the
    /// first bind makes it, owner-only, instead of failing on the lock.
    #[test]
    fn a_socket_in_a_folder_that_does_not_exist_yet_binds() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let sessions = dir.path().join(".cache/croft/sessions");
        let sock = sessions.join("w.hook.sock");
        let _l = bind_socket_0600(&sock).expect("the folder is made, then bound");
        std::os::unix::net::UnixStream::connect(&sock).expect("the listener answers");
        let mode = std::fs::metadata(&sessions).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o700, "{mode:o}");
    }

    /// #1368, negative: a sessions folder that already exists is used as
    /// it is; making it is not a reason to change its mode.
    #[test]
    fn an_existing_socket_folder_is_left_as_it_is() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let sessions = dir.path().join("sessions");
        std::fs::create_dir(&sessions).unwrap();
        std::fs::set_permissions(&sessions, std::fs::Permissions::from_mode(0o750)).unwrap();
        let _l = bind_socket_0600(&sessions.join("w.sock")).unwrap();
        let mode = std::fs::metadata(&sessions).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o750, "{mode:o}");
    }

    /// A stale socket file (its owner crashed; nobody accepts) must not block
    /// the next creator: the binder proves it dead and replaces it.
    #[test]
    fn a_dead_stale_socket_file_is_replaced() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("stale.sock");
        drop(bind_socket_0600(&sock).expect("first bind"));
        assert!(sock.exists(), "a dropped listener leaves its file behind");
        let _l = bind_socket_0600(&sock).expect("a dead socket file must be replaced");
        std::os::unix::net::UnixStream::connect(&sock).expect("the new listener answers");
    }

    /// Every croft socket is owner-only from its first observable instant.
    #[test]
    fn a_bound_socket_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("a.sock");
        let _l = bind_socket_0600(&sock).expect("bind");
        let mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "socket must be 0600, got {mode:o}");
    }

    /// Binding must not go through process-global state: the parallel test
    /// suite (and any future in-process threading) binds relay and mux
    /// sockets from many threads at once. The old save/restore umask dance
    /// raced - two interleaved binds could restore each other's masks
    /// (permanently corrupting the process umask) and one socket could be
    /// created under the caller's loose umask for its whole life.
    #[test]
    fn concurrent_binds_never_corrupt_the_process_umask_or_a_socket() {
        use std::os::unix::fs::PermissionsExt;
        let read_umask = || unsafe {
            // Read is a write on this API; probe with the tightest value so
            // the blink can only ever make a concurrent file MORE private.
            let cur = libc::umask(0o077);
            libc::umask(cur);
            cur
        };
        let before = read_umask();
        let dir = tempfile::tempdir().unwrap();
        let worst = std::sync::Arc::new(std::sync::Mutex::new(0u32));
        std::thread::scope(|s| {
            for t in 0..2 {
                let dir = dir.path().to_path_buf();
                let worst = std::sync::Arc::clone(&worst);
                s.spawn(move || {
                    for i in 0..300 {
                        let sock = dir.join(format!("{t}-{i}.sock"));
                        let l = bind_socket_0600(&sock).expect("bind");
                        let mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777;
                        let mut w = worst.lock().unwrap();
                        if mode > *w {
                            *w = mode;
                        }
                        drop(l);
                        let _ = std::fs::remove_file(&sock);
                    }
                });
            }
        });
        assert_eq!(
            *worst.lock().unwrap(),
            0o600,
            "a racing bind produced a socket looser than 0600"
        );
        assert_eq!(
            read_umask(),
            before,
            "racing binds corrupted the process umask"
        );
    }

    /// The single-host lock is exclusive: a second acquirer is refused while
    /// the first holds it, and the lock frees when the holder drops (the OS
    /// releases it, which is how a crashed host hands off).
    #[test]
    fn pair_host_lock_is_exclusive_and_frees_on_drop() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("x.pair-host.lock");
        let first = try_acquire_pair_host_lock(&path).expect("first acquires");
        assert!(
            matches!(
                try_acquire_pair_host_lock(&path),
                Err(PairHostLockError::Busy)
            ),
            "a second croft must be refused as BUSY while the first holds the lock"
        );
        drop(first);
        assert!(
            try_acquire_pair_host_lock(&path).is_ok(),
            "the lock frees when the holder drops"
        );
    }

    /// A lock file croft cannot open is not another window holding it: the
    /// two failures were folded into one `None` and the caller reported a
    /// missing config directory as contention (#337).
    #[test]
    fn an_unopenable_lock_file_is_an_io_error_not_busy() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("no-such-dir").join("x.pair-host.lock");
        match try_acquire_pair_host_lock(&path) {
            Err(PairHostLockError::Io(e)) => {
                assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "{e}");
            }
            other => panic!("expected an io error, got {other:?}"),
        }
    }

    /// The navigator activation record: written by `croft pair`, read by a
    /// running croft; keyed like the other workspace sidecars; roundtrips.
    #[test]
    fn pair_record_roundtrips_and_shares_the_workspace_keying() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("x.pair.json");
        assert_eq!(read_pair_record(&path), None);
        let record = PairRecord {
            model: Some("claude-haiku-4-5-20251001".into()),
            name: "navigator".into(),
            enabled: true,
            task: Some("look around".into()),
            provider: None,
            base_url: None,
        };
        write_pair_record(&path, &record).unwrap();
        assert_eq!(read_pair_record(&path), Some(record));

        let keyed = pair_record_path(Path::new("/work/repo"));
        assert!(keyed.to_string_lossy().ends_with(".pair.json"));
        assert_eq!(
            keyed.parent(),
            collab_socket_path(Path::new("/work/repo")).parent()
        );
    }

    /// A record activated for a local provider keeps the provider and its
    /// endpoint across the write/read cycle.
    #[test]
    fn pair_record_roundtrips_local_provider() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("x.pair.json");
        let record = PairRecord {
            model: Some("qwen3-coder:30b".into()),
            name: "navigator".into(),
            enabled: true,
            task: None,
            provider: Some("ollama".into()),
            base_url: Some("http://localhost:11434".into()),
        };
        write_pair_record(&path, &record).unwrap();
        assert_eq!(read_pair_record(&path), Some(record));
    }

    /// A 0.1.635 record (no provider fields) still reads: absent fields mean
    /// the claude provider, exactly what those records were written for.
    #[test]
    fn legacy_record_without_provider_is_claude() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("x.pair.json");
        std::fs::write(
            &path,
            r#"{"model":null,"name":"claude","enabled":true,"task":null}"#,
        )
        .unwrap();
        let record = read_pair_record(&path).expect("legacy record reads");
        assert_eq!(record.provider, None);
        assert_eq!(record.base_url, None);
    }

    #[test]
    fn socket_path_is_stable_per_workspace_and_differs_across_paths() {
        let a1 = socket_path(Path::new("/work/repo"));
        let a2 = socket_path(Path::new("/work/repo"));
        let b = socket_path(Path::new("/work/other"));
        assert_eq!(a1, a2);
        assert_ne!(a1, b);
        assert!(a1.to_string_lossy().contains(".cache/croft/sessions"));
        assert_eq!(a1.extension().and_then(|e| e.to_str()), Some("sock"));
    }

    #[test]
    fn collab_socket_shares_keying_but_not_name_with_the_mux_socket() {
        let ws = Path::new("/work/repo");
        let collab = collab_socket_path(ws);
        assert_eq!(collab, collab_socket_path(ws), "keying must be stable");
        assert!(
            collab
                .to_string_lossy()
                .ends_with(&format!("{}.collab.sock", socket_name(ws)))
        );
        assert_ne!(collab, mux_socket_path(ws));
        assert_ne!(collab, socket_path(ws));
    }

    #[test]
    fn meta_round_trips_next_to_socket() {
        let dir = std::env::temp_dir().join(format!("croft-session-meta-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let socket = dir.join("deadbeef.sock");
        let meta = SessionMeta {
            workspace: PathBuf::from("/work/repo"),
            created_unix: 1_700_000_000,
        };
        write_meta(&socket, &meta).unwrap();
        assert_eq!(read_meta(&socket), Some(meta));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn reattach_preserves_original_created_unix() {
        let dir =
            std::env::temp_dir().join(format!("croft-session-reattach-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let socket = dir.join("cafef00d.sock");
        // First attach records creation time.
        write_meta(
            &socket,
            &SessionMeta {
                workspace: PathBuf::from("/work/repo"),
                created_unix: 1_700_000_000,
            },
        )
        .unwrap();
        // Reattach resolves creation time from the existing sidecar, not "now".
        let created = read_meta(&socket)
            .map(|m| m.created_unix)
            .unwrap_or_else(now_unix);
        assert_eq!(created, 1_700_000_000);
        // A fresh workspace with no sidecar falls back to now.
        let fresh = dir.join("00000000.sock");
        let created_fresh = read_meta(&fresh)
            .map(|m| m.created_unix)
            .unwrap_or_else(now_unix);
        assert!(created_fresh >= 1_700_000_000);
        let _ = std::fs::remove_dir_all(&dir);
    }
}