supercode-harness 0.5.1

The optional native Volter Harness agent and tool harness
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
//! Live Claude Code peer sessions: registry discovery and inbound policy.
//!
//! Claude Code is the one supported harness whose *running* interactive
//! sessions are addressable. Each live process registers
//! `~/.claude/sessions/<pid>.json` and binds the Unix socket named in it. The
//! catalog ([`supercode_interchange::catalog`]) is deliberately about persisted state only, so
//! nothing there may claim liveness; this module is the separate, explicitly
//! process-checking half; it feeds session activity and the mail router's
//! `native` door, which reach clients as a discovered descriptor's `activity`
//! and `delivery`.
//!
//! Two rules earn their place here:
//!
//! 1. **A registry file is not a live session.** These files survive a crash,
//!    so every read re-checks the recorded pid with `kill(pid, 0)` and drops
//!    the record when the process is gone.
//! 2. **Nothing here writes the socket.** The socket path is documented, but
//!    its wire frame is not, and a foreign process authenticating to it is not
//!    a supported case. Messages reach a live session through a Claude relay
//!    ([`crate::claude_relay`]), a headless Claude that sends with Claude's own
//!    `SendMessage`.

use std::path::{Path, PathBuf};
use std::{fs::OpenOptions, io::Write};

use serde::{Deserialize, Serialize};

use crate::HarnessHomes;

/// Activity a live Claude Code session reports for itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClaudePeerStatus {
    /// A turn is running.
    Busy,
    /// The turn ended; the session waits for its user's next prompt.
    Idle,
    /// A turn is blocked on its user: a permission prompt or a question.
    Waiting,
}

impl ClaudePeerStatus {
    /// Stable wire spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Busy => "busy",
            Self::Idle => "idle",
            Self::Waiting => "waiting",
        }
    }

    /// Interpret Claude Code's registry spelling without making discovery
    /// brittle to a newer status value. `shell` is published while Claude is
    /// executing a shell tool, so it is active work from a messenger's point
    /// of view just like `busy`.
    fn from_registry(value: &str) -> Option<Self> {
        match value {
            "busy" | "shell" => Some(Self::Busy),
            "idle" => Some(Self::Idle),
            "waiting" => Some(Self::Waiting),
            _ => None,
        }
    }
}

/// One live Claude Code session: a registry record whose pid answered
/// `kill(pid, 0)` during the read that produced this value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaudePeerSession {
    /// Process holding the session.
    pub pid: u32,
    /// Claude-native session id, joinable to a discovered transcript.
    pub session_id: String,
    /// Working directory the session was started in.
    pub cwd: Option<PathBuf>,
    /// Registry display name; this is also the cross-session address.
    pub name: String,
    /// Unix socket the session binds for peer messaging.
    pub socket_path: PathBuf,
    /// Reported activity. Absent on sessions that never published one.
    pub status: Option<ClaudePeerStatus>,
    /// Registry update time in epoch milliseconds, when recorded.
    pub updated_at_ms: Option<u64>,
    /// Claude Code version that wrote the record.
    pub version: Option<String>,
    /// The tmux session and pane it runs in (`<session>:@<window>.%<pane>`),
    /// when it runs in tmux.
    pub tmux: Option<String>,
}

/// Directory holding the live-session registry for the configured Claude home.
///
/// [`HarnessHomes::claude_code`] points at `<claude home>/projects`, so the
/// registry is that directory's sibling. Deriving it keeps one configuration
/// knob (`CLAUDE_CONFIG_DIR`, through [`HarnessHomes`]) rather than adding a
/// second that could disagree with it.
pub fn registry_dir(homes: &HarnessHomes) -> PathBuf {
    homes
        .claude_code
        .parent()
        .unwrap_or(Path::new("."))
        .join("sessions")
}

/// User-level policy Claude Code applies to messages from other sessions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClaudeCrossSessionInbound {
    /// Deliver messages without a separate inbound approval.
    Accept,
    /// Queue messages for an explicit approval.
    Hold,
    /// Drop messages without delivering them.
    Refuse,
}

impl ClaudeCrossSessionInbound {
    /// Stable Claude settings spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Accept => "accept",
            Self::Hold => "hold",
            Self::Refuse => "refuse",
        }
    }
}

/// The user-settings portion Supercode can inspect without pretending to know
/// a target process's complete managed/project/CLI precedence stack.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ClaudePeerSettings {
    /// Exact user settings file read or written.
    pub path: PathBuf,
    /// Hash of the exact native bytes observed. Configure calls may use this
    /// as an optimistic concurrency guard.
    pub revision: String,
    /// Explicit user value. `None` means Claude's permission-class default
    /// remains in effect and can hold a message.
    pub cross_session_inbound: Option<ClaudeCrossSessionInbound>,
}

impl ClaudePeerSettings {
    /// True only when this user setting explicitly opts into automatic
    /// delivery. A higher-precedence managed/project/CLI setting can still
    /// override it, so callers must label this as user-level evidence.
    pub fn user_allows_automatic_delivery(&self) -> bool {
        self.cross_session_inbound == Some(ClaudeCrossSessionInbound::Accept)
    }
}

/// Failure to read or safely update Claude Code's user settings.
#[derive(Debug, thiserror::Error)]
pub enum ClaudePeerSettingsError {
    /// Filesystem access failed.
    #[error("Claude Code settings I/O failed: {0}")]
    Io(#[from] std::io::Error),
    /// The existing settings file is not valid JSON.
    #[error("Claude Code settings JSON is invalid: {0}")]
    Json(#[from] serde_json::Error),
    /// The document shape or setting value is not one Supercode can preserve.
    #[error("{0}")]
    Invalid(String),
    /// Another process edited the file during Supercode's read-modify-write.
    #[error("Claude Code settings changed while Volter Harness was updating them; retry the explicit configuration action")]
    ChangedDuringWrite,
}

/// Claude Code's user settings file for the configured Claude home.
pub fn user_settings_path(homes: &HarnessHomes) -> PathBuf {
    homes
        .claude_code
        .parent()
        .unwrap_or(Path::new("."))
        .join("settings.json")
}

/// Inspect only the user-level inbound setting. The report deliberately does
/// not claim to be Claude's effective value because managed, project, and
/// command-line settings can have higher precedence in a particular target.
pub fn read_claude_peer_settings(
    homes: &HarnessHomes,
) -> Result<ClaudePeerSettings, ClaudePeerSettingsError> {
    let path = user_settings_path(homes);
    let bytes = match std::fs::read(&path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
        Err(error) => return Err(error.into()),
    };
    let value = if bytes.is_empty() {
        serde_json::Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_slice(&bytes)?
    };
    let object = value.as_object().ok_or_else(|| {
        ClaudePeerSettingsError::Invalid(format!(
            "Claude Code settings at {} must be a JSON object",
            path.display()
        ))
    })?;
    let cross_session_inbound = match object.get("crossSessionInbound") {
        None => None,
        Some(serde_json::Value::String(value)) if value == "accept" => {
            Some(ClaudeCrossSessionInbound::Accept)
        }
        Some(serde_json::Value::String(value)) if value == "hold" => {
            Some(ClaudeCrossSessionInbound::Hold)
        }
        Some(serde_json::Value::String(value)) if value == "refuse" => {
            Some(ClaudeCrossSessionInbound::Refuse)
        }
        Some(value) => {
            return Err(ClaudePeerSettingsError::Invalid(format!(
                "Claude Code setting `crossSessionInbound` at {} must be `accept`, `hold`, or `refuse`, not {value}",
                path.display()
            )))
        }
    };
    Ok(ClaudePeerSettings {
        path,
        revision: blake3::hash(&bytes).to_hex().to_string(),
        cross_session_inbound,
    })
}

/// Explicitly update Claude Code's user-level inbound policy while preserving
/// every unrelated setting. The write is atomic, refuses symlinks, and aborts
/// when it observes an edit between its initial read and commit.
pub fn write_claude_peer_settings(
    homes: &HarnessHomes,
    cross_session_inbound: ClaudeCrossSessionInbound,
) -> Result<ClaudePeerSettings, ClaudePeerSettingsError> {
    update_claude_peer_settings(homes, Some(cross_session_inbound), None)
}

/// Set or reset Claude Code's user-level inbound policy. `expected_revision`
/// prevents an explicit UI action from overwriting settings inspected before
/// another process changed the file.
pub fn update_claude_peer_settings(
    homes: &HarnessHomes,
    cross_session_inbound: Option<ClaudeCrossSessionInbound>,
    expected_revision: Option<&str>,
) -> Result<ClaudePeerSettings, ClaudePeerSettingsError> {
    let path = user_settings_path(homes);
    if std::fs::symlink_metadata(&path)
        .map(|metadata| metadata.file_type().is_symlink())
        .unwrap_or(false)
    {
        return Err(ClaudePeerSettingsError::Invalid(format!(
            "refusing to replace symlinked Claude Code settings at {}",
            path.display()
        )));
    }
    let original = match std::fs::read(&path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
        Err(error) => return Err(error.into()),
    };
    let original_revision = blake3::hash(&original).to_hex().to_string();
    if expected_revision.is_some_and(|expected| expected != original_revision) {
        return Err(ClaudePeerSettingsError::ChangedDuringWrite);
    }
    let mut value = if original.is_empty() {
        serde_json::Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_slice(&original)?
    };
    let object = value.as_object_mut().ok_or_else(|| {
        ClaudePeerSettingsError::Invalid(format!(
            "Claude Code settings at {} must be a JSON object",
            path.display()
        ))
    })?;
    let changed = match cross_session_inbound {
        Some(value) => {
            object.insert(
                "crossSessionInbound".into(),
                serde_json::Value::String(value.as_str().into()),
            ) != Some(serde_json::Value::String(value.as_str().into()))
        }
        None => object.remove("crossSessionInbound").is_some(),
    };
    if !changed {
        return read_claude_peer_settings(homes);
    }
    let mut encoded = serde_json::to_vec_pretty(&value)?;
    encoded.push(b'\n');

    let parent = path.parent().unwrap_or(Path::new("."));
    std::fs::create_dir_all(parent)?;
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let temporary = parent.join(format!(
        ".settings.json.supercode-{}-{nonce}.tmp",
        std::process::id()
    ));
    let write_result = (|| -> Result<(), ClaudePeerSettingsError> {
        let mut options = OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        let mut file = options.open(&temporary)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::{MetadataExt, PermissionsExt};
            let mode = std::fs::metadata(&path)
                .map(|metadata| metadata.mode() & 0o777)
                .unwrap_or(0o600);
            file.set_permissions(std::fs::Permissions::from_mode(mode))?;
        }
        file.write_all(&encoded)?;
        file.sync_all()?;
        let current = match std::fs::read(&path) {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
            Err(error) => return Err(error.into()),
        };
        if current != original {
            return Err(ClaudePeerSettingsError::ChangedDuringWrite);
        }
        std::fs::rename(&temporary, &path)?;
        Ok(())
    })();
    if write_result.is_err() {
        std::fs::remove_file(&temporary).ok();
    }
    write_result?;
    read_claude_peer_settings(homes)
}

#[derive(Deserialize)]
struct RegistryRecord {
    pid: u32,
    #[serde(rename = "sessionId")]
    session_id: String,
    #[serde(default)]
    cwd: Option<PathBuf>,
    #[serde(default)]
    name: Option<String>,
    #[serde(rename = "messagingSocketPath", default)]
    messaging_socket_path: Option<PathBuf>,
    #[serde(default)]
    // Keep the vendor-owned value as text here. Deserializing it directly as
    // our closed enum made one newly introduced status discard the ENTIRE
    // live peer record, including its safe endpoint and process evidence.
    status: Option<String>,
    #[serde(rename = "updatedAt", default)]
    updated_at: Option<u64>,
    #[serde(default)]
    version: Option<String>,
    #[serde(default)]
    tmux: Option<String>,
}

/// Read every LIVE session from a Claude registry directory.
///
/// Records are skipped, never fatal, when the file is malformed, when it names
/// no messaging socket, or when its pid is gone — a stale file left by a
/// crashed session is exactly the case that must not be reported as live.
pub fn read_registry(directory: &Path) -> Vec<ClaudePeerSession> {
    let Ok(entries) = std::fs::read_dir(directory) else {
        return Vec::new();
    };
    let mut sessions = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|value| value.to_str()) != Some("json") {
            continue;
        }
        let Ok(bytes) = std::fs::read(&path) else {
            continue;
        };
        let Ok(record) = serde_json::from_slice::<RegistryRecord>(&bytes) else {
            continue;
        };
        let (Some(name), Some(socket_path)) = (record.name, record.messaging_socket_path) else {
            continue;
        };
        if record.session_id.is_empty() || name.is_empty() || !process_is_live(record.pid) {
            continue;
        }
        sessions.push(ClaudePeerSession {
            pid: record.pid,
            session_id: record.session_id,
            cwd: record.cwd,
            name,
            socket_path,
            status: record
                .status
                .as_deref()
                .and_then(ClaudePeerStatus::from_registry),
            updated_at_ms: record.updated_at,
            version: record.version,
            tmux: record.tmux,
        });
    }
    sessions.sort_by_key(|session| session.pid);
    sessions
}

#[cfg(unix)]
pub(crate) fn process_is_live(pid: u32) -> bool {
    // SAFETY: signal 0 performs only a liveness/permission check.
    let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
    result == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

#[cfg(not(unix))]
pub(crate) fn process_is_live(pid: u32) -> bool {
    // Claude Code's peer messaging socket is a Unix socket; the registry is
    // not addressable on Windows in the first place.
    let _ = pid;
    false
}

/// Why a message could not be delivered into a live session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClaudePeerRefusal {
    /// No live process is running this session right now.
    NotLive,
    /// The registry name no longer resolves to the requested session.
    IdentityMismatch,
    /// The relay did not report the message as sent.
    DeliveryFailed,
}

impl ClaudePeerRefusal {
    /// Stable wire spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NotLive => "not_live",
            Self::IdentityMismatch => "identity_mismatch",
            Self::DeliveryFailed => "delivery_failed",
        }
    }
}

/// A refusal paired with the detail that names it.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{message}")]
pub struct ClaudePeerRefusalError {
    /// Machine-readable reason.
    pub reason: ClaudePeerRefusal,
    /// Human-readable detail.
    pub message: String,
}

impl ClaudePeerRefusalError {
    fn new(reason: ClaudePeerRefusal, message: impl Into<String>) -> Self {
        Self {
            reason,
            message: message.into(),
        }
    }
}

/// Resolve `session_id` to the live Claude session running it.
///
/// The registry is re-read here rather than trusted from a discovery result,
/// and the resolved name is checked back against the requested session id: a
/// name that has moved to another live session must refuse, not deliver a
/// message to the wrong reader.
pub fn resolve_live_session(
    homes: &HarnessHomes,
    session_id: &str,
) -> Result<ClaudePeerSession, ClaudePeerRefusalError> {
    let registry = read_registry(&registry_dir(homes));
    let target = registry
        .iter()
        .find(|session| session.session_id == session_id)
        .cloned()
        .ok_or_else(|| {
            ClaudePeerRefusalError::new(
                ClaudePeerRefusal::NotLive,
                format!(
                    "no live Claude Code process is running session `{session_id}`; \
                     its transcript is persisted only"
                ),
            )
        })?;
    let by_name = registry
        .iter()
        .filter(|session| session.name == target.name)
        .collect::<Vec<_>>();
    if by_name.len() != 1 || by_name[0].session_id != target.session_id {
        return Err(ClaudePeerRefusalError::new(
            ClaudePeerRefusal::IdentityMismatch,
            format!(
                "the registry name `{}` no longer resolves to session `{session_id}` alone; \
                 refusing rather than delivering into another session",
                target.name
            ),
        ));
    }

    Ok(target)
}

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

    fn temp_dir(label: &str) -> PathBuf {
        let path = std::env::temp_dir().join(format!(
            "supercode-claude-peer-{label}-{}-{:?}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&path).unwrap();
        path
    }

    /// A pid that is certainly gone: a process we started and reaped.
    fn dead_pid() -> u32 {
        let mut child = std::process::Command::new("/usr/bin/true")
            .spawn()
            .or_else(|_| std::process::Command::new("true").spawn())
            .unwrap();
        let pid = child.id();
        child.wait().unwrap();
        pid
    }

    fn write_record(directory: &Path, pid: u32, session_id: &str, name: &str, status: &str) {
        let status = if status.is_empty() {
            String::new()
        } else {
            format!(",\"status\":\"{status}\",\"updatedAt\":1786907689006")
        };
        std::fs::write(
            directory.join(format!("{pid}.json")),
            format!(
                "{{\"pid\":{pid},\"sessionId\":\"{session_id}\",\"cwd\":\"/tmp/project\",\
                 \"version\":\"2.1.224\",\"peerProtocol\":1,\"kind\":\"interactive\",\
                 \"entrypoint\":\"cli\",\"messagingSocketPath\":\"/tmp/cc-socks/{pid}.sock\",\
                 \"name\":\"{name}\",\"nameSource\":\"derived\"{status}}}"
            ),
        )
        .unwrap();
    }

    fn homes_for(root: &Path) -> HarnessHomes {
        HarnessHomes {
            claude_code: root.join("projects"),
            ..HarnessHomes::default()
        }
    }

    #[test]
    fn explicit_peer_policy_update_preserves_the_rest_of_claude_settings() {
        let root = temp_dir("settings");
        let settings_path = root.join("settings.json");
        std::fs::write(
            &settings_path,
            r#"{"permissions":{"allow":["Bash(git status)"]},"theme":"dark"}"#,
        )
        .unwrap();

        let homes = homes_for(&root);
        let before = read_claude_peer_settings(&homes).unwrap();
        let updated = update_claude_peer_settings(
            &homes,
            Some(ClaudeCrossSessionInbound::Accept),
            Some(&before.revision),
        )
        .unwrap();
        assert_eq!(
            updated.cross_session_inbound,
            Some(ClaudeCrossSessionInbound::Accept)
        );
        let document: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&settings_path).unwrap()).unwrap();
        assert_eq!(document["theme"], "dark");
        assert_eq!(document["permissions"]["allow"][0], "Bash(git status)");
        assert_eq!(document["crossSessionInbound"], "accept");

        let stale = update_claude_peer_settings(
            &homes,
            Some(ClaudeCrossSessionInbound::Hold),
            Some(&before.revision),
        )
        .unwrap_err();
        assert!(matches!(stale, ClaudePeerSettingsError::ChangedDuringWrite));

        let reset = update_claude_peer_settings(&homes, None, Some(&updated.revision)).unwrap();
        assert_eq!(reset.cross_session_inbound, None);
        let reset_document: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&settings_path).unwrap()).unwrap();
        assert_eq!(reset_document["theme"], "dark");
        assert!(reset_document.get("crossSessionInbound").is_none());
        std::fs::remove_dir_all(root).ok();
    }

    #[cfg(unix)]
    #[test]
    fn explicit_peer_policy_update_refuses_a_symlinked_settings_file() {
        use std::os::unix::fs::symlink;

        let root = temp_dir("settings-symlink");
        let outside = root.join("outside.json");
        std::fs::write(&outside, "{}\n").unwrap();
        symlink(&outside, root.join("settings.json")).unwrap();

        let error =
            write_claude_peer_settings(&homes_for(&root), ClaudeCrossSessionInbound::Accept)
                .unwrap_err();
        assert!(matches!(error, ClaudePeerSettingsError::Invalid(_)));
        assert_eq!(std::fs::read_to_string(outside).unwrap(), "{}\n");
        std::fs::remove_dir_all(root).ok();
    }

    #[test]
    fn registry_reports_live_records_and_drops_stale_ones() {
        let root = temp_dir("registry");
        let sessions = root.join("sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        let live = std::process::id();
        let dead = dead_pid();
        write_record(&sessions, live, "live-session", "peer-live", "busy");
        write_record(&sessions, dead, "dead-session", "peer-dead", "idle");
        // A record from a version that publishes no socket is not addressable.
        std::fs::write(
            sessions.join("777.json"),
            format!("{{\"pid\":{live},\"sessionId\":\"no-socket\",\"name\":\"peer-x\"}}"),
        )
        .unwrap();
        std::fs::write(sessions.join("bad.json"), "{not json").unwrap();

        let found = read_registry(&sessions);
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].session_id, "live-session");
        assert_eq!(found[0].name, "peer-live");
        assert_eq!(found[0].status, Some(ClaudePeerStatus::Busy));
        assert_eq!(
            found[0].socket_path,
            PathBuf::from(format!("/tmp/cc-socks/{live}.sock"))
        );
        assert_eq!(registry_dir(&homes_for(&root)), sessions);
        std::fs::remove_dir_all(root).ok();
    }

    #[test]
    fn registry_keeps_live_peers_during_shell_tools_and_unknown_vendor_states() {
        let root = temp_dir("registry-statuses");
        let sessions = root.join("sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        let live = std::process::id();
        write_record(&sessions, live, "shell-session", "peer-shell", "shell");
        let future = std::fs::read_to_string(sessions.join(format!("{live}.json")))
            .unwrap()
            .replace("shell-session", "future-session")
            .replace("peer-shell", "peer-future")
            .replace("\"status\":\"shell\"", "\"status\":\"future-status\"");
        std::fs::write(sessions.join("future.json"), future).unwrap();

        let found = read_registry(&sessions);
        assert_eq!(found.len(), 2, "a vendor status must not erase a live peer");
        let shell = found
            .iter()
            .find(|peer| peer.session_id == "shell-session")
            .unwrap();
        let future = found
            .iter()
            .find(|peer| peer.session_id == "future-session")
            .unwrap();
        assert_eq!(shell.status, Some(ClaudePeerStatus::Busy));
        assert_eq!(future.status, None);
        std::fs::remove_dir_all(root).ok();
    }

    #[test]
    fn a_persisted_only_session_refuses_with_not_live() {
        let root = temp_dir("not-live");
        std::fs::create_dir_all(root.join("sessions")).unwrap();
        write_record(
            &root.join("sessions"),
            dead_pid(),
            "gone-session",
            "peer-gone",
            "idle",
        );
        let refusal = resolve_live_session(&homes_for(&root), "gone-session").unwrap_err();
        assert_eq!(refusal.reason, ClaudePeerRefusal::NotLive);
        std::fs::remove_dir_all(root).ok();
    }

    #[test]
    fn a_name_shared_by_two_live_sessions_refuses_instead_of_guessing() {
        let root = temp_dir("mismatch");
        let sessions = root.join("sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        let live = std::process::id();
        write_record(&sessions, live, "wanted-session", "peer-shared", "idle");
        // Same derived name, different session: delivering here would put the
        // message in front of the wrong reader.
        std::fs::write(
            sessions.join(format!("{}.json", live + 1)),
            format!(
                "{{\"pid\":{live},\"sessionId\":\"other-session\",\
                 \"messagingSocketPath\":\"/tmp/cc-socks/{live}.sock\",\"name\":\"peer-shared\"}}"
            ),
        )
        .unwrap();

        let refusal = resolve_live_session(&homes_for(&root), "wanted-session").unwrap_err();
        assert_eq!(refusal.reason, ClaudePeerRefusal::IdentityMismatch);
        assert!(refusal.message.contains("peer-shared"));
        std::fs::remove_dir_all(root).ok();
    }
}