openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! Boundary preflight — proving the forwarder actually *forwards* before any
//! agent is pointed at it, and un-pointing them the moment it stops.
//!
//! Binding the pinned port proves only that the port is held. It says nothing
//! about the leg that actually breaks in the field: loopback → axum → the
//! observe/transform stage → reqwest → TLS → `api.anthropic.com` → back. A
//! boundary that binds and then cannot reach upstream — captive portal, VPN not
//! up yet, corporate TLS interception, a regression in the forward path — is
//! indistinguishable from a healthy one from the agent's side, and every Claude
//! Code session on the machine dies on it, because `ANTHROPIC_BASE_URL` is set.
//!
//! So the wiring hangs off a *round trip*, not off a bind:
//!
//! > **Gate.** `ANTHROPIC_BASE_URL` is written only after a synthetic request
//! > has travelled the full path through our own listener and come back with an
//! > answer that provably originated upstream.
//!
//! ## Why an unauthenticated request is the right probe
//!
//! [`probe`] sends a deliberately credential-less `POST /v1/messages`. Anthropic
//! answers `401`. That is the **success** case: the question is not "did the
//! call succeed" but "did an *upstream* response come back at all". OpenLatch
//! has no provider credential of its own — the boundary forwards the caller's
//! verbatim — so a probe that required one would be unrunnable at daemon start,
//! and a probe that spent tokens would bill the customer for our health check.
//! A 401 costs nothing, needs no key, and still exercises every hop.
//!
//! The one response that must NOT open the gate is the boundary's own synthetic
//! 502 (`proxy::synth_502`, C-5b) — which is exactly what an unreachable
//! upstream produces. It carries `x-openlatch-upstream: unreachable`, so the two
//! are told apart by header rather than by status code: a real upstream 502
//! still proves a live path, because it came from upstream.
//!
//! ## Why the probe carries a marker header
//!
//! [`PREFLIGHT_HEADER`] marks the request as ours. The observe/transform stage
//! still runs on it — that stage is where bugs live, and a panic there is worth
//! surfacing — but the resulting observation is dropped instead of being
//! promoted to an economics event. Our health check is not the customer's
//! traffic and must never land on their bill or in their usage data. The header
//! is stripped before the request leaves for upstream.

use std::collections::BTreeMap;
use std::sync::Mutex;
use std::time::Duration;

use super::wire_format::WireFormat;

/// Marks a request as OpenLatch's own preflight probe.
///
/// Read in exactly two places: `proxy::proxy_any` drops the observation so the
/// probe never reaches the economics rail, and `proxy::forward_headers` strips
/// it so it never reaches the provider.
pub const PREFLIGHT_HEADER: &str = "x-openlatch-preflight";

/// The header the boundary stamps on its synthetic 502 when it could not reach
/// upstream at all (`proxy::synth_502`). Its presence is the single signal that
/// separates "our forwarder answered *for* the upstream" from "the upstream
/// answered".
const UPSTREAM_UNREACHABLE_HEADER: &str = "x-openlatch-upstream";

/// Total budget for one probe.
///
/// Deliberately far shorter than the forward path's own `HEADER_TIMEOUT` (60 s):
/// that budget is generous because a slow first token is legitimate on a real
/// turn, whereas an unauthenticated request is rejected at the provider's edge
/// and comes back in well under a second. A daemon start must not stall on a
/// silent upstream, and the supervisor's retry loop makes a tight budget safe —
/// a false negative costs one tick, not the wiring.
pub const PREFLIGHT_TIMEOUT: Duration = Duration::from_secs(5);

/// A credential-less `/v1/messages` body. `max_tokens: 1` so that even a
/// hypothetical future in which this request DID authenticate could not spend
/// meaningfully; as written it is rejected before a model is ever loaded.
const PREFLIGHT_BODY: &str =
    r#"{"model":"claude-sonnet-4-5","max_tokens":1,"messages":[{"role":"user","content":"ping"}]}"#;

/// The same claim in the OpenAI Responses shape — the minimal valid request,
/// with `max_output_tokens` playing `max_tokens`' role.
///
/// A probe that spoke `/v1/messages` at a Codex plane would prove a **Claude
/// Code** round trip and then open the gate for Codex: a disabled subsystem
/// rendering as healthy, which is the failure the gate exists to stop (PRD
/// D-13).
const PREFLIGHT_BODY_RESPONSES: &str =
    r#"{"model":"gpt-5-codex","input":"preflight","max_output_tokens":16}"#;

/// The value sent as `x-api-key`. Not a credential and not a redacted one — a
/// literal that cannot be mistaken for either in a log or a capture.
const PREFLIGHT_API_KEY: &str = "ol-preflight-not-a-key";

/// The outcome of the most recent probe.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Verdict {
    /// No probe has completed yet — the daemon is up but the gate has not run.
    /// Distinct from `Failed` on purpose: `init` waits `Pending` out, and a
    /// caller that collapsed the two would report a healthy install as broken
    /// for the first second of its life.
    #[default]
    Pending,
    /// A response provably originating upstream came back through our listener.
    Ok,
    /// The round trip did not complete. Carries the reason, surfaced verbatim by
    /// `init` and `doctor` — a preflight failure the operator cannot act on is
    /// barely better than no check at all.
    Failed(String),
}

impl Verdict {
    /// Stable machine-readable label for the admin surface and `--json`.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Ok => "ok",
            Self::Failed(_) => "failed",
        }
    }

    /// The failure reason, when there is one.
    pub fn error(&self) -> Option<&str> {
        match self {
            Self::Failed(e) => Some(e.as_str()),
            _ => None,
        }
    }

    /// Whether the gate is open.
    pub fn is_ok(&self) -> bool {
        matches!(self, Self::Ok)
    }
}

/// Process-wide view of the wiring gate, **keyed per agent**, shared by the
/// three parties that must agree on it: the supervisor that opens and closes
/// it, the admin status endpoint that reports it, and — through that endpoint —
/// `init` and `doctor`.
///
/// Deliberately NOT a field on the per-attempt `BoundaryState`: a boundary
/// restart rebuilds that struct, and the verdict has to survive one.
///
/// **Both fields are per agent, and neither may be left process-wide.** Two
/// agents on one host point at the same listener through different conventions
/// and are probed in different formats, so one can be wired while the other's
/// round trip fails. A single flag would report one plane's verdict for both:
/// `init` would pass on a host whose Codex plane never came up, and the failing
/// agent's own unwire would take the healthy one's wiring with it.
///
/// A missing key is `Pending` / not wired — the state an agent is in between
/// the supervisor seeding it and its first probe returning.
#[derive(Debug, Default)]
pub struct WiringState {
    wired: Mutex<BTreeMap<&'static str, bool>>,
    verdict: Mutex<BTreeMap<&'static str, Verdict>>,
    /// The format each agent's request plane was wired to speak, from its own
    /// [`BoundaryWiring`](crate::hooks::binding::BoundaryWiring).
    ///
    /// Recorded beside the flag rather than derived, because it is a fact about
    /// THIS install's configuration — the `wire_api` we wrote into Codex's
    /// `config.toml`, the `ANTHROPIC_BASE_URL` we set for Claude Code — and not
    /// a fixed agent→protocol table, which PRD D-7 says does not exist.
    format: Mutex<BTreeMap<&'static str, WireFormat>>,
}

impl WiringState {
    /// Read a map, degrading a poisoned lock to the value it was holding.
    ///
    /// This is read from the admin handler on the boundary's own runtime, and
    /// the gate's observability must never be able to take the listener down.
    fn read<T: Clone>(m: &Mutex<BTreeMap<&'static str, T>>) -> BTreeMap<&'static str, T> {
        match m.lock() {
            Ok(v) => v.clone(),
            Err(poisoned) => poisoned.into_inner().clone(),
        }
    }

    /// Mutate a map under the same poison-tolerant rule.
    fn write<T>(
        m: &Mutex<BTreeMap<&'static str, T>>,
        f: impl FnOnce(&mut BTreeMap<&'static str, T>),
    ) {
        match m.lock() {
            Ok(mut v) => f(&mut v),
            Err(poisoned) => f(&mut poisoned.into_inner()),
        }
    }

    /// Whether `agent`'s config currently points at this listener.
    pub fn is_wired(&self, agent: &str) -> bool {
        match self.wired.lock() {
            Ok(v) => v.get(agent).copied().unwrap_or(false),
            Err(poisoned) => poisoned.into_inner().get(agent).copied().unwrap_or(false),
        }
    }

    /// Record `agent`'s wiring state after a successful write / removal.
    pub fn set_wired(&self, agent: &'static str, wired: bool) {
        Self::write(&self.wired, |m| {
            m.insert(agent, wired);
        });
    }

    /// Record the format `agent`'s request plane was wired to speak.
    ///
    /// Separate from [`set_wired`](Self::set_wired) so an unwire clears the flag
    /// without erasing what the agent speaks — the entry is inert while the flag
    /// is false, and correct again the moment it is re-wired.
    pub fn set_wired_format(&self, agent: &'static str, format: WireFormat) {
        Self::write(&self.format, |m| {
            m.insert(agent, format);
        });
    }

    /// The single wired agent speaking `format`, when there is exactly one.
    ///
    /// This is the whole of the deduction, and the counting is the point.
    ///
    /// The boundary resolves a request's format from its ROUTE and never from
    /// agent identity (PRD D-7), so this cannot run backwards into "an Anthropic
    /// request means Claude Code". What it may say is narrower and checkable:
    /// *on this install, only one wired agent was configured to speak this
    /// protocol, so a request in it came from that agent.* Two speakers, or
    /// none, and there is no such sentence to say — the caller keeps `unknown`.
    ///
    /// `Unknown` is never attributable: it is the catch-all for every route the
    /// boundary does not capture, so "the sole agent speaking unknown" would be
    /// an answer about the routes rather than about an agent.
    pub fn sole_wired_agent_for(&self, format: WireFormat) -> Option<&'static str> {
        if !format.is_captured() {
            return None;
        }
        let wired = Self::read(&self.wired);
        let mut hit = None;
        for (agent, agent_format) in Self::read(&self.format) {
            if agent_format != format || !wired.get(agent).copied().unwrap_or(false) {
                continue;
            }
            if hit.is_some() {
                // A second speaker. Naming either would be a coin flip wearing
                // the platform's `(org, source, agent_id)` join key.
                return None;
            }
            hit = Some(agent);
        }
        hit
    }

    /// The most recent probe verdict for `agent`.
    ///
    /// `Pending` when the agent has no entry — the honest answer for a plane
    /// the supervisor has not judged yet, and the same value a fresh daemon
    /// reported before the state was keyed.
    pub fn verdict(&self, agent: &str) -> Verdict {
        match self.verdict.lock() {
            Ok(v) => v.get(agent).cloned().unwrap_or_default(),
            Err(poisoned) => poisoned
                .into_inner()
                .get(agent)
                .cloned()
                .unwrap_or_default(),
        }
    }

    /// Store a fresh probe verdict for `agent`.
    pub fn set_verdict(&self, agent: &'static str, verdict: Verdict) {
        Self::write(&self.verdict, |m| {
            m.insert(agent, verdict);
        });
    }

    /// Every verdict, for the admin surface to render one entry per agent.
    pub fn verdicts(&self) -> BTreeMap<&'static str, Verdict> {
        Self::read(&self.verdict)
    }

    /// Every wiring flag, for the same reason.
    ///
    /// A separate snapshot from [`verdicts`](Self::verdicts) because the two
    /// facts differ by design: the verdict goes `Ok` when the probe returns,
    /// the flag goes true only once the agent's file was actually written.
    /// Collapsing them would report a plane as wired on the strength of a green
    /// probe whose write then failed.
    pub fn wired_agents(&self) -> BTreeMap<&'static str, bool> {
        Self::read(&self.wired)
    }

    /// Give `agent` its `Pending` / not-wired entry, unless it already has one.
    ///
    /// The supervisor seeds every agent that has a request plane before its
    /// first probe. Without it an unprobed agent has no key at all, and every
    /// consumer of the status JSON — `classify_boundary`, `init`'s wait rule,
    /// `doctor` — falls through to its "some other reason" arm and renders a
    /// host that is merely still checking as one that is unwired.
    ///
    /// Never clobbers: a supervised restart re-seeds, and an agent already
    /// judged must keep its verdict.
    pub fn seed(&self, agent: &'static str) {
        Self::write(&self.wired, |m| {
            m.entry(agent).or_insert(false);
        });
        Self::write(&self.verdict, |m| {
            m.entry(agent).or_default();
        });
    }
}

/// Send one synthetic request through the boundary on `port` and classify the
/// round trip.
///
/// The listener must already be serving — this probes it over loopback exactly
/// as an agent would, rather than calling the handler in-process, because "the
/// handler works" and "the listener is reachable" are different claims and the
/// agent depends on both.
///
/// `upstream` is only ever named in the failure message — the probe cannot reach
/// it directly and must not try, since a check that bypassed the forwarder would
/// vouch for a path nobody uses. Passing it in keeps the message honest when the
/// daemon forwards somewhere other than the first-party API.
///
/// `Ok(())` means a response came back and it did not originate from our own
/// unreachable-upstream fallback. Every other outcome is `Err` with a reason
/// short enough for a CLI error and specific enough to act on.
///
/// **The probe speaks `fmt`** — its route, its credential header and its body.
/// Everything else is identical across formats: the same loopback target, the
/// same `UPSTREAM_UNREACHABLE_HEADER` check, the same error strings, and the
/// same non-credential.
pub async fn probe(
    port: u16,
    fmt: WireFormat,
    upstream: &str,
    timeout: Duration,
) -> Result<(), String> {
    let client = match crate::egress::client_builder().timeout(timeout).build() {
        Ok(c) => c,
        Err(e) => return Err(format!("could not build the preflight client: {e}")),
    };

    // `Unknown` is unreachable: the caller only ever probes a format it is about
    // to wire. Probe as Anthropic rather than refuse — a `debug_assert` says so
    // in a test build, and a release build must not turn a caller's mistake into
    // an unwired host.
    let responses = match fmt {
        WireFormat::OpenAiResponses => true,
        WireFormat::AnthropicMessages => false,
        // Named rather than a wildcard, so a fourth format is a compile error
        // here instead of silently probing as Anthropic.
        WireFormat::Unknown => {
            debug_assert!(false, "probe called for a format nothing wires: {fmt:?}");
            false
        }
    };

    let route = if responses {
        "/v1/responses"
    } else {
        "/v1/messages"
    };
    let url = format!("http://127.0.0.1:{port}{route}");
    let mut req = client
        .post(&url)
        .header("content-type", "application/json")
        .header(PREFLIGHT_HEADER, "1");
    req = if responses {
        req.header("authorization", format!("Bearer {PREFLIGHT_API_KEY}"))
            .body(PREFLIGHT_BODY_RESPONSES)
    } else {
        req.header("anthropic-version", "2023-06-01")
            .header("x-api-key", PREFLIGHT_API_KEY)
            .body(PREFLIGHT_BODY)
    };
    let sent = req.send().await;

    let resp = match sent {
        Ok(r) => r,
        Err(e) if e.is_timeout() => {
            return Err(format!(
                "no response from the boundary on 127.0.0.1:{port} within {}s",
                timeout.as_secs()
            ))
        }
        // `without_url` keeps the message to the source cause. The URL is
        // loopback and the body synthetic, so nothing sensitive is at stake —
        // but a reqwest Display that embeds the request is a habit worth not
        // forming on a path whose output lands in CLI errors and logs.
        Err(e) => {
            return Err(format!(
                "could not reach the boundary on 127.0.0.1:{port}: {}",
                e.without_url()
            ))
        }
    };

    if resp.headers().contains_key(UPSTREAM_UNREACHABLE_HEADER) {
        return Err(format!(
            "the boundary is listening but could not reach {upstream} — model calls would fail"
        ));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::boundary::{mock, serve_ephemeral, BoundaryState};
    use std::sync::Arc;

    fn state_for(upstream_port: u16) -> Arc<BoundaryState> {
        let base = reqwest::Url::parse(&format!("http://127.0.0.1:{upstream_port}")).unwrap();
        Arc::new(BoundaryState::new(base, 0, 8, &[]))
    }

    /// The gate opens on a reachable upstream — including one that rejects the
    /// call. "Upstream answered" is the claim, not "the call succeeded": the
    /// probe carries no credential precisely so it cannot succeed.
    #[tokio::test(flavor = "multi_thread")]
    async fn probe_passes_when_upstream_answers() {
        let upstream = mock::spawn_capture_200().await;
        let port = serve_ephemeral(state_for(upstream.port)).await;

        assert_eq!(
            probe(
                port,
                WireFormat::AnthropicMessages,
                crate::boundary::ANTHROPIC_BASE,
                PREFLIGHT_TIMEOUT
            )
            .await,
            Ok(())
        );
    }

    /// An upstream that cannot be reached produces the synthetic 502, and the
    /// gate must stay shut on it. This is the exact shape of the field bug: the
    /// bind succeeded, the listener is up, and every session would still die if
    /// the agent were wired here.
    #[tokio::test(flavor = "multi_thread")]
    async fn probe_fails_when_upstream_is_unreachable() {
        let dead = mock::closed_port().await;
        let port = serve_ephemeral(state_for(dead)).await;

        let err = probe(
            port,
            WireFormat::AnthropicMessages,
            crate::boundary::ANTHROPIC_BASE,
            PREFLIGHT_TIMEOUT,
        )
        .await
        .unwrap_err();
        assert!(
            err.contains("could not reach"),
            "an unreachable upstream must be named as such, got: {err}"
        );
    }

    /// An upstream that accepts the connection and then says nothing is the hang
    /// the forward path's header timeout exists for. The probe must not wait it
    /// out — it has its own, much tighter budget, and a daemon start that blocks
    /// on a silent provider is its own outage.
    #[tokio::test(flavor = "multi_thread")]
    async fn probe_fails_fast_on_a_silent_upstream() {
        let hung = mock::spawn_hang_after_accept().await;
        let upstream = reqwest::Url::parse(&format!("http://127.0.0.1:{hung}")).unwrap();
        // Mirror production ordering: the forward path's own header wait is far
        // longer than the probe budget, so the probe's timeout is what fires.
        let state = Arc::new(
            BoundaryState::new(upstream, 0, 8, &[]).with_header_timeout(Duration::from_secs(60)),
        );
        let port = serve_ephemeral(state).await;

        let started = std::time::Instant::now();
        let err = probe(
            port,
            WireFormat::AnthropicMessages,
            crate::boundary::ANTHROPIC_BASE,
            Duration::from_millis(300),
        )
        .await
        .unwrap_err();
        assert!(
            err.contains("no response"),
            "a silent upstream must read as no response, got: {err}"
        );
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "the probe must return on its own budget, not the forward path's"
        );
    }

    /// Nothing listening at all — what a supervisor restart passes through.
    #[tokio::test(flavor = "multi_thread")]
    async fn probe_fails_when_nothing_is_listening() {
        let port = mock::closed_port().await;
        assert!(probe(
            port,
            WireFormat::AnthropicMessages,
            crate::boundary::ANTHROPIC_BASE,
            Duration::from_millis(500)
        )
        .await
        .is_err());
    }

    /// THE D-13 GATE. Without it the probe passes on a broken Codex plane: run
    /// unchanged it sends `POST /v1/messages` with `anthropic-version`, proving
    /// a **Claude Code** round trip and then opening the gate for Codex — a
    /// disabled subsystem rendering as healthy.
    #[tokio::test(flavor = "multi_thread")]
    async fn probe_sends_the_format_it_was_given() {
        let upstream = mock::spawn_capture_200().await;
        let port = serve_ephemeral(state_for(upstream.port)).await;

        assert_eq!(
            probe(
                port,
                WireFormat::OpenAiResponses,
                crate::boundary::wire_format::OPENAI_BASE,
                PREFLIGHT_TIMEOUT
            )
            .await,
            Ok(())
        );

        let line = upstream
            .received_request_line
            .lock()
            .unwrap()
            .clone()
            .expect("the mock recorded the request line");
        assert!(
            line.starts_with("POST /v1/responses"),
            "a Responses probe must speak the Responses route, got: {line}"
        );
        assert_eq!(
            upstream.header("anthropic-version"),
            None,
            "an Anthropic protocol header on an OpenAI request is the exact defect this gate exists to catch"
        );
    }

    /// The probe's claim is "upstream answered", never "the call worked" — so it
    /// must keep carrying a literal that cannot authenticate, in BOTH formats.
    /// A real credential here would put OpenLatch's own synthetic traffic on the
    /// customer's bill.
    #[tokio::test(flavor = "multi_thread")]
    async fn probe_carries_no_real_credential() {
        let anthropic_up = mock::spawn_capture_200().await;
        let port = serve_ephemeral(state_for(anthropic_up.port)).await;
        assert_eq!(
            probe(
                port,
                WireFormat::AnthropicMessages,
                crate::boundary::ANTHROPIC_BASE,
                PREFLIGHT_TIMEOUT
            )
            .await,
            Ok(())
        );
        assert_eq!(
            anthropic_up.header("x-api-key").as_deref(),
            Some(PREFLIGHT_API_KEY),
            "the Anthropic probe must send the not-a-key literal"
        );

        let responses_up = mock::spawn_capture_200().await;
        let port = serve_ephemeral(state_for(responses_up.port)).await;
        assert_eq!(
            probe(
                port,
                WireFormat::OpenAiResponses,
                crate::boundary::wire_format::OPENAI_BASE,
                PREFLIGHT_TIMEOUT
            )
            .await,
            Ok(())
        );
        assert_eq!(
            responses_up.header("authorization").as_deref(),
            Some(format!("Bearer {PREFLIGHT_API_KEY}").as_str()),
            "the Responses probe must send the same not-a-key literal as a Bearer"
        );
    }

    #[test]
    fn verdict_labels_are_stable() {
        assert_eq!(Verdict::default(), Verdict::Pending);
        assert_eq!(Verdict::Pending.label(), "pending");
        assert_eq!(Verdict::Ok.label(), "ok");
        assert_eq!(Verdict::Failed("boom".into()).label(), "failed");
        assert_eq!(Verdict::Failed("boom".into()).error(), Some("boom"));
        assert_eq!(Verdict::Ok.error(), None);
        assert!(Verdict::Ok.is_ok());
        assert!(!Verdict::Pending.is_ok());
    }

    #[test]
    fn wiring_state_round_trips() {
        let st = WiringState::default();
        assert!(!st.is_wired("claude-code"));
        assert_eq!(st.verdict("claude-code"), Verdict::Pending);

        st.set_wired("claude-code", true);
        st.set_verdict("claude-code", Verdict::Ok);
        assert!(st.is_wired("claude-code"));
        assert_eq!(st.verdict("claude-code"), Verdict::Ok);
    }

    /// Two agents point at ONE listener through two conventions, and one can be
    /// wired while the other's round trip fails. A process-wide flag reports
    /// one plane's verdict for both — which is how `init` passes on a host
    /// whose Codex plane never came up, and how one failing probe unwires the
    /// agent that was working.
    ///
    /// `wiring_state_round_trips` above cannot gate this: it still compiles and
    /// passes against a single-valued `WiringState`.
    #[test]
    fn wiring_state_is_keyed_per_agent() {
        let st = WiringState::default();

        st.set_wired("claude-code", true);
        assert!(st.is_wired("claude-code"));
        assert!(
            !st.is_wired("codex-cli"),
            "one agent's wiring says nothing about another's"
        );

        st.set_verdict("claude-code", Verdict::Ok);
        assert_eq!(
            st.verdict("codex-cli"),
            Verdict::Pending,
            "an agent with no entry is Pending — not the other agent's verdict"
        );

        st.set_verdict("codex-cli", Verdict::Failed("no round trip".into()));
        let verdicts = st.verdicts();
        assert_eq!(verdicts.get("claude-code"), Some(&Verdict::Ok));
        assert_eq!(
            verdicts.get("codex-cli"),
            Some(&Verdict::Failed("no round trip".into())),
            "the snapshot the admin surface renders carries every agent"
        );

        let wired = st.wired_agents();
        assert_eq!(wired.get("claude-code"), Some(&true));
        assert_eq!(
            wired.get("codex-cli"),
            None,
            "a verdict is not a write: codex-cli was judged, never wired"
        );

        // Seeding gives an unprobed agent its entry without clobbering one
        // that has already been judged.
        st.seed("cursor");
        st.seed("claude-code");
        assert_eq!(st.verdict("cursor"), Verdict::Pending);
        assert_eq!(st.wired_agents().get("cursor"), Some(&false));
        assert_eq!(
            st.verdict("claude-code"),
            Verdict::Ok,
            "re-seeding must never overwrite a verdict the supervisor recorded"
        );
        assert_eq!(st.wired_agents().get("claude-code"), Some(&true));
    }

    /// One wired speaker of the format, so the request has one possible author.
    #[test]
    fn a_lone_speaker_is_named() {
        let st = WiringState::default();
        st.set_wired("claude-code", true);
        st.set_wired_format("claude-code", WireFormat::AnthropicMessages);
        st.set_wired("codex-cli", true);
        st.set_wired_format("codex-cli", WireFormat::OpenAiResponses);

        assert_eq!(
            st.sole_wired_agent_for(WireFormat::AnthropicMessages),
            Some("claude-code")
        );
        assert_eq!(
            st.sole_wired_agent_for(WireFormat::OpenAiResponses),
            Some("codex-cli")
        );
    }

    /// TWO speakers, and the answer is silence.
    ///
    /// This is the case the whole design turns on. Cline and Claude Code both
    /// speak the Anthropic Messages API, so on a host running both, naming
    /// either is a coin flip — and it would be a coin flip wearing the
    /// platform's `(org, source, agent_id)` join key, which is exactly the
    /// unfalsifiable attribution `unknown` exists to prevent.
    #[test]
    fn two_speakers_of_one_format_name_nobody() {
        let st = WiringState::default();
        st.set_wired("claude-code", true);
        st.set_wired_format("claude-code", WireFormat::AnthropicMessages);
        st.set_wired("cline", true);
        st.set_wired_format("cline", WireFormat::AnthropicMessages);

        assert_eq!(st.sole_wired_agent_for(WireFormat::AnthropicMessages), None);
    }

    /// An agent that is no longer wired is not a candidate.
    ///
    /// `set_wired_format` deliberately does not clear on unwire, so without the
    /// flag check an uninstalled agent would keep answering for a protocol it
    /// no longer speaks — and worse, would keep a live second agent from being
    /// the lone speaker.
    #[test]
    fn an_unwired_agent_does_not_speak() {
        let st = WiringState::default();
        st.set_wired_format("claude-code", WireFormat::AnthropicMessages);
        st.set_wired("claude-code", false);
        assert_eq!(st.sole_wired_agent_for(WireFormat::AnthropicMessages), None);

        st.set_wired("cline", true);
        st.set_wired_format("cline", WireFormat::AnthropicMessages);
        assert_eq!(
            st.sole_wired_agent_for(WireFormat::AnthropicMessages),
            Some("cline"),
            "the unwired agent must not block the one that is actually wired"
        );
    }

    /// Nothing wired for the format at all.
    #[test]
    fn no_speaker_names_nobody() {
        let st = WiringState::default();
        st.set_wired("claude-code", true);
        st.set_wired_format("claude-code", WireFormat::AnthropicMessages);
        assert_eq!(st.sole_wired_agent_for(WireFormat::OpenAiResponses), None);
    }

    /// `Unknown` is never attributable, however few agents are wired.
    ///
    /// It is the catch-all for every route the boundary does not capture
    /// (`GET /v1/models`, count_tokens, the batch endpoints), so "the sole agent
    /// speaking Unknown" would be a statement about the route table, not about
    /// an agent. Those routes emit no economics event anyway; refusing here
    /// keeps the rule true rather than true-by-accident.
    #[test]
    fn the_uncaptured_format_is_never_attributable() {
        let st = WiringState::default();
        st.set_wired("claude-code", true);
        st.set_wired_format("claude-code", WireFormat::Unknown);
        assert_eq!(st.sole_wired_agent_for(WireFormat::Unknown), None);
    }
}