trusty_code/tui_client/discovery.rs
1//! Daemon discovery for [`crate::tui_client::CodeEngine`] (issue #3415,
2//! DOC-50 §3.4).
3//!
4//! Why: `tcode tui` needs to find an already-running `tcode serve --http`
5//! daemon without the operator hand-copying a port. DOC-50 §3.4 specifies
6//! the lookup priority — explicit override, then a discovery file, then a
7//! liveness check — but its prose sketched a NEW `~/.trusty-code/daemon.json`
8//! shape; `crate::serve::discovery` documents why this crate follows the
9//! ALREADY-ESTABLISHED sibling convention (`trusty-memory`/`trusty-search`'s
10//! plain-text `http_addr` file) instead. This module is the READ side of
11//! that convention; `crate::serve::discovery`'s `write_http_addr_file` is
12//! the write side, called from `crate::serve::http::run_http`.
13//! What: [`lookup_daemon`] tries, in order, [`DAEMON_URL_ENV`] (an
14//! explicit override — trusted without a liveness check of its own source,
15//! but still ping-verified before use, same as the file-sourced candidate)
16//! then the `http_addr` discovery file; whichever candidate is found is
17//! verified alive via `GET {url}/health` (the SAME route
18//! `crate::serve::methods::health_payload` answers, already the
19//! ecosystem-standard liveness probe per `crate::serve::http`'s docs). It
20//! reports the outcome as a three-way [`Lookup`] — live, found-but-dead
21//! (naming its [`Source`]), or no candidate at all — because a CALLER has to
22//! branch on WHICH source failed: `tcode tui` auto-spawns a daemon when the
23//! discovery file is stale or absent, but must NOT when
24//! [`DAEMON_URL_ENV`] explicitly named an address, since spawning
25//! something at a DIFFERENT address would quietly ignore that instruction
26//! (#4512). A live daemon additionally carries the [`ReportedBinding`] it
27//! published, because "a daemon is answering" is NOT the same question as
28//! "that daemon serves the project I mean to work in" — see
29//! [`ReportedBinding`]. [`discover_daemon_url`] is the attach-only wrapper
30//! over it, collapsing the same three outcomes into a [`DiscoveryError`]
31//! with an actionable message — never a silent `None`/default.
32//! Test: `discovery_tests::*` for the pure candidate-selection logic (env
33//! var precedence, file fallback, "neither present" case), the
34//! [`Lookup`]-to-[`DiscoveryError`] collapse, and [`ReportedBinding`]
35//! parsing; the liveness-ping branch is covered end-to-end in
36//! `tests/tui_client_engine.rs` against a mock daemon (a unit test would need
37//! a real bound socket to ping, which belongs in that hermetic integration
38//! suite, not here).
39
40use std::path::PathBuf;
41use std::time::Duration;
42
43use crate::binding::ProjectBinding;
44
45/// Environment variable that, when set to a non-empty value, names the
46/// daemon URL directly — highest-priority discovery source (DOC-50 §3.4
47/// point 1).
48pub const DAEMON_URL_ENV: &str = "TCODE_DAEMON_URL";
49
50/// Environment variable naming the daemon credential directly, ahead of the
51/// token file (#5439).
52///
53/// Why: a client may run where it cannot read the daemon's data directory — a
54/// container, a different account, an operator driving a remote daemon over a
55/// tunnel. This is a CLIENT-side override only: `tcode serve --http` never
56/// reads it, because a server that took its credential from the environment
57/// would accept whatever a caller could arrange to export.
58pub const DAEMON_TOKEN_ENV: &str = "TCODE_DAEMON_TOKEN";
59
60/// The credential to send to `base_url`, or `None` when there is none to send
61/// or none that may be sent.
62///
63/// Why: the token authenticates a caller to the LOCAL daemon, and nothing
64/// else. `TCODE_DAEMON_URL` can legitimately name a non-loopback address (an
65/// operator forwarding a port, a remote daemon over a tunnel), and attaching
66/// the local machine's credential to a request leaving loopback would hand it
67/// to whatever answers. This crate resolves it in one place so the three
68/// request sites — `RpcHttpClient`, the SSE readers, and `probe_health` —
69/// cannot each grow their own answer.
70/// What: a thin naming of `trusty_common::daemon_token::credential_for`, which
71/// owns the loopback gate, the override precedence, and the file read.
72///
73/// The gate lives THERE and not here for a reason worth stating: the first
74/// version of this function called `server::origin_is_loopback`, an
75/// `Origin`-HEADER parser, which reads
76/// `http://127.0.0.1:7882@attacker.example` as loopback and shipped the token
77/// off-machine. `trusty-code-gui` had the identical bug in its own copy. One
78/// implementation, parsing the way the client that dials the URL parses.
79/// Test: `discovery_tests::credential_is_withheld_from_a_non_loopback_url`,
80/// `discovery_tests::credential_env_override_wins_for_a_loopback_url`.
81pub fn daemon_credential_for(base_url: &str) -> Option<String> {
82 trusty_common::daemon_token::credential_for(
83 crate::serve::http::TOKEN_APP_NAME,
84 base_url,
85 DAEMON_TOKEN_ENV,
86 )
87}
88
89/// How long the liveness ping (`GET {url}/health`) waits before treating the
90/// candidate as dead. Short and fixed — this call happens once, at REPL
91/// startup, and a slow/hung `/health` response is itself a strong "don't use
92/// this daemon" signal.
93const PING_TIMEOUT: Duration = Duration::from_secs(2);
94
95/// Which discovery source produced a candidate URL — carried into
96/// [`Lookup::Dead`] (and from there into [`DiscoveryError::NotAlive`]) so the
97/// error message tells the operator WHERE the stale/wrong pointer came from,
98/// and so `tcode tui`'s auto-spawn can tell an EXPLICIT instruction it must
99/// obey ([`Source::Env`]) from a stale file it may replace ([`Source::File`]).
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum Source {
102 /// [`DAEMON_URL_ENV`] named the URL — an explicit operator instruction.
103 Env,
104 /// The `http_addr` discovery file named the URL — a best-effort pointer
105 /// a previous daemon left behind.
106 File,
107}
108
109impl Source {
110 /// Human-readable name for error messages ("from {found_via}").
111 pub fn as_str(self) -> &'static str {
112 match self {
113 Source::Env => "TCODE_DAEMON_URL",
114 Source::File => "discovery file",
115 }
116 }
117}
118
119/// The project binding a live daemon published on `GET /health` (#4512).
120///
121/// Why: a `tcode serve --http` daemon binds exactly ONE `ProjectBinding` at
122/// `crate::serve::build_router` time and keeps it for its whole life. Until
123/// #4512 that binding was invisible to clients, which was harmless while
124/// `tcode tui` refused to run without a hand-started daemon — the operator
125/// who started it knew what it was bound to. Auto-attach removes that
126/// guarantee: a TUI launched in project B finds project A's daemon on the
127/// well-known port and would drive it, so every session, index, and file
128/// operation would silently land in the wrong project. Making the binding
129/// part of the lookup result is what lets a caller refuse.
130/// What: the daemon's bound project root, or an explicit projectless state,
131/// or [`Unreported`](ReportedBinding::Unreported) when `/health` answered but
132/// carried no usable `binding` field — a daemon older than #4512, or one
133/// whose payload could not be parsed. Those two are deliberately the same
134/// variant: both mean "this daemon's project CANNOT be verified", and a
135/// caller must treat an unverifiable daemon the same way regardless of why.
136/// Test: `discovery_tests::reported_binding_parses_every_health_shape`.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub enum ReportedBinding {
139 /// The daemon reported it serves no project.
140 Projectless,
141 /// The daemon reported this canonical project root.
142 Bound(PathBuf),
143 /// `/health` answered, but with no parseable `binding` field.
144 Unreported,
145}
146
147impl ReportedBinding {
148 /// Read a [`ReportedBinding`] out of a `GET /health` body.
149 ///
150 /// Why/What: reuses `ProjectBinding`'s own `Deserialize` (the
151 /// `{state, root}` wire shape defined once in `crate::binding`) rather
152 /// than re-spelling that shape here, so the reader can never drift from
153 /// the writer. A missing or malformed field is
154 /// [`Unreported`](ReportedBinding::Unreported), never a guess.
155 /// Test: `discovery_tests::reported_binding_parses_every_health_shape`.
156 pub fn from_health(health: &serde_json::Value) -> Self {
157 let Some(raw) = health.get("binding") else {
158 return Self::Unreported;
159 };
160 match serde_json::from_value::<ProjectBinding>(raw.clone()) {
161 Ok(binding) => match binding.root() {
162 Some(root) => Self::Bound(root.to_path_buf()),
163 None => Self::Projectless,
164 },
165 Err(_) => Self::Unreported,
166 }
167 }
168
169 /// How to name this binding in an operator-facing message.
170 ///
171 /// Why: a mismatch error has to print BOTH sides, and "no project" has to
172 /// read as a deliberate state rather than as missing information.
173 /// Test: `discovery_tests::reported_binding_describes_each_state`.
174 pub fn describe(&self) -> String {
175 match self {
176 Self::Projectless => "<projectless>".to_string(),
177 Self::Bound(root) => root.display().to_string(),
178 Self::Unreported => "<unreported — daemon predates #4512>".to_string(),
179 }
180 }
181}
182
183/// The three distinguishable outcomes of one daemon lookup.
184///
185/// Why: [`DiscoveryError`] collapses "found but dead" and "nothing found"
186/// into two error variants that both mean "you can't attach", which is all
187/// an attach-only caller needs. Auto-spawn needs MORE: it must refuse to
188/// spawn when [`Source::Env`] named a dead address (spawning would land at a
189/// different address and ignore the operator's explicit instruction), while
190/// treating a dead or absent discovery file as a green light (#4512). It
191/// also needs the live daemon's [`ReportedBinding`], since attaching to a
192/// daemon bound to a DIFFERENT project is worse than not attaching at all.
193/// Test: `discovery_tests::lookup_collapses_into_discovery_errors`.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub enum Lookup {
196 /// A candidate answered `GET {url}/health` — attach to it, if `binding`
197 /// is the project the caller wants.
198 Live {
199 url: String,
200 binding: ReportedBinding,
201 },
202 /// A candidate URL was named by `source` but is not responding.
203 Dead { url: String, source: Source },
204 /// Neither source named a candidate URL.
205 Absent,
206}
207
208/// See module docs.
209#[derive(Debug, thiserror::Error, PartialEq, Eq)]
210pub enum DiscoveryError {
211 /// Neither `TCODE_DAEMON_URL` nor the discovery file named a candidate
212 /// daemon URL.
213 #[error(
214 "no tcode daemon found — start one with `tcode serve --http`, or point \
215 `tcode tui` at a running instance with `{DAEMON_URL_ENV}=http://host:port`"
216 )]
217 NotFound,
218
219 /// A candidate URL was found (from `source`) but did not answer
220 /// `GET {url}/health` with a success status within [`PING_TIMEOUT`].
221 #[error(
222 "found a tcode daemon reference at {url} (from {found_via}) but it is not responding \
223 — is it still running? Start one with `tcode serve --http`, or update {DAEMON_URL_ENV} \
224 to point at a live daemon"
225 )]
226 NotAlive {
227 url: String,
228 found_via: &'static str,
229 },
230}
231
232/// Resolve a candidate daemon URL and report whether it is live, per this
233/// module's docs.
234///
235/// Why/What: see module docs — this is the source-aware primitive
236/// [`discover_daemon_url`] and `tcode tui`'s auto-spawn (#4512) are both
237/// built on. `client` is caller-supplied (rather than built internally) so
238/// `CodeEngine` can reuse the SAME pooled `reqwest::Client` for both this
239/// ping and every later `POST /rpc`/SSE call — one connection pool for the
240/// engine's whole lifetime, not one throwaway client per call.
241/// Test: `discovery_tests::env_var_wins_over_file`,
242/// `discovery_tests::env_var_trailing_slash_is_stripped`,
243/// `discovery_tests::blank_env_var_is_ignored` cover candidate selection;
244/// the liveness branch is covered by `tests/tui_client_engine.rs` and (for
245/// the spawn decision it feeds) `cli::daemon_autospawn`'s tests.
246pub async fn lookup_daemon(client: &reqwest::Client) -> Lookup {
247 let Some((url, source)) = candidate_url() else {
248 return Lookup::Absent;
249 };
250 match probe_health(client, &url).await {
251 Some(health) => Lookup::Live {
252 url,
253 binding: ReportedBinding::from_health(&health),
254 },
255 None => Lookup::Dead { url, source },
256 }
257}
258
259/// Resolve and verify a live daemon URL, failing when none can be attached
260/// to — the attach-only view of [`lookup_daemon`].
261///
262/// Why: `CodeEngine::discover` (and every non-TUI caller) only ever wants
263/// "give me a live daemon or an actionable error"; the three-way [`Lookup`]
264/// distinction matters solely to the auto-spawn path.
265/// Test: `discovery_tests::lookup_collapses_into_discovery_errors`;
266/// end-to-end in `tests/tui_client_engine.rs`.
267pub async fn discover_daemon_url(client: &reqwest::Client) -> Result<String, DiscoveryError> {
268 collapse(lookup_daemon(client).await)
269}
270
271/// The pure [`Lookup`] -> [`DiscoveryError`] mapping, split out of
272/// [`discover_daemon_url`] so it is unit testable without a bound socket.
273fn collapse(lookup: Lookup) -> Result<String, DiscoveryError> {
274 match lookup {
275 Lookup::Live { url, .. } => Ok(url),
276 Lookup::Dead { url, source } => Err(DiscoveryError::NotAlive {
277 url,
278 found_via: source.as_str(),
279 }),
280 Lookup::Absent => Err(DiscoveryError::NotFound),
281 }
282}
283
284/// Pick a candidate URL from the env var or the discovery file, per the
285/// documented priority. Pure (no network I/O) so it's directly unit
286/// testable.
287fn candidate_url() -> Option<(String, Source)> {
288 if let Ok(raw) = std::env::var(DAEMON_URL_ENV) {
289 let trimmed = raw.trim();
290 if !trimmed.is_empty() {
291 return Some((trimmed.trim_end_matches('/').to_string(), Source::Env));
292 }
293 }
294 let path = crate::serve::discovery::http_addr_path()?;
295 let addr = crate::serve::discovery::read_http_addr_file(&path)?;
296 Some((format!("http://{addr}"), Source::File))
297}
298
299/// `GET {base_url}/health`, bounded by [`PING_TIMEOUT`] — `Some(body)` iff
300/// it returns a success (2xx) status with a JSON body.
301///
302/// #4512: this used to answer a bare `bool`. The BODY is now needed too, for
303/// the `binding` field the caller checks before attaching; a 2xx whose body
304/// will not parse as JSON still counts as alive (the daemon is answering),
305/// and degrades to `Value::Null`, from which
306/// [`ReportedBinding::from_health`] correctly reports `Unreported`.
307///
308/// #5439/#6472: `/health` stays reachable without a credential, but it answers
309/// an anonymous caller with liveness ALONE. This probe therefore sends the
310/// credential when it has one — without it the body carries no `binding`, and
311/// [`ReportedBinding::from_health`] correctly reports `Unreported`, which the
312/// caller must then treat as an unverifiable daemon.
313async fn probe_health(client: &reqwest::Client, base_url: &str) -> Option<serde_json::Value> {
314 let url = format!("{base_url}/health");
315 let mut req = client.get(&url).timeout(PING_TIMEOUT);
316 if let Some(token) = daemon_credential_for(base_url) {
317 req = req.bearer_auth(token);
318 }
319 let resp = req.send().await.ok()?;
320 if !resp.status().is_success() {
321 return None;
322 }
323 Some(resp.json().await.unwrap_or(serde_json::Value::Null))
324}
325
326#[cfg(test)]
327mod discovery_tests {
328 use super::*;
329
330 /// Serializes every test in this module that mutates `DAEMON_URL_ENV` —
331 /// mirrors `crate::task::mock_llm::MOCK_LLM_ENV_LOCK`'s established
332 /// pattern for env-mutating tests in this crate (a plain `tokio::sync::Mutex`
333 /// guard rather than pulling in `serial_test` for one file).
334 static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
335
336 /// #5439's credential-exfiltration guard: the local token authenticates a
337 /// caller to the LOCAL daemon and must never leave loopback, however the
338 /// operator points `TCODE_DAEMON_URL`.
339 ///
340 /// This is the arm that fails open if the gate is dropped — with a token
341 /// available in the environment, a non-loopback base URL must still
342 /// resolve to `None`.
343 #[tokio::test]
344 async fn credential_is_withheld_from_a_non_loopback_url() {
345 let _guard = ENV_LOCK.lock().await;
346 // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
347 unsafe {
348 std::env::set_var(DAEMON_TOKEN_ENV, "a".repeat(64));
349 }
350 let remote = [
351 "http://example.test:7882",
352 "https://10.0.0.5:7882",
353 "http://192.168.1.4:7882",
354 // The userinfo family. An `Origin`-header parser splits the
355 // authority at the FIRST `:`, so it reads the host of these as
356 // `127.0.0.1` and calls them loopback; WHATWG URL parsing splits
357 // userinfo at the LAST `@`, so the real host is `attacker.example`
358 // and every request goes there. Gating on the header parser shipped
359 // a credential-exfiltration path that the plain-hostname rows above
360 // could never catch.
361 "http://127.0.0.1:7882@attacker.example",
362 "http://127.0.0.1:7882@attacker.example/rpc",
363 "http://localhost@attacker.example",
364 "http://user:pass@attacker.example",
365 ]
366 .map(daemon_credential_for);
367 let local = daemon_credential_for("http://127.0.0.1:7882");
368 unsafe {
369 std::env::remove_var(DAEMON_TOKEN_ENV);
370 }
371 for (url, resolved) in [
372 "example.test",
373 "10.0.0.5",
374 "192.168.1.4",
375 "127.0.0.1:7882@attacker.example",
376 "127.0.0.1:7882@attacker.example/rpc",
377 "localhost@attacker.example",
378 "user:pass@attacker.example",
379 ]
380 .iter()
381 .zip(remote.iter())
382 {
383 assert_eq!(resolved.as_deref(), None, "{url} must get no credential");
384 }
385 assert_eq!(
386 local.as_deref(),
387 Some("a".repeat(64).as_str()),
388 "loopback must get the credential"
389 );
390 }
391
392 /// The env override must beat the token file, so a client that cannot read
393 /// the daemon's data directory can still be pointed at a credential.
394 #[tokio::test]
395 async fn credential_env_override_wins_for_a_loopback_url() {
396 let _guard = ENV_LOCK.lock().await;
397 // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
398 unsafe {
399 std::env::set_var(DAEMON_TOKEN_ENV, "b".repeat(64));
400 }
401 let resolved = daemon_credential_for("http://localhost:7882");
402 unsafe {
403 std::env::remove_var(DAEMON_TOKEN_ENV);
404 }
405 assert_eq!(resolved.as_deref(), Some("b".repeat(64).as_str()));
406 }
407
408 /// A blank override must be ignored rather than becoming an empty
409 /// credential — an empty bearer is a malformed header, not "no header".
410 #[tokio::test]
411 async fn blank_credential_override_falls_through() {
412 let _guard = ENV_LOCK.lock().await;
413 // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
414 unsafe {
415 std::env::set_var(DAEMON_TOKEN_ENV, " ");
416 }
417 let resolved = daemon_credential_for("http://127.0.0.1:7882");
418 unsafe {
419 std::env::remove_var(DAEMON_TOKEN_ENV);
420 }
421 assert_ne!(
422 resolved.as_deref(),
423 Some(""),
424 "a blank override must not become an empty credential"
425 );
426 }
427
428 /// Both a `TCODE_DAEMON_URL` and a discovery file present: the env var
429 /// must win (DOC-50 §3.4 point 1's explicit priority).
430 #[tokio::test]
431 async fn env_var_wins_over_file() {
432 let _guard = ENV_LOCK.lock().await;
433 // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
434 unsafe {
435 std::env::set_var(DAEMON_URL_ENV, "http://127.0.0.1:9999");
436 }
437 let (url, source) = candidate_url().expect("candidate");
438 unsafe {
439 std::env::remove_var(DAEMON_URL_ENV);
440 }
441 assert_eq!(url, "http://127.0.0.1:9999");
442 assert_eq!(source, Source::Env);
443 }
444
445 /// A trailing slash on the env var is stripped, so URL-joining callers
446 /// (`{base}/rpc`, `{base}/health`) never produce a doubled `//`.
447 #[tokio::test]
448 async fn env_var_trailing_slash_is_stripped() {
449 let _guard = ENV_LOCK.lock().await;
450 // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
451 unsafe {
452 std::env::set_var(DAEMON_URL_ENV, "http://127.0.0.1:9999/");
453 }
454 let (url, _source) = candidate_url().expect("candidate");
455 unsafe {
456 std::env::remove_var(DAEMON_URL_ENV);
457 }
458 assert_eq!(url, "http://127.0.0.1:9999");
459 }
460
461 /// An empty/whitespace `TCODE_DAEMON_URL` must be treated as unset, not
462 /// as a (broken) candidate.
463 #[tokio::test]
464 async fn blank_env_var_is_ignored() {
465 let _guard = ENV_LOCK.lock().await;
466 // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
467 unsafe {
468 std::env::set_var(DAEMON_URL_ENV, " ");
469 }
470 // With the env var blank, resolution falls through to the discovery
471 // file — assert only that the env var itself did not win.
472 let result = candidate_url();
473 unsafe {
474 std::env::remove_var(DAEMON_URL_ENV);
475 }
476 if let Some((_, source)) = result {
477 assert_ne!(source, Source::Env);
478 }
479 }
480
481 /// `DiscoveryError::NotFound`'s message must name the actionable fix
482 /// (start a daemon, or set the env var) — pinned so a future edit can't
483 /// silently regress it into an unhelpful "not found".
484 #[test]
485 fn not_found_message_is_actionable() {
486 let msg = DiscoveryError::NotFound.to_string();
487 assert!(msg.contains("tcode serve --http"));
488 assert!(msg.contains(DAEMON_URL_ENV));
489 }
490
491 /// Every `Lookup` outcome must collapse to the matching attach-only
492 /// result — pinned because `tcode tui`'s auto-spawn now branches on the
493 /// SAME three outcomes (#4512), and the two views must stay agreed on
494 /// what each one means.
495 #[test]
496 fn lookup_collapses_into_discovery_errors() {
497 assert_eq!(
498 collapse(Lookup::Live {
499 url: "http://127.0.0.1:7882".to_string(),
500 binding: ReportedBinding::Projectless,
501 }),
502 Ok("http://127.0.0.1:7882".to_string())
503 );
504 assert_eq!(
505 collapse(Lookup::Dead {
506 url: "http://127.0.0.1:7882".to_string(),
507 source: Source::Env,
508 }),
509 Err(DiscoveryError::NotAlive {
510 url: "http://127.0.0.1:7882".to_string(),
511 found_via: "TCODE_DAEMON_URL",
512 })
513 );
514 assert_eq!(collapse(Lookup::Absent), Err(DiscoveryError::NotFound));
515 }
516
517 /// Every shape a real `GET /health` body can take must map to the right
518 /// `ReportedBinding` — including the two "cannot verify" shapes, which
519 /// must NOT be mistaken for a projectless daemon (#4512).
520 #[test]
521 fn reported_binding_parses_every_health_shape() {
522 use serde_json::json;
523
524 let bound = json!({
525 "server": "tcode",
526 "binding": {"state": crate::binding::STATE_GIT_REPO, "root": "/tmp/proj"},
527 });
528 assert_eq!(
529 ReportedBinding::from_health(&bound),
530 ReportedBinding::Bound(PathBuf::from("/tmp/proj"))
531 );
532
533 let projectless = json!({
534 "binding": {"state": crate::binding::STATE_PROJECTLESS, "root": null},
535 });
536 assert_eq!(
537 ReportedBinding::from_health(&projectless),
538 ReportedBinding::Projectless
539 );
540
541 // A pre-#4512 daemon: `/health` answers, but with no binding at all.
542 let old = json!({"server": "tcode", "version": "0.2.0", "status": "ok"});
543 assert_eq!(
544 ReportedBinding::from_health(&old),
545 ReportedBinding::Unreported,
546 "a daemon that reports nothing must never read as projectless"
547 );
548
549 // A malformed payload is equally unverifiable, never a guess.
550 let malformed = json!({"binding": {"state": "who knows"}});
551 assert_eq!(
552 ReportedBinding::from_health(&malformed),
553 ReportedBinding::Unreported
554 );
555 assert_eq!(
556 ReportedBinding::from_health(&serde_json::Value::Null),
557 ReportedBinding::Unreported
558 );
559 }
560
561 /// Each state must render an operator-readable name — the mismatch error
562 /// prints both sides, so "no project" must not come out blank.
563 #[test]
564 fn reported_binding_describes_each_state() {
565 assert_eq!(ReportedBinding::Projectless.describe(), "<projectless>");
566 assert_eq!(
567 ReportedBinding::Bound(PathBuf::from("/tmp/proj")).describe(),
568 "/tmp/proj"
569 );
570 assert!(
571 ReportedBinding::Unreported.describe().contains("4512"),
572 "an unverifiable daemon must say why it cannot be checked"
573 );
574 }
575
576 /// `DiscoveryError::NotAlive`'s message must name both the dead URL and
577 /// which source produced it.
578 #[test]
579 fn not_alive_message_names_url_and_source() {
580 let err = DiscoveryError::NotAlive {
581 url: "http://127.0.0.1:7882".to_string(),
582 found_via: Source::File.as_str(),
583 };
584 let msg = err.to_string();
585 assert!(msg.contains("http://127.0.0.1:7882"));
586 assert!(msg.contains("discovery file"));
587 }
588}