whetstone-cli 3.19.0

Installer and CLI for Claude Code token optimization (Headroom + RTK + Memory)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! Per-config Headroom proxy registry: fingerprint the exact proxy config a
//! session would spawn, so two sessions share a proxy iff they would spawn a
//! byte-identical one. Keyed reuse via `~/.whetstone/proxies.json`.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

/// Everything that varies a spawned Headroom proxy's behavior. Two specs with
/// the same fingerprint may share one proxy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProxySpec {
    /// Resolved `HEADROOM_SAVINGS_PROFILE`.
    pub savings_profile: String,
    /// Whether telemetry is enabled (drives `--no-telemetry` / env).
    pub telemetry: bool,
    /// Whether the proxy is started with `--memory`.
    pub memory: bool,
    /// Resolved `ANTHROPIC_TARGET_API_URL`, if any.
    pub anthropic_api_url: Option<String>,
    /// The `HEADROOM_*` apply set, EXCLUDING `HEADROOM_MEMORY_DB_PATH`.
    pub env: BTreeMap<String, String>,
    /// SSH destination when the proxy runs on another machine; `None` = local.
    pub remote: Option<String>,
}

fn canonical(spec: &ProxySpec) -> String {
    let mut s = String::new();
    s.push_str("sp=");
    s.push_str(&spec.savings_profile);
    s.push('\n');
    s.push_str("tel=");
    s.push(if spec.telemetry { '1' } else { '0' });
    s.push('\n');
    s.push_str("mem=");
    s.push(if spec.memory { '1' } else { '0' });
    s.push('\n');
    s.push_str("url=");
    s.push_str(spec.anthropic_api_url.as_deref().unwrap_or(""));
    s.push('\n');
    for (k, v) in &spec.env {
        s.push_str("e:");
        s.push_str(k);
        s.push('=');
        s.push_str(v);
        s.push('\n');
    }
    // Only rendered when set, so local fingerprints predate this field.
    if let Some(remote) = &spec.remote {
        s.push_str("remote=");
        s.push_str(remote);
        s.push('\n');
    }
    s
}

fn fnv1a(bytes: &[u8]) -> u64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for b in bytes {
        hash ^= u64::from(*b);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash
}

/// FNV-1a 64-bit over a canonical rendering of the spec.
pub fn proxy_fingerprint(spec: &ProxySpec) -> String {
    format!("{:016x}", fnv1a(canonical(spec).as_bytes()))
}

const GLOBAL_DIR: &str = ".whetstone";
const REGISTRY_FILENAME: &str = "proxies.json";

/// One whetstone-spawned proxy: its config fingerprint, bound port, and pid.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProxyEntry {
    pub fingerprint: String,
    pub port: u16,
    /// The `headroom proxy` pid, or the `ssh` tunnel pid for a remote proxy.
    pub pid: u32,
    /// SSH destination the tunnel on `port` leads to; `None` = local proxy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote: Option<String>,
    /// Pids of the sessions launched onto this proxy. A session `exec`s, so
    /// its pid lives exactly as long as it does.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sessions: Vec<u32>,
    /// Unix seconds of the last launch that used this proxy. `0` marks an
    /// entry written before sessions were tracked; those are never idle-reaped
    /// because a live session may be using one unrecorded.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub last_used: u64,
}

fn is_zero(n: &u64) -> bool {
    *n == 0
}

/// Is `pid` still the kind of process we started? Pids are reused (always
/// after a reboot, which the registry file survives), so a recorded pid alone
/// is not proof.
fn pid_runs(pid: u32, needle: &str) -> bool {
    std::process::Command::new("ps")
        .args(["-p", &pid.to_string(), "-o", "args="])
        .output()
        .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(needle))
}

/// Stop the process behind a registry entry — the `headroom proxy`, or the
/// `ssh` tunnel for a remote one — but only if the pid still is that.
pub fn kill_entry(entry: &ProxyEntry) {
    let needle = if entry.remote.is_some() {
        "ssh"
    } else {
        "headroom"
    };
    if pid_runs(entry.pid, needle) {
        let _ = std::process::Command::new("kill")
            .arg(entry.pid.to_string())
            .stderr(std::process::Stdio::null())
            .status();
    }
}

/// The set of live whetstone-spawned proxies. Persisted to
/// `~/.whetstone/proxies.json`.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Registry {
    #[serde(default)]
    pub entries: Vec<ProxyEntry>,
}

/// `~/.whetstone/proxies.json`, or `None` if the home dir can't be found.
pub fn registry_path() -> Option<PathBuf> {
    dirs::home_dir().map(|h| h.join(GLOBAL_DIR).join(REGISTRY_FILENAME))
}

impl Registry {
    /// Load the registry, treating a missing or corrupt file as empty — a
    /// stale registry must never block a launch.
    pub fn load(path: &Path) -> Self {
        let Ok(raw) = std::fs::read_to_string(path) else {
            return Self::default();
        };
        serde_json::from_str(&raw).unwrap_or_default()
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating {}", parent.display()))?;
        }
        let pretty = serde_json::to_string_pretty(self)
            .context("serializing proxy registry")?;
        crate::config::write_atomic(path, &pretty)
    }

    pub fn find(&self, fingerprint: &str) -> Option<&ProxyEntry> {
        self.entries.iter().find(|e| e.fingerprint == fingerprint)
    }
}

/// Registry lock guard: an OS file lock, released when this drops — or when
/// the holder dies, so a crash can never leave a stale lock behind.
pub struct LockGuard {
    _file: std::fs::File,
}

/// Acquire the registry lock, waiting until it's free or `timeout` elapses.
pub fn acquire_lock(path: &Path, timeout: Duration) -> Result<LockGuard> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    let file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(path)
        .with_context(|| format!("opening lock {}", path.display()))?;
    let deadline = Instant::now() + timeout;
    loop {
        if file.try_lock().is_ok() {
            return Ok(LockGuard { _file: file });
        }
        if Instant::now() >= deadline {
            anyhow::bail!(
                "timed out acquiring proxy registry lock at {}",
                path.display()
            );
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// Backward-compat anchor port. Assigned best-effort to the first proxy
/// whetstone spawns so a bare `claude` launch and doctor's fast-path still
/// find a proxy at `127.0.0.1:8787`.
pub const ANCHOR_PORT: u16 = 8787;

/// Pick a port for a new proxy: the anchor when it's free and unclaimed,
/// otherwise a fresh OS-assigned free port.
pub fn choose_port(
    reg: &Registry,
    port_free: impl Fn(u16) -> bool,
    free_port: impl Fn() -> Option<u16>,
) -> Option<u16> {
    let anchor_claimed = reg.entries.iter().any(|e| e.port == ANCHOR_PORT);
    if !anchor_claimed && port_free(ANCHOR_PORT) {
        return Some(ANCHOR_PORT);
    }
    free_port()
}

/// The result of resolving a launch to a proxy port.
#[derive(Debug, PartialEq, Eq)]
pub enum ProxyOutcome {
    /// An already-running proxy matched the fingerprint.
    Reused(u16),
    /// A fresh proxy was spawned on this port.
    Spawned(u16),
    /// No proxy could be brought up; caller should soft-fall-back.
    Failed,
}

/// Injected side effects so `resolve` is unit-testable without a real proxy.
pub struct ResolveDeps<'a> {
    /// Does a proxy answer `/health` on this port?
    pub probe: &'a dyn Fn(u16) -> bool,
    /// Can we bind this port right now?
    pub port_free: &'a dyn Fn(u16) -> bool,
    /// Ask the OS for an unused port.
    pub free_port: &'a dyn Fn() -> Option<u16>,
    /// Spawn a proxy for the current spec on this port; return its pid when it
    /// comes up ready, else `None`.
    pub spawn: &'a dyn Fn(u16) -> Option<u32>,
    /// Is this session pid still running?
    pub alive: &'a dyn Fn(u32) -> bool,
    /// Stop the process behind an entry that is being dropped.
    pub reap: &'a dyn Fn(&ProxyEntry),
    /// Unix seconds now.
    pub now: u64,
    /// Pid of the session being launched.
    pub session: u32,
}

/// How long a proxy with no live session is kept for the next launch.
const IDLE_SECS: u64 = 10 * 60;

/// Prune dead entries, reuse a live matching proxy, or spawn a new one.
/// Mutates `reg`; the caller persists it under the lock.
pub fn resolve(
    reg: &mut Registry,
    spec: &ProxySpec,
    deps: &ResolveDeps,
) -> ProxyOutcome {
    let fingerprint = proxy_fingerprint(spec);
    let matched_port = reg.find(&fingerprint).map(|e| e.port);

    // Keep an entry only while it answers (two tries: a live-but-busy proxy
    // must not be dropped) and someone could still want it. Whatever is
    // dropped is stopped too, so proxies don't pile up for the life of the
    // machine — one per config ever tried.
    for mut entry in std::mem::take(&mut reg.entries) {
        entry.sessions.retain(|pid| (deps.alive)(*pid));
        let healthy = (deps.probe)(entry.port) || (deps.probe)(entry.port);
        // The anchor also serves clients no session pid stands for: a bare
        // `claude` or an editor following the shell profile's
        // ANTHROPIC_BASE_URL. It is never idle.
        let idle = Some(entry.port) != matched_port
            && entry.port != ANCHOR_PORT
            && entry.last_used != 0
            && entry.sessions.is_empty()
            && deps.now.saturating_sub(entry.last_used) > IDLE_SECS;
        if healthy && !idle {
            reg.entries.push(entry);
        } else {
            (deps.reap)(&entry);
        }
    }

    if let Some(entry) = reg
        .entries
        .iter_mut()
        .find(|e| e.fingerprint == fingerprint)
    {
        entry.sessions.push(deps.session);
        // An entry from before session tracking stays unstamped: sessions
        // started by the old binary are still on it, unrecorded.
        if entry.last_used != 0 {
            entry.last_used = deps.now;
        }
        return ProxyOutcome::Reused(entry.port);
    }

    let Some(port) = choose_port(reg, deps.port_free, deps.free_port) else {
        return ProxyOutcome::Failed;
    };
    match (deps.spawn)(port) {
        Some(pid) => {
            reg.entries.push(ProxyEntry {
                fingerprint,
                port,
                pid,
                remote: spec.remote.clone(),
                sessions: vec![deps.session],
                last_used: deps.now,
            });
            ProxyOutcome::Spawned(port)
        }
        None => ProxyOutcome::Failed,
    }
}

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

    #[test]
    fn load_missing_file_is_empty() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("proxies.json");
        let reg = Registry::load(&path);
        assert!(reg.entries.is_empty());
    }

    #[test]
    fn save_then_load_roundtrips() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("proxies.json");
        let reg = Registry {
            entries: vec![ProxyEntry {
                fingerprint: "abc123".into(),
                port: 8801,
                pid: 4242,
                remote: None,
                sessions: vec![],
                last_used: 0,
            }],
        };
        reg.save(&path).unwrap();
        let back = Registry::load(&path);
        assert_eq!(back.entries, reg.entries);
        assert_eq!(back.find("abc123").map(|e| e.port), Some(8801));
        assert!(back.find("nope").is_none());
    }

    #[test]
    fn load_corrupt_file_is_empty() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("proxies.json");
        std::fs::write(&path, "not json").unwrap();
        assert!(Registry::load(&path).entries.is_empty());
    }

    fn base() -> ProxySpec {
        ProxySpec {
            savings_profile: "agent-90".into(),
            telemetry: false,
            memory: false,
            anthropic_api_url: None,
            env: BTreeMap::new(),
            remote: None,
        }
    }

    #[test]
    fn local_fingerprint_is_unchanged_by_the_remote_field() {
        // Pinned: live local proxies registered before `remote` existed must
        // still match after an upgrade.
        assert_eq!(canonical(&base()), "sp=agent-90\ntel=0\nmem=0\nurl=\n");
    }

    #[test]
    fn remote_changes_the_fingerprint() {
        let remote = ProxySpec {
            remote: Some("me@box".into()),
            ..base()
        };
        let other = ProxySpec {
            remote: Some("me@other".into()),
            ..base()
        };
        assert_ne!(proxy_fingerprint(&base()), proxy_fingerprint(&remote));
        assert_ne!(proxy_fingerprint(&remote), proxy_fingerprint(&other));
    }

    #[test]
    fn registry_written_before_remote_existed_still_loads() {
        let reg: Registry = serde_json::from_str(
            r#"{"entries":[{"fingerprint":"a","port":8787,"pid":1}]}"#,
        )
        .unwrap();
        assert_eq!(reg.entries[0].remote, None);
    }

    #[test]
    fn fingerprint_is_stable_and_16_hex() {
        let fp = proxy_fingerprint(&base());
        assert_eq!(fp.len(), 16);
        assert!(fp.chars().all(|c| c.is_ascii_hexdigit()));
        assert_eq!(fp, proxy_fingerprint(&base()));
    }

    #[test]
    fn fingerprint_is_order_independent_for_env() {
        let mut a = base();
        a.env.insert("HEADROOM_RPM".into(), "1".into());
        a.env
            .insert("HEADROOM_CODE_AWARE_ENABLED".into(), "1".into());
        // BTreeMap canonicalizes order; inserting in the other order matches.
        let mut b = base();
        b.env
            .insert("HEADROOM_CODE_AWARE_ENABLED".into(), "1".into());
        b.env.insert("HEADROOM_RPM".into(), "1".into());
        assert_eq!(proxy_fingerprint(&a), proxy_fingerprint(&b));
    }

    #[test]
    fn each_field_changes_the_fingerprint() {
        let f0 = proxy_fingerprint(&base());

        let mut sp = base();
        sp.savings_profile = "agent-50".into();
        assert_ne!(f0, proxy_fingerprint(&sp));

        let mut tel = base();
        tel.telemetry = true;
        assert_ne!(f0, proxy_fingerprint(&tel));

        let mut mem = base();
        mem.memory = true;
        assert_ne!(f0, proxy_fingerprint(&mem));

        let mut url = base();
        url.anthropic_api_url = Some("https://example.test".into());
        assert_ne!(f0, proxy_fingerprint(&url));

        let mut env = base();
        env.env.insert("HEADROOM_RPM".into(), "120".into());
        assert_ne!(f0, proxy_fingerprint(&env));
    }

    #[test]
    fn lock_is_exclusive_then_released_on_drop() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("proxies.lock");
        let short = std::time::Duration::from_millis(200);

        let g = acquire_lock(&lock, short).unwrap();
        // Second acquisition times out while the first is held.
        assert!(acquire_lock(&lock, short).is_err());
        drop(g);
        // After release, it succeeds again.
        assert!(acquire_lock(&lock, short).is_ok());
    }

    #[test]
    fn leftover_lock_file_does_not_block() {
        // A crashed holder leaves the file but not the OS lock.
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("proxies.lock");
        std::fs::write(&lock, "12345").unwrap();
        assert!(
            acquire_lock(&lock, std::time::Duration::from_millis(200)).is_ok()
        );
    }

    fn entry(fp: &str, port: u16) -> ProxyEntry {
        ProxyEntry {
            fingerprint: fp.into(),
            port,
            pid: 1,
            remote: None,
            sessions: vec![],
            last_used: 0,
        }
    }

    #[test]
    fn choose_port_prefers_anchor_when_free_and_unclaimed() {
        let reg = Registry::default();
        let port = choose_port(&reg, |_| true, || Some(9001));
        assert_eq!(port, Some(ANCHOR_PORT));
    }

    #[test]
    fn choose_port_skips_anchor_when_claimed_by_a_live_entry() {
        let reg = Registry {
            entries: vec![entry("x", ANCHOR_PORT)],
        };
        let port = choose_port(&reg, |_| true, || Some(9002));
        assert_eq!(port, Some(9002));
    }

    #[test]
    fn choose_port_skips_anchor_when_port_busy() {
        let reg = Registry::default();
        // Anchor reported busy by the OS even though no entry claims it.
        let port = choose_port(&reg, |p| p != ANCHOR_PORT, || Some(9003));
        assert_eq!(port, Some(9003));
    }

    const NOW: u64 = 1_000_000;

    fn deps_from<'a>(
        probe: &'a dyn Fn(u16) -> bool,
        port_free: &'a dyn Fn(u16) -> bool,
        free_port: &'a dyn Fn() -> Option<u16>,
        spawn: &'a dyn Fn(u16) -> Option<u32>,
    ) -> ResolveDeps<'a> {
        ResolveDeps {
            probe,
            port_free,
            free_port,
            spawn,
            alive: &|_| true,
            reap: &|_| {},
            now: NOW,
            session: 4242,
        }
    }

    #[test]
    fn resolve_reuses_a_live_matching_proxy() {
        let spec = base();
        let fp = proxy_fingerprint(&spec);
        let mut reg = Registry {
            entries: vec![ProxyEntry {
                fingerprint: fp,
                port: 8801,
                pid: 7,
                remote: None,
                sessions: vec![],
                last_used: 0,
            }],
        };

        let probe = |_p: u16| true; // 8801 answers
        let port_free = |_p: u16| true;
        let free_port = || Some(9100u16);
        let spawn =
            |_p: u16| -> Option<u32> { panic!("must not spawn on reuse") };
        let deps = deps_from(&probe, &port_free, &free_port, &spawn);

        let outcome = resolve(&mut reg, &spec, &deps);
        assert_eq!(outcome, ProxyOutcome::Reused(8801));
        assert_eq!(reg.entries.len(), 1);
    }

    #[test]
    fn resolve_reuses_transiently_busy_matching_proxy() {
        let spec = base();
        let fp = proxy_fingerprint(&spec);
        let mut reg = Registry {
            entries: vec![ProxyEntry {
                fingerprint: fp,
                port: 8801,
                pid: 7,
                remote: None,
                sessions: vec![],
                last_used: 0,
            }],
        };

        // First probe of the matching port says dead; second says alive.
        // Must still be reused, not pruned + duplicate-spawned.
        let call_count = std::cell::Cell::new(0u32);
        let probe = |_p: u16| {
            let n = call_count.get();
            call_count.set(n + 1);
            n >= 1 // false on the first call, true from then on
        };
        let port_free = |_p: u16| true;
        let free_port = || Some(9100u16);
        let spawn = |_p: u16| -> Option<u32> {
            panic!("must not spawn a duplicate for a transiently-busy match")
        };
        let deps = deps_from(&probe, &port_free, &free_port, &spawn);

        let outcome = resolve(&mut reg, &spec, &deps);
        assert_eq!(outcome, ProxyOutcome::Reused(8801));
        assert_eq!(reg.entries.len(), 1);
        assert_eq!(call_count.get(), 2);
    }

    #[test]
    fn resolve_prunes_dead_entry_and_spawns() {
        let spec = base();
        let fp = proxy_fingerprint(&spec);
        let mut reg = Registry {
            entries: vec![ProxyEntry {
                fingerprint: fp.clone(),
                port: 8801,
                pid: 7,
                remote: None,
                sessions: vec![],
                last_used: 0,
            }],
        };

        let probe = |_p: u16| false; // nothing answers → 8801 is dead
        let port_free = |_p: u16| true;
        let free_port = || Some(9100u16);
        let spawned: std::cell::Cell<Option<u16>> = std::cell::Cell::new(None);
        let spawn = |p: u16| -> Option<u32> {
            spawned.set(Some(p));
            Some(555)
        };
        let deps = deps_from(&probe, &port_free, &free_port, &spawn);

        let outcome = resolve(&mut reg, &spec, &deps);
        // Dead 8801 pruned; anchor free & unclaimed → spawns on 8787.
        assert_eq!(outcome, ProxyOutcome::Spawned(ANCHOR_PORT));
        assert_eq!(spawned.get(), Some(ANCHOR_PORT));
        assert_eq!(
            reg.find(&fp).map(|e| (e.port, e.pid)),
            Some((ANCHOR_PORT, 555))
        );
    }

    #[test]
    fn resolve_spawns_new_port_when_anchor_taken() {
        let spec = base();
        let fp = proxy_fingerprint(&spec);
        // A different fingerprint holds a live anchor.
        let mut reg = Registry {
            entries: vec![ProxyEntry {
                fingerprint: "other".into(),
                port: ANCHOR_PORT,
                pid: 1,
                remote: None,
                sessions: vec![],
                last_used: 0,
            }],
        };

        let probe = |_p: u16| true; // anchor's holder is alive
        let port_free = |_p: u16| true;
        let free_port = || Some(9100u16);
        let spawn = |_p: u16| -> Option<u32> { Some(556) };
        let deps = deps_from(&probe, &port_free, &free_port, &spawn);

        let outcome = resolve(&mut reg, &spec, &deps);
        assert_eq!(outcome, ProxyOutcome::Spawned(9100));
        assert_eq!(reg.find(&fp).map(|e| e.port), Some(9100));
    }

    #[test]
    fn resolve_reports_failed_when_spawn_fails() {
        let spec = base();
        let mut reg = Registry::default();
        let probe = |_p: u16| false;
        let port_free = |_p: u16| true;
        let free_port = || Some(9100u16);
        let spawn = |_p: u16| -> Option<u32> { None };
        let deps = deps_from(&probe, &port_free, &free_port, &spawn);

        assert_eq!(resolve(&mut reg, &spec, &deps), ProxyOutcome::Failed);
        assert!(reg.find(&proxy_fingerprint(&spec)).is_none());
    }

    /// A healthy proxy for some other config.
    fn other(sessions: Vec<u32>, last_used: u64) -> Registry {
        Registry {
            entries: vec![ProxyEntry {
                fingerprint: "other".into(),
                port: 9001,
                pid: 77,
                remote: None,
                sessions,
                last_used,
            }],
        }
    }

    /// Resolve a launch for `base()`; returns the pids that were reaped.
    fn resolve_reaping(
        reg: &mut Registry,
        alive: &dyn Fn(u32) -> bool,
    ) -> Vec<u32> {
        let reaped = std::cell::RefCell::new(Vec::new());
        let reap = |e: &ProxyEntry| reaped.borrow_mut().push(e.pid);
        let deps = ResolveDeps {
            probe: &|_| true,
            port_free: &|_| true,
            free_port: &|| Some(9100),
            spawn: &|_| Some(556),
            alive,
            reap: &reap,
            now: NOW,
            session: 4242,
        };
        resolve(reg, &base(), &deps);
        reaped.into_inner()
    }

    #[test]
    fn idle_proxy_with_no_live_session_is_reaped() {
        let mut reg = other(vec![5], NOW - IDLE_SECS - 1);
        assert_eq!(resolve_reaping(&mut reg, &|_| false), vec![77]);
        assert!(reg.find("other").is_none());
    }

    #[test]
    fn proxy_with_a_live_session_is_kept_however_old() {
        let mut reg = other(vec![5], 1);
        assert!(resolve_reaping(&mut reg, &|_| true).is_empty());
        assert_eq!(
            reg.find("other").map(|e| e.sessions.clone()),
            Some(vec![5])
        );
    }

    #[test]
    fn recently_used_proxy_is_kept_for_the_next_launch() {
        let mut reg = other(vec![5], NOW - 60);
        assert!(resolve_reaping(&mut reg, &|_| false).is_empty());
        // The dead session is forgotten even though the proxy stays.
        assert_eq!(reg.find("other").map(|e| e.sessions.len()), Some(0));
    }

    #[test]
    fn entry_from_before_session_tracking_is_never_idle_reaped() {
        let mut reg = other(vec![], 0);
        assert!(resolve_reaping(&mut reg, &|_| false).is_empty());
    }

    #[test]
    fn anchor_proxy_is_never_idle_reaped() {
        let mut reg = other(vec![], 1);
        reg.entries[0].port = ANCHOR_PORT;
        assert!(resolve_reaping(&mut reg, &|_| false).is_empty());
    }

    #[test]
    fn reusing_a_pre_tracking_entry_keeps_it_exempt() {
        let mut reg = other(vec![], 0);
        reg.entries[0].fingerprint = proxy_fingerprint(&base());
        resolve_reaping(&mut reg, &|_| true);
        assert_eq!(reg.entries[0].last_used, 0);
    }

    #[test]
    fn dead_proxy_is_reaped_not_just_forgotten() {
        let mut reg = other(vec![5], NOW);
        let reaped = std::cell::RefCell::new(Vec::new());
        let reap = |e: &ProxyEntry| reaped.borrow_mut().push(e.pid);
        let deps = ResolveDeps {
            probe: &|p| p != 9001,
            port_free: &|_| true,
            free_port: &|| Some(9100),
            spawn: &|_| Some(556),
            alive: &|_| true,
            reap: &reap,
            now: NOW,
            session: 4242,
        };
        resolve(&mut reg, &base(), &deps);
        assert_eq!(reaped.into_inner(), vec![77]);
    }

    #[test]
    fn launch_records_its_session_on_the_proxy_it_uses() {
        let mut reg = Registry::default();
        resolve_reaping(&mut reg, &|_| true);
        let entry = reg.find(&proxy_fingerprint(&base())).unwrap();
        assert_eq!(
            (entry.sessions.clone(), entry.last_used),
            (vec![4242], NOW)
        );
    }

    #[test]
    fn kill_entry_leaves_a_reused_pid_alone() {
        // Our own pid is alive but is neither headroom nor ssh: the check
        // must refuse, or this test process would die.
        assert!(!pid_runs(std::process::id(), "headroom proxy"));
        assert!(pid_runs(std::process::id(), "whetstone"));
    }
}