Skip to main content

micromux_control/
select.rs

1//! Session selection from live control endpoints.
2
3use std::path::{Path, PathBuf};
4
5use schemars::JsonSchema;
6use serde::Serialize;
7
8use crate::{
9    CanonicalConfigPath, ControlEndpoint, ControlError, EndpointProbe, EndpointProbeResult,
10    PROTOCOL_VERSION, ProtocolVersion, RuntimeDirStatus, SessionInfo, endpoint_for,
11    endpoint_from_hash, endpoint_hash, probe_endpoints, probe_runtime_dirs, runtime_dir_statuses,
12    unique_answering_session_probes, usable_runtime_dirs,
13};
14
15/// A session selector accepted by the control-plane resolver.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum SessionSelector {
18    /// Resolve the config selected by the current directory or an explicit config override.
19    Current,
20    /// Match the session's configured display name.
21    Name(String),
22    /// Match the session process id.
23    Pid(u32),
24    /// Match the deterministic endpoint hash for a config path.
25    ConfigHash(String),
26}
27
28impl SessionSelector {
29    /// Parse selector syntax without rejecting malformed prefixed values.
30    ///
31    /// Invalid prefixed forms such as `pid:x` remain usable as literal session names.
32    #[must_use]
33    pub fn parse(raw: &str) -> Self {
34        let raw = raw.trim();
35        if raw.is_empty() || raw.eq_ignore_ascii_case("current") {
36            Self::Current
37        } else if let Some(pid) = raw.strip_prefix("pid:") {
38            pid.trim()
39                .parse()
40                .map_or_else(|_| Self::Name(raw.to_string()), Self::Pid)
41        } else if let Some(hash) = raw.strip_prefix("hash:") {
42            Self::ConfigHash(hash.trim().to_string())
43        } else if let Some(name) = raw.strip_prefix("name:") {
44            Self::Name(name.trim().to_string())
45        } else {
46            Self::Name(raw.to_string())
47        }
48    }
49}
50
51/// Usability details for one candidate runtime directory.
52#[derive(Debug, Clone, Serialize, JsonSchema)]
53pub struct RuntimeDirDetail {
54    /// Runtime directory path.
55    pub path: String,
56    /// Whether the directory can host or discover control endpoints.
57    pub usable: bool,
58    /// Why the directory is unusable.
59    pub error: Option<String>,
60}
61
62/// Probe details for one derived or discovered control endpoint.
63#[derive(Debug, Clone, Serialize, JsonSchema)]
64pub struct SocketProbeDetail {
65    /// Display form of the endpoint.
66    pub endpoint: String,
67    /// Probe classification.
68    pub status: SocketProbeStatus,
69    /// Transport or compatibility detail.
70    pub message: Option<String>,
71    /// Protocol version advertised by the session, when one was decoded.
72    pub peer_protocol_version: Option<ProtocolVersion>,
73    /// Protocol version spoken by this client.
74    pub client_protocol_version: Option<ProtocolVersion>,
75    /// Live session identity when the endpoint answered successfully.
76    pub session: Option<SessionInfo>,
77}
78
79/// Result class for a control endpoint probe.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
81#[serde(rename_all = "snake_case")]
82pub enum SocketProbeStatus {
83    /// The endpoint answered with a compatible session description.
84    Session,
85    /// Nothing live answered at the endpoint.
86    Absent,
87    /// The endpoint answered with an incompatible protocol version.
88    ProtocolMismatch,
89    /// Something was listening but could not answer a usable request.
90    Unreachable,
91}
92
93/// Most probes that found nothing live which diagnostics list one by one; the rest are counted.
94pub const LISTED_ABSENT_PROBES: usize = 3;
95
96/// Probe diagnostics that stay bounded however many dead endpoints a scan finds.
97///
98/// Probes that found a session, an incompatible protocol, or an unusable endpoint are all listed,
99/// since a caller can act on each.
100/// Probes that found nothing live are summarized as a count with a few examples.
101#[derive(Debug, Clone, Default)]
102pub struct SocketProbeDetails {
103    /// Every probe that found something listening, then the first [`LISTED_ABSENT_PROBES`] that
104    /// found nothing live, in probe order.
105    pub socket_probes: Vec<SocketProbeDetail>,
106    /// How many probes found nothing live, including those listed in `socket_probes`.
107    pub absent_probe_count: usize,
108}
109
110impl SocketProbeDetails {
111    /// Converts probes into bounded diagnostics, keeping their order within each group.
112    #[must_use]
113    pub fn from_probes(probes: impl IntoIterator<Item = EndpointProbe>) -> Self {
114        let mut socket_probes = Vec::new();
115        let mut absent_examples = Vec::new();
116        let mut absent_probe_count = 0;
117        for probe in probes {
118            if matches!(probe.result, EndpointProbeResult::Absent(_)) {
119                absent_probe_count += 1;
120                if absent_examples.len() < LISTED_ABSENT_PROBES {
121                    absent_examples.push(probe_detail(probe));
122                }
123            } else {
124                socket_probes.push(probe_detail(probe));
125            }
126        }
127        socket_probes.extend(absent_examples);
128        Self {
129            socket_probes,
130            absent_probe_count,
131        }
132    }
133}
134
135/// Structured transport facts collected while resolving a selector.
136#[derive(Debug, Clone)]
137pub struct ProbeReport {
138    /// Human summary of the failed resolution.
139    pub summary: String,
140    /// Canonical config path when resolution reached one.
141    pub config_path: Option<String>,
142    /// Candidate runtime directories.
143    pub runtime_dirs: Vec<RuntimeDirDetail>,
144    /// Every probe that found something listening, then a few that found nothing live (see
145    /// [`SocketProbeDetails`]).
146    pub socket_probes: Vec<SocketProbeDetail>,
147    /// How many probes found nothing live, including those listed in `socket_probes`.
148    pub absent_probe_count: usize,
149}
150
151/// A live session selected together with the endpoint that drives it.
152pub struct ResolvedSession {
153    /// The control endpoint to connect to.
154    pub endpoint: ControlEndpoint,
155    /// Live session identity returned by the endpoint.
156    pub info: SessionInfo,
157}
158
159/// Details for a selector that matched more than one live session.
160#[derive(Debug)]
161pub struct AmbiguousSelection {
162    /// Human-readable explanation and disambiguation hint.
163    pub message: String,
164    /// The live candidates, used by interactive clients to print concrete selectors.
165    pub candidates: Vec<SessionInfo>,
166}
167
168/// Failures produced while selecting a live session.
169#[derive(Debug, thiserror::Error)]
170pub enum SelectError {
171    /// No live session matched.
172    #[error("no session: {}", .0.summary)]
173    NoSession(Box<ProbeReport>),
174    /// More than one live session matched.
175    #[error("ambiguous selector: {}", .0.message)]
176    Ambiguous(Box<AmbiguousSelection>),
177    /// A possibly matching endpoint existed but was unusable.
178    #[error("session busy: {0}")]
179    Busy(String),
180    /// The control transport is unavailable on this platform.
181    #[error("the micromux control plane is not supported on this platform")]
182    Unsupported,
183    /// Endpoint discovery or probing failed.
184    #[error(transparent)]
185    Control(ControlError),
186}
187
188impl From<ControlError> for SelectError {
189    fn from(error: ControlError) -> Self {
190        match error {
191            ControlError::Unsupported => Self::Unsupported,
192            ControlError::Timeout => {
193                Self::Busy("the micromux session did not answer in time".to_string())
194            }
195            other => Self::Control(other),
196        }
197    }
198}
199
200/// Resolve a selector to exactly one live session across all usable runtime directories.
201///
202/// `None` selects [`SessionSelector::Current`]. A config override participates only in current
203/// selection; explicit name, pid, and hash selectors ignore it.
204///
205/// # Errors
206///
207/// Returns [`SelectError::NoSession`] when nothing answers, [`SelectError::Ambiguous`] when more
208/// than one session matches, or [`SelectError::Unsupported`] without a control transport.
209pub async fn resolve_selector(
210    cwd: &Path,
211    selector: Option<SessionSelector>,
212    config_override: Option<&Path>,
213) -> Result<ResolvedSession, SelectError> {
214    if !crate::transport_supported() {
215        return Err(SelectError::Unsupported);
216    }
217    resolve_selector_with_statuses(&runtime_dir_statuses(), cwd, selector, config_override).await
218}
219
220/// Resolve a selector across the usable directories among `dir_statuses`.
221///
222/// It is [`resolve_selector`] for a client that chooses its own runtime directories, such as a
223/// test that runs its sessions in a private one.
224///
225/// # Errors
226///
227/// Returns the same errors as [`resolve_selector`].
228pub async fn resolve_selector_with_statuses(
229    dir_statuses: &[RuntimeDirStatus],
230    cwd: &Path,
231    selector: Option<SessionSelector>,
232    config_override: Option<&Path>,
233) -> Result<ResolvedSession, SelectError> {
234    if !crate::transport_supported() {
235        return Err(SelectError::Unsupported);
236    }
237    let runtime_dirs = usable_runtime_dirs(dir_statuses);
238    if runtime_dirs.is_empty() {
239        return Err(SelectError::NoSession(Box::new(probe_report(
240            "no runtime directory could be resolved".to_string(),
241            None,
242            dir_statuses,
243            SocketProbeDetails::default(),
244        ))));
245    }
246    resolve_selector_in_runtime_dirs(&runtime_dirs, dir_statuses, cwd, selector, config_override)
247        .await
248}
249
250/// Resolve a selector against caller-supplied runtime directories.
251///
252/// This lower-level form supports clients that have already prepared or constrained discovery.
253///
254/// # Errors
255///
256/// Returns the same errors as [`resolve_selector`].
257pub async fn resolve_selector_in_runtime_dirs(
258    runtime_dirs: &[PathBuf],
259    dir_statuses: &[RuntimeDirStatus],
260    cwd: &Path,
261    selector: Option<SessionSelector>,
262    config_override: Option<&Path>,
263) -> Result<ResolvedSession, SelectError> {
264    match selector.unwrap_or(SessionSelector::Current) {
265        SessionSelector::Current => {
266            resolve_current(runtime_dirs, dir_statuses, cwd, config_override).await
267        }
268        SessionSelector::ConfigHash(hash) => resolve_hash(runtime_dirs, dir_statuses, &hash).await,
269        SessionSelector::Name(name) => resolve_name(runtime_dirs, dir_statuses, &name).await,
270        SessionSelector::Pid(pid) => resolve_pid(runtime_dirs, dir_statuses, pid).await,
271    }
272}
273
274async fn verify_any(
275    endpoints: Vec<ControlEndpoint>,
276    describe: &str,
277    absent: impl Fn(SocketProbeDetails) -> ProbeReport,
278) -> Result<ResolvedSession, SelectError> {
279    let probes = probe_endpoints(&endpoints).await;
280    let matches = unique_answering_session_probes(&probes)
281        .into_iter()
282        .map(|(endpoint, info)| ResolvedSession { endpoint, info })
283        .collect::<Vec<_>>();
284    classify_probe_matches(
285        matches,
286        probes,
287        describe,
288        "use pid: or name: to disambiguate",
289        "endpoint(s)",
290        absent,
291    )
292}
293
294async fn resolve_current(
295    runtime_dirs: &[PathBuf],
296    dir_statuses: &[RuntimeDirStatus],
297    cwd: &Path,
298    config_override: Option<&Path>,
299) -> Result<ResolvedSession, SelectError> {
300    let target = config_override.unwrap_or(cwd);
301    let config_path = config_for_target(target).await.ok_or_else(|| {
302        SelectError::NoSession(Box::new(probe_report(
303            if config_override.is_some() {
304                format!("no micromux config found at or above {}", target.display())
305            } else {
306                "no micromux config found from the current directory".to_string()
307            },
308            None,
309            dir_statuses,
310            SocketProbeDetails::default(),
311        )))
312    })?;
313    let endpoints = runtime_dirs
314        .iter()
315        .map(|runtime_dir| endpoint_for(runtime_dir, &config_path))
316        .collect();
317    match verify_any(endpoints, "the current config", |socket_probes| {
318        let dir = config_path.parent().unwrap_or(config_path.as_path());
319        probe_report(
320            format!(
321                "no running micromux session for {}; start one with the start_session tool, or run `micromux` in {}",
322                config_path.display(),
323                dir.display(),
324            ),
325            Some(&config_path),
326            dir_statuses,
327            socket_probes,
328        )
329    })
330    .await
331    {
332        Ok(resolved) => Ok(resolved),
333        Err(error @ SelectError::Busy(_)) => {
334            match resolve_current_config_by_scanning(runtime_dirs, &config_path).await? {
335                Some(resolved) => Ok(resolved),
336                None => Err(error),
337            }
338        }
339        Err(error @ SelectError::NoSession(_)) => {
340            let scanned = if config_override.is_some() {
341                resolve_current_config_by_scanning(runtime_dirs, &config_path).await?
342            } else {
343                resolve_current_project_by_scanning(runtime_dirs, cwd, &config_path).await?
344            };
345            match scanned {
346                Some(resolved) => Ok(resolved),
347                None => Err(error),
348            }
349        }
350        Err(error) => Err(error),
351    }
352}
353
354async fn resolve_current_config_by_scanning(
355    runtime_dirs: &[PathBuf],
356    config_path: &CanonicalConfigPath,
357) -> Result<Option<ResolvedSession>, SelectError> {
358    let probes = probe_runtime_dirs(runtime_dirs).await?;
359    resolve_current_config_matches(&probes, config_path)
360}
361
362async fn resolve_current_project_by_scanning(
363    runtime_dirs: &[PathBuf],
364    cwd: &Path,
365    config_path: &CanonicalConfigPath,
366) -> Result<Option<ResolvedSession>, SelectError> {
367    let probes = probe_runtime_dirs(runtime_dirs).await?;
368    if let Some(resolved) = resolve_current_config_matches(&probes, config_path)? {
369        return Ok(Some(resolved));
370    }
371    let project_matches =
372        current_scan_matches(&probes, |info| session_config_path_is_under(info, cwd));
373    resolve_unique_current_scan_matches(project_matches, "a config under the current directory")
374}
375
376fn resolve_current_config_matches(
377    probes: &[EndpointProbe],
378    config_path: &CanonicalConfigPath,
379) -> Result<Option<ResolvedSession>, SelectError> {
380    let config_matches = current_scan_matches(probes, |info| {
381        session_matches_config_path(info, config_path)
382    });
383    resolve_unique_current_scan_matches(config_matches, "the current config")
384}
385
386fn current_scan_matches(
387    probes: &[EndpointProbe],
388    matches_session: impl Fn(&SessionInfo) -> bool,
389) -> Vec<ResolvedSession> {
390    unique_answering_session_probes(probes)
391        .into_iter()
392        .filter(|(_endpoint, info)| matches_session(info))
393        .map(|(endpoint, info)| ResolvedSession { endpoint, info })
394        .collect()
395}
396
397fn resolve_unique_current_scan_matches(
398    matches: Vec<ResolvedSession>,
399    describe: &str,
400) -> Result<Option<ResolvedSession>, SelectError> {
401    if matches.len() > 1 {
402        return Err(ambiguous_selection(
403            format!(
404                "{describe} matched {} live sessions; use pid: or name: to disambiguate",
405                matches.len()
406            ),
407            &matches,
408        ));
409    }
410    Ok(matches.into_iter().next())
411}
412
413/// Return whether a session's identity hash matches a canonical config path.
414#[must_use]
415pub fn session_matches_config_path(info: &SessionInfo, config_path: &CanonicalConfigPath) -> bool {
416    info.id == endpoint_hash(config_path)
417}
418
419/// Return whether a session's canonical config path is inside a directory.
420///
421/// Deliberately takes a raw [`Path`], not [`CanonicalConfigPath`]: `directory` is an arbitrary
422/// user directory (not a config file), and the session side must keep best-effort fallback
423/// semantics when its advertised config file no longer exists on disk.
424#[must_use]
425pub fn session_config_path_is_under(info: &SessionInfo, directory: &Path) -> bool {
426    if info.config_path.is_empty() {
427        return false;
428    }
429    let session_config_path = canonicalize_for_match(Path::new(&info.config_path));
430    let directory = canonicalize_for_match(directory);
431    session_config_path.starts_with(&directory)
432}
433
434fn canonicalize_for_match(path: &Path) -> PathBuf {
435    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
436}
437
438async fn resolve_hash(
439    runtime_dirs: &[PathBuf],
440    dir_statuses: &[RuntimeDirStatus],
441    hash: &str,
442) -> Result<ResolvedSession, SelectError> {
443    // Any other value names no session's socket, and may even point outside the runtime
444    // directories, so nothing is probed for it.
445    if !crate::endpoint::is_endpoint_hash(hash) {
446        return Err(SelectError::NoSession(Box::new(probe_report(
447            format!("no session with hash {hash}"),
448            None,
449            dir_statuses,
450            SocketProbeDetails::default(),
451        ))));
452    }
453    let endpoints = runtime_dirs
454        .iter()
455        .map(|runtime_dir| endpoint_from_hash(runtime_dir, hash))
456        .collect();
457    let describe = format!("hash {hash}");
458    verify_any(endpoints, &describe, |socket_probes| {
459        probe_report(
460            format!("no session with hash {hash}"),
461            None,
462            dir_statuses,
463            socket_probes,
464        )
465    })
466    .await
467}
468
469async fn resolve_name(
470    runtime_dirs: &[PathBuf],
471    dir_statuses: &[RuntimeDirStatus],
472    name: &str,
473) -> Result<ResolvedSession, SelectError> {
474    resolve_scanned_selector(
475        runtime_dirs,
476        dir_statuses,
477        &format!("name `{name}`"),
478        "use pid: or hash: to disambiguate",
479        // The routing name is what services see as `MICROMUX_SESSION`, so it selects too.
480        |info| {
481            info.name == name
482                || info
483                    .session
484                    .as_ref()
485                    .is_some_and(|session| session.name == name)
486        },
487    )
488    .await
489}
490
491async fn resolve_pid(
492    runtime_dirs: &[PathBuf],
493    dir_statuses: &[RuntimeDirStatus],
494    pid: u32,
495) -> Result<ResolvedSession, SelectError> {
496    resolve_scanned_selector(
497        runtime_dirs,
498        dir_statuses,
499        &format!("pid {pid}"),
500        "use hash: to disambiguate",
501        |info| info.pid == pid,
502    )
503    .await
504}
505
506async fn resolve_scanned_selector(
507    runtime_dirs: &[PathBuf],
508    dir_statuses: &[RuntimeDirStatus],
509    describe: &str,
510    disambiguate_hint: &str,
511    matches_session: impl Fn(&SessionInfo) -> bool,
512) -> Result<ResolvedSession, SelectError> {
513    let probes = probe_runtime_dirs(runtime_dirs).await?;
514    let matches = unique_answering_session_probes(&probes)
515        .into_iter()
516        .filter(|(_endpoint, info)| matches_session(info))
517        .map(|(endpoint, info)| ResolvedSession { endpoint, info })
518        .collect();
519    classify_probe_matches(
520        matches,
521        probes,
522        describe,
523        disambiguate_hint,
524        "session(s)",
525        |socket_probes| {
526            probe_report(
527                format!("no session matched {describe}"),
528                None,
529                dir_statuses,
530                socket_probes,
531            )
532        },
533    )
534}
535
536fn classify_probe_matches(
537    matches: Vec<ResolvedSession>,
538    probes: Vec<EndpointProbe>,
539    describe: &str,
540    disambiguate_hint: &str,
541    busy_unit: &str,
542    report: impl FnOnce(SocketProbeDetails) -> ProbeReport,
543) -> Result<ResolvedSession, SelectError> {
544    if matches.len() > 1 {
545        return Err(ambiguous_selection(
546            format!(
547                "{describe} matched {} live sessions; {disambiguate_hint}",
548                matches.len()
549            ),
550            &matches,
551        ));
552    }
553    if let Some(resolved) = matches.into_iter().next() {
554        return Ok(resolved);
555    }
556    let unusable = unusable_messages(&probes);
557    if !unusable.is_empty() {
558        return Err(SelectError::Busy(format!(
559            "no answering session matched {describe}; {} live {busy_unit} were reachable but unusable and may be the target: {}",
560            unusable.len(),
561            unusable.join("; ")
562        )));
563    }
564    Err(SelectError::NoSession(Box::new(report(
565        SocketProbeDetails::from_probes(probes),
566    ))))
567}
568
569fn ambiguous_selection(message: String, matches: &[ResolvedSession]) -> SelectError {
570    SelectError::Ambiguous(Box::new(AmbiguousSelection {
571        message,
572        candidates: matches
573            .iter()
574            .map(|resolved| resolved.info.clone())
575            .collect(),
576    }))
577}
578
579/// Convert an endpoint probe into its transport-level diagnostic representation.
580#[must_use]
581pub fn probe_detail(probe: EndpointProbe) -> SocketProbeDetail {
582    match probe.result {
583        EndpointProbeResult::Session(info) => SocketProbeDetail {
584            endpoint: probe.endpoint.to_string(),
585            status: SocketProbeStatus::Session,
586            message: None,
587            peer_protocol_version: Some(info.protocol_version),
588            client_protocol_version: Some(PROTOCOL_VERSION),
589            session: Some(*info),
590        },
591        EndpointProbeResult::Absent(reason) => SocketProbeDetail {
592            endpoint: probe.endpoint.to_string(),
593            status: SocketProbeStatus::Absent,
594            message: Some(reason),
595            peer_protocol_version: None,
596            client_protocol_version: Some(PROTOCOL_VERSION),
597            session: None,
598        },
599        EndpointProbeResult::ProtocolMismatch { peer, ours } => SocketProbeDetail {
600            endpoint: probe.endpoint.to_string(),
601            status: SocketProbeStatus::ProtocolMismatch,
602            message: Some(format!(
603                "control protocol version mismatch: peer={peer}, ours={ours}"
604            )),
605            peer_protocol_version: Some(peer),
606            client_protocol_version: Some(ours),
607            session: None,
608        },
609        EndpointProbeResult::Unreachable(reason) => SocketProbeDetail {
610            endpoint: probe.endpoint.to_string(),
611            status: SocketProbeStatus::Unreachable,
612            message: Some(reason),
613            peer_protocol_version: None,
614            client_protocol_version: Some(PROTOCOL_VERSION),
615            session: None,
616        },
617    }
618}
619
620fn unusable_messages(probes: &[EndpointProbe]) -> Vec<String> {
621    probes
622        .iter()
623        .filter_map(|probe| match &probe.result {
624            EndpointProbeResult::ProtocolMismatch { peer, ours } => Some(format!(
625                "{} -> protocol mismatch: peer={peer}, ours={ours}",
626                probe.endpoint
627            )),
628            EndpointProbeResult::Unreachable(reason) => {
629                Some(format!("{} -> {reason}", probe.endpoint))
630            }
631            EndpointProbeResult::Session(_) | EndpointProbeResult::Absent(_) => None,
632        })
633        .collect()
634}
635
636fn probe_report(
637    summary: String,
638    config_path: Option<&Path>,
639    dir_statuses: &[RuntimeDirStatus],
640    probes: SocketProbeDetails,
641) -> ProbeReport {
642    let SocketProbeDetails {
643        socket_probes,
644        absent_probe_count,
645    } = probes;
646    ProbeReport {
647        summary,
648        config_path: config_path.map(|path| path.display().to_string()),
649        runtime_dirs: dir_statuses
650            .iter()
651            .map(|status| RuntimeDirDetail {
652                path: status.path.display().to_string(),
653                usable: status.usable,
654                error: status.error.clone(),
655            })
656            .collect(),
657        socket_probes,
658        absent_probe_count,
659    }
660}
661
662/// Resolve a config target: use a file directly or search upward from a directory.
663#[must_use]
664pub async fn config_for_target(path: &Path) -> Option<CanonicalConfigPath> {
665    if tokio::fs::metadata(path)
666        .await
667        .is_ok_and(|metadata| metadata.is_file())
668    {
669        return tokio::fs::canonicalize(path)
670            .await
671            .ok()
672            .map(CanonicalConfigPath::from_canonicalized);
673    }
674    find_config_upward(path).await
675}
676
677/// Walk upward from `start` (stopping after the home directory), returning the first
678/// canonicalized micromux config path found.
679///
680/// Hand-rolled instead of delegating to `micromux::find_config_file`: that function's future
681/// captures a path-joining closure, which the rmcp `#[tool]` macro's higher-ranked `'static`
682/// bound rejects in the MCP tool futures that await this resolver — this future must stay
683/// closure-free.
684async fn find_config_upward(start: &Path) -> Option<CanonicalConfigPath> {
685    let home = directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf());
686    find_config_upward_with_home(start, home.as_deref()).await
687}
688
689async fn find_config_upward_with_home(
690    start: &Path,
691    home: Option<&Path>,
692) -> Option<CanonicalConfigPath> {
693    let mut directory = start.to_path_buf();
694    loop {
695        for name in micromux::config_file_names() {
696            let candidate = directory.join(name);
697            if let Ok(canonical) = tokio::fs::canonicalize(&candidate).await {
698                return Some(CanonicalConfigPath::from_canonicalized(canonical));
699            }
700        }
701        if home.is_some_and(|home| directory == home) {
702            return None;
703        }
704        match directory.parent() {
705            Some(parent) => directory = parent.to_path_buf(),
706            None => return None,
707        }
708    }
709}
710
711#[cfg(all(test, unix))]
712mod tests {
713    use std::sync::Arc;
714
715    use micromux::CancellationToken;
716    use similar_asserts::assert_eq;
717
718    use super::*;
719    use crate::{ControlServer, SessionIdentity, bind};
720    use color_eyre::eyre;
721
722    struct Running {
723        shutdown: CancellationToken,
724        _runner: tokio::task::JoinHandle<Result<(), micromux::Error>>,
725    }
726
727    fn boot(
728        runtime_dir: &Path,
729        working_dir: &Path,
730        config_path: &CanonicalConfigPath,
731    ) -> eyre::Result<Running> {
732        let yaml = "version: 1\nservices:\n  svc:\n    command: [\"sh\", \"-c\", \"sleep 60\"]\n";
733        let mut diagnostics = Vec::new();
734        let config = micromux::from_str(yaml, working_dir, 0usize, None, &mut diagnostics)
735            .map_err(|error| eyre::eyre!("parse: {error}"))?;
736        let mux = Arc::new(
737            micromux::Micromux::new(&config)?.with_cache_directory(runtime_dir.join("cache")),
738        );
739        let shutdown = CancellationToken::new();
740        let (runner, handles) = mux.clone().start(shutdown.clone());
741        let runner = tokio::spawn(runner);
742        let endpoint = endpoint_for(runtime_dir, config_path);
743        let guard = bind(&endpoint)?.ok_or_else(|| eyre::eyre!("bind failed"))?;
744        let identity = SessionIdentity::new("selected".to_string(), working_dir, config_path);
745        let server = Arc::new(ControlServer::new(
746            handles.reader.clone(),
747            handles.service_control(),
748            identity,
749            handles.dynamic_services.clone(),
750        ));
751        tokio::spawn({
752            let shutdown = shutdown.clone();
753            async move {
754                let _ = server.serve(guard, shutdown).await;
755            }
756        });
757        Ok(Running {
758            shutdown,
759            _runner: runner,
760        })
761    }
762
763    #[tokio::test]
764    async fn upward_config_search_stops_after_checking_home() -> eyre::Result<()> {
765        let root = tempfile::Builder::new()
766            .prefix("micromux-control-home-boundary-")
767            .tempdir()?;
768        let home = root.path().join("home/me");
769        let project = home.join("repo/subdir");
770        std::fs::create_dir_all(&project)?;
771        std::fs::write(
772            root.path().join("micromux.yaml"),
773            "version: 1\nservices: {}\n",
774        )?;
775
776        let found = find_config_upward_with_home(&project, Some(&home)).await;
777
778        assert_eq!(found, None);
779        Ok(())
780    }
781
782    #[tokio::test]
783    async fn upward_config_search_outside_home_still_walks_to_root() -> eyre::Result<()> {
784        let root = tempfile::Builder::new()
785            .prefix("micromux-control-outside-home-")
786            .tempdir()?;
787        let project = root.path().join("tmp/project");
788        std::fs::create_dir_all(&project)?;
789        let config = root.path().join("micromux.yaml");
790        std::fs::write(&config, "version: 1\nservices: {}\n")?;
791
792        let found = find_config_upward_with_home(&project, Some(Path::new("/home/me"))).await;
793
794        assert_eq!(
795            found.as_deref(),
796            Some(std::fs::canonicalize(config)?.as_path())
797        );
798        Ok(())
799    }
800
801    /// Absent probes collapse into a count with a few examples, however many there are, while
802    /// every probe that found something listening stays listed.
803    #[test]
804    fn probe_details_list_every_listener_and_sample_absent_probes() {
805        let endpoint =
806            |index: usize| ControlEndpoint::Unix(PathBuf::from(format!("/{index}.sock")));
807        let mut probes = (0..50)
808            .map(|index| EndpointProbe {
809                endpoint: endpoint(index),
810                result: EndpointProbeResult::Absent("connect: refused".to_string()),
811            })
812            .collect::<Vec<_>>();
813        probes.push(EndpointProbe {
814            endpoint: endpoint(50),
815            result: EndpointProbeResult::Unreachable("probe timed out".to_string()),
816        });
817        probes.push(EndpointProbe {
818            endpoint: endpoint(51),
819            result: EndpointProbeResult::ProtocolMismatch {
820                peer: ProtocolVersion::new(PROTOCOL_VERSION.major() + 1, 0),
821                ours: PROTOCOL_VERSION,
822            },
823        });
824
825        let details = SocketProbeDetails::from_probes(probes);
826
827        // Listeners come first, then the first absent probes in probe order.
828        let listed = details
829            .socket_probes
830            .iter()
831            .map(|probe| (probe.endpoint.as_str(), probe.status))
832            .collect::<Vec<_>>();
833        assert_eq!(
834            listed,
835            vec![
836                ("/50.sock", SocketProbeStatus::Unreachable),
837                ("/51.sock", SocketProbeStatus::ProtocolMismatch),
838                ("/0.sock", SocketProbeStatus::Absent),
839                ("/1.sock", SocketProbeStatus::Absent),
840                ("/2.sock", SocketProbeStatus::Absent),
841            ]
842        );
843        assert_eq!(details.absent_probe_count, 50);
844    }
845
846    #[test]
847    fn selector_parser_preserves_infallible_grammar() {
848        assert_eq!(SessionSelector::parse(""), SessionSelector::Current);
849        assert_eq!(SessionSelector::parse("current"), SessionSelector::Current);
850        assert_eq!(
851            SessionSelector::parse("name:api"),
852            SessionSelector::Name("api".to_string())
853        );
854        assert_eq!(SessionSelector::parse("pid:42"), SessionSelector::Pid(42));
855        assert_eq!(
856            SessionSelector::parse("pid:x"),
857            SessionSelector::Name("pid:x".to_string())
858        );
859        assert_eq!(
860            SessionSelector::parse("hash:abc"),
861            SessionSelector::ConfigHash("abc".to_string())
862        );
863    }
864
865    /// A `hash:` selector that is not an endpoint hash names no session, so it is never turned
866    /// into a socket path, not even one of another live socket in the runtime directory.
867    #[cfg(unix)]
868    #[tokio::test]
869    async fn a_hash_selector_that_is_not_an_endpoint_hash_probes_nothing() -> eyre::Result<()> {
870        let runtime_dir = tempfile::tempdir()?;
871        let _proxy = std::os::unix::net::UnixListener::bind(runtime_dir.path().join("proxy.sock"))?;
872        let runtime_dirs = vec![runtime_dir.path().to_path_buf()];
873        let dir_statuses = vec![RuntimeDirStatus {
874            path: runtime_dir.path().to_path_buf(),
875            usable: true,
876            error: None,
877        }];
878
879        for hash in ["proxy", "../proxy", "3F98F83E6E2C8D23"] {
880            let result = resolve_selector_in_runtime_dirs(
881                &runtime_dirs,
882                &dir_statuses,
883                runtime_dir.path(),
884                Some(SessionSelector::ConfigHash(hash.to_string())),
885                None,
886            )
887            .await;
888
889            let Err(SelectError::NoSession(report)) = result else {
890                eyre::bail!("expected no session for hash {hash}");
891            };
892            assert_eq!(report.socket_probes.len(), 0, "{hash}");
893        }
894        Ok(())
895    }
896
897    #[tokio::test]
898    async fn config_override_selects_a_session_outside_the_cwd() -> eyre::Result<()> {
899        let runtime_dir = tempfile::tempdir()?;
900        let cwd = tempfile::tempdir()?;
901        let project = tempfile::tempdir()?;
902        let config_path = project.path().join("micromux.yaml");
903        std::fs::write(
904            &config_path,
905            "version: 1\nservices:\n  svc:\n    command: [\"sh\", \"-c\", \"sleep 60\"]\n",
906        )?;
907        let config_path = CanonicalConfigPath::new(config_path)?;
908        let running = boot(runtime_dir.path(), project.path(), &config_path)?;
909        let statuses = vec![RuntimeDirStatus {
910            path: runtime_dir.path().to_path_buf(),
911            usable: true,
912            error: None,
913        }];
914
915        let resolved = resolve_selector_in_runtime_dirs(
916            &[runtime_dir.path().to_path_buf()],
917            &statuses,
918            cwd.path(),
919            None,
920            Some(config_path.as_path()),
921        )
922        .await?;
923
924        assert_eq!(resolved.info.name, "selected");
925        assert_eq!(Path::new(&resolved.info.config_path), config_path.as_path());
926        running.shutdown.cancel();
927        Ok(())
928    }
929
930    /// The session binds under the *canonical* config path; a client whose cwd or `--config`
931    /// override reaches that config only through a symlink must still derive the same endpoint.
932    /// macOS hits this constantly (`/tmp` and `/var` are symlinks into `/private`); the explicit
933    /// symlink makes the divergence deterministic on every unix platform.
934    #[tokio::test]
935    async fn selector_resolves_through_a_symlinked_project_path() -> eyre::Result<()> {
936        let runtime_dir = tempfile::tempdir()?;
937        let root = tempfile::tempdir()?;
938        let project = root.path().join("real-project");
939        std::fs::create_dir(&project)?;
940        let alias = root.path().join("alias");
941        std::os::unix::fs::symlink(&project, &alias)?;
942        let config_path = project.join("micromux.yaml");
943        std::fs::write(
944            &config_path,
945            "version: 1\nservices:\n  svc:\n    command: [\"sh\", \"-c\", \"sleep 60\"]\n",
946        )?;
947        // Mirror production startup: the endpoint is derived from the canonical config path.
948        let canonical = CanonicalConfigPath::new(&config_path)?;
949        let running = boot(runtime_dir.path(), &project, &canonical)?;
950        let statuses = vec![RuntimeDirStatus {
951            path: runtime_dir.path().to_path_buf(),
952            usable: true,
953            error: None,
954        }];
955
956        // Current-directory discovery from inside the symlinked alias.
957        let resolved = resolve_selector_in_runtime_dirs(
958            &[runtime_dir.path().to_path_buf()],
959            &statuses,
960            &alias,
961            None,
962            None,
963        )
964        .await?;
965        assert_eq!(resolved.info.name, "selected");
966
967        // An explicit config override spelled through the symlink.
968        let resolved = resolve_selector_in_runtime_dirs(
969            &[runtime_dir.path().to_path_buf()],
970            &statuses,
971            root.path(),
972            None,
973            Some(&alias.join("micromux.yaml")),
974        )
975        .await?;
976        assert_eq!(resolved.info.name, "selected");
977
978        running.shutdown.cancel();
979        Ok(())
980    }
981}