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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! `openlatch boundary <status|enable|disable|explain>` — inspect and switch
//! the model-boundary listener.
//!
//! **`enable` / `disable` write config, and only config.** The agent's
//! `ANTHROPIC_BASE_URL` stays owned by the daemon: it writes the value after it
//! binds the pinned port and removes it when it lets go, which is what keeps
//! the agent config from ever naming a listener that does not exist. A command
//! that wrote that value by hand would be a second owner of the invariant, and
//! two owners is how the config came to point at a port nobody held.
//!
//! These commands existed as a documented non-feature until an operator with
//! `[boundary] enabled = false` in `config.toml` had no supported way back:
//! `init` never writes `true`, so the opt-out was a one-way door out of the
//! product's main capability, undone only by hand-editing TOML. Writing the
//! flag is not the same job as owning the wiring, and the second job stays
//! where it was.

use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::{BoundaryCommands, BoundaryToggleArgs};
use crate::error::{OlError, ERR_BOUNDARY_FINDING_NOT_FOUND};

/// Dispatch `openlatch boundary <sub>`.
pub fn run(cmd: &BoundaryCommands, output: &OutputConfig) -> Result<(), OlError> {
    match cmd {
        BoundaryCommands::Status => status(output),
        BoundaryCommands::Enable(args) => toggle(true, args, output),
        BoundaryCommands::Disable(args) => toggle(false, args, output),
        BoundaryCommands::Explain { finding_id } => explain(finding_id, output),
    }
}

/// `openlatch boundary enable|disable` — write `[boundary] enabled`, then offer
/// the restart that makes it real.
///
/// There is no hot switch on purpose. Binding 7600 and writing
/// `ANTHROPIC_BASE_URL` are startup invariants of the daemon
/// (`daemon::serve_with_listener`), so a running daemon cannot adopt the new
/// value without coming back up. Claiming otherwise would produce exactly the
/// divergence this whole area is being repaired for: a config that says one
/// thing and a process doing another.
fn toggle(enable: bool, args: &BoundaryToggleArgs, output: &OutputConfig) -> Result<(), OlError> {
    use std::io::{BufRead, IsTerminal, Write};

    let config_path = crate::config::openlatch_dir().join("config.toml");
    if !config_path.exists() {
        crate::config::ensure_config(crate::config::Config::defaults().port)?;
    }

    let before = crate::config::Config::load(None, None, false)
        .map(|c| c.boundary.enabled)
        .unwrap_or(true);
    let verb = if enable { "enabled" } else { "disabled" };

    crate::cli::header::print(
        output,
        &["boundary", if enable { "enable" } else { "disable" }],
    );

    if before == enable {
        // Idempotent, and deliberately not an early return: config and runtime
        // can disagree, and that disagreement is the thing worth fixing.
        output.print_substep(&format!("Model boundary already {verb} in config"));
    } else {
        crate::config::persist_boundary_enabled(&config_path, enable)?;
        output.print_step(&format!(
            "Model boundary {verb} in {}",
            config_path.display()
        ));
    }

    // Nothing to restart, nothing to reconcile.
    let daemon_up = crate::cli::commands::lifecycle::read_pid_file()
        .map(crate::cli::commands::lifecycle::is_process_alive)
        .unwrap_or(false);
    if !daemon_up {
        output.print_step("No daemon running — the change applies at the next start");
        emit_toggle_json(enable, true, false, true, output);
        return Ok(());
    }

    // Prompting requires someone to answer. A non-TTY that passed neither flag
    // gets the same treatment as `--no-restart`: the config is written, the
    // exit code says it is not in effect, and nothing hangs waiting on a stdin
    // that will never carry a keystroke.
    let interactive =
        std::io::stdin().is_terminal() && output.format == OutputFormat::Human && !output.quiet;
    let restart = if args.yes {
        true
    } else if args.no_restart || !interactive {
        false
    } else {
        eprint!("Restart the daemon now to apply? [y/N] ");
        let _ = std::io::stderr().flush();
        let mut answer = String::new();
        let _ = std::io::stdin().lock().read_line(&mut answer);
        matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
    };

    if !restart {
        output.print_substep(
            "Config updated — not in effect until the daemon restarts (run `openlatch restart`)",
        );
        emit_toggle_json(enable, true, false, false, output);
        // Config and runtime disagree. That is the definition of degraded, and
        // a script must be able to see it.
        crate::cli::report::record_exit_code(crate::cli::report::EXIT_DEGRADED);
        return Ok(());
    }

    crate::cli::commands::lifecycle::run_restart(output)?;

    // Measured, not assumed: the restart is only "applied" if the listener
    // state now matches what was just written.
    let cfg = crate::config::Config::load(None, None, false)?;
    // EVERY request plane, not the first one: a two-agent host where only
    // Claude Code came back up has not applied the change, and saying it has is
    // the "off is never a pass" failure in its most literal form.
    let in_effect = boundary_rows(&cfg).iter().all(|row| match row.state {
        BoundaryState::Disabled => !enable,
        BoundaryState::Wired | BoundaryState::Isolated => enable,
        _ => false,
    });
    if in_effect {
        output.print_step(&format!("Model boundary {verb} and in effect"));
    } else {
        output.print_substep(
            "Daemon restarted, but the boundary is not in the requested state — run \
             `openlatch doctor` for the reason",
        );
        crate::cli::report::record_exit_code(crate::cli::report::EXIT_DEGRADED);
    }
    emit_toggle_json(enable, true, true, in_effect, output);
    Ok(())
}

fn emit_toggle_json(
    enabled: bool,
    config_written: bool,
    restarted: bool,
    in_effect: bool,
    output: &OutputConfig,
) {
    if output.format != OutputFormat::Json {
        return;
    }
    output.print_json(&serde_json::json!({
        "enabled": enabled,
        "config_written": config_written,
        "restarted": restarted,
        "in_effect": in_effect,
        "exit_code": if in_effect { 0 } else { crate::cli::report::EXIT_DEGRADED },
    }));
}

/// Who owns the pinned boundary port right now. Read by `openlatch status` and
/// by `openlatch doctor`'s wiring-coherence check, which classify boundary
/// liveness from this signature probe rather than from any disk marker.
#[derive(Debug, PartialEq)]
pub(crate) enum PortOwnership {
    /// A live OpenLatch boundary answered with our status signature — safe.
    Owned,
    /// Something is listening but it is NOT our boundary (wrong/missing
    /// signature). Wiring the agent here would leak its provider credential.
    Foreign,
    /// Nothing is holding the port — the daemon isn't up yet. Covers both a
    /// refused connection and one that never got answered, because which of
    /// the two a closed loopback port produces is a property of the host; see
    /// `verify_port_ownership`.
    Unreachable,
}

/// Budget for the TCP connect leg alone. Deliberately far shorter than
/// `PROBE_TIMEOUT`: a live listener on loopback accepts in microseconds, so
/// 100ms is three orders of magnitude of headroom for the only question this
/// leg asks — is anything there. Keeping it separate is what stops the two
/// legs from stacking into a ~1s worst case on a listener that accepts and
/// then stalls. Same split, same values, as `openlatch-hook`'s
/// `CONNECT_TIMEOUT` / `TOTAL_TIMEOUT`.
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100);

/// Budget for the HTTP round-trip against the admin status endpoint.
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500);

/// GET the boundary's admin status endpoint.
///
/// The single place that knows the URL and the client configuration, because
/// `verify_port_ownership` and `probe_boundary` both need it and had already
/// drifted: the timeout was a named constant in one and a bare `500` literal
/// in the other. `None` is "no answer" — both callers treat a build failure
/// and a transport failure the same way, and neither can act on the
/// distinction.
fn get_admin_status(port: u16) -> Option<reqwest::blocking::Response> {
    let url = format!("http://127.0.0.1:{port}/admin/boundary/status");
    crate::egress::blocking_client_builder()
        .timeout(PROBE_TIMEOUT)
        .build()
        .ok()?
        .get(&url)
        .send()
        .ok()
}

/// Probe `http://127.0.0.1:{port}/admin/boundary/status` and classify who owns
/// the port. Ownership is proven by our JSON signature (`status` + `upstream`
/// keys) — reused from `boundary_status` so a foreign listener cannot forge it
/// by chance.
pub(crate) fn verify_port_ownership(port: u16) -> PortOwnership {
    // Liveness is decided by a raw TCP connect, deliberately BEFORE any HTTP,
    // and "could not connect" is `Unreachable` regardless of *why*.
    //
    // The previous version classified on reqwest's `is_connect()`, which is not
    // portable, for a reason worth recording because it is counter-intuitive:
    // the time a closed loopback port takes to report refused is a property of
    // the host, not of the protocol. Measured on Windows 11 with the firewall's
    // filter driver in the path, a closed 127.0.0.1 port answers
    // `ConnectionRefused` (WSAECONNREFUSED, os error 10061) only after ~2s of
    // SYN retries. Any probe on a sub-2s budget therefore never sees the
    // refusal — it sees its own timeout. reqwest surfaced that as
    // `is_connect() == false` / `is_timeout() == true`, so the closed port fell
    // through to the catch-all "no answer" case and was called `Foreign`.
    //
    // The user-visible result was not subtle: on every Windows host with the
    // daemon simply not running — the normal idle state — `openlatch status`
    // printed the boundary as "failed" rather than "down"
    // (`status.rs::boundary_state_from_ownership`) and `doctor` diagnosed a
    // port conflict that did not exist. It passed CI throughout because Linux
    // runners refuse instantly and stay inside the budget.
    //
    // Collapsing refused and timed-out into one verdict is what makes this
    // robust rather than merely re-tuned: the target is loopback, where a live
    // listener accepts in microseconds, so a connect that has neither been
    // accepted nor refused within the budget is not holding the port. The one
    // counter-case is a local listener with a saturated backlog, which is
    // pathological and still a refusal — "down" instead of "failed", both of
    // which decline. Only `Owned`, which requires our JSON signature below,
    // ever permits anything.
    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    if std::net::TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).is_err() {
        return PortOwnership::Unreachable;
    }

    // Something is listening (proven above), so no answer here means it did
    // not answer *our* protocol.
    let Some(resp) = get_admin_status(port) else {
        return PortOwnership::Foreign;
    };
    if !resp.status().is_success() {
        return PortOwnership::Foreign;
    }
    match resp.json::<serde_json::Value>() {
        Ok(v) if v.get("status").is_some() && v.get("upstream").is_some() => PortOwnership::Owned,
        _ => PortOwnership::Foreign,
    }
}

/// `openlatch boundary status` — say what the boundary is actually doing.
///
/// Classified, not probed. This used to call `probe_boundary` alone, so a host
/// with `[boundary] enabled = false` was told `Boundary: down (pinned port
/// 7600)` and advised to `openlatch start` — a command that will not bind a
/// listener the config has switched off. The operator runs it, nothing changes,
/// and the one command named after the subsystem is the one that cannot explain
/// it. [`classify_boundary`] is the same predicate `doctor` and `status` use;
/// three commands answering one question now answer it identically.
pub fn status(output: &OutputConfig) -> Result<(), OlError> {
    let cfg = crate::config::Config::load(None, None, false)?;
    let port = cfg.boundary.port;
    // One row per request plane. The command answers for the HOST, so the exit
    // code and the headline come from the worst of them — a broken Codex plane
    // must not hide behind a green Claude one.
    let rows = boundary_rows(&cfg);
    let probe = probe_boundary(port);

    // Same three tiers as every other diagnostic: switched off warns, broken
    // fails, working is silent about itself.
    let exit = match boundary_severity(&worst_row(&rows).state) {
        0 => 0,
        2 => 1,
        _ => crate::cli::report::EXIT_DEGRADED,
    };
    crate::cli::report::record_exit_code(exit);

    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "port": port,
            "state": worst_row(&rows).state.label(),
            // The RESOLVED per-format map, rendered from CONFIG so it answers
            // with no daemon running — a stock host's map is empty and printing
            // the raw one would print nothing where a host today prints its
            // upstream. These three entries ARE the three-step precedence.
            "upstream": crate::boundary::wire_format::WireFormat::ALL
                .iter()
                .map(|f| (f.as_str().to_string(), serde_json::json!(cfg.boundary.upstream_for(*f))))
                .collect::<serde_json::Map<_, _>>(),
            "classification": format!("{:?}", worst_row(&rows).state),
            "enabled": cfg.boundary.enabled,
            "owns_agent_wiring": cfg.boundary.owns_agent_wiring(),
            "wired_to": worst_row(&rows).wired,
            // The per-agent breakdown the top-level fields summarise. Wiring is
            // per agent now, and a script that has to know WHICH plane is down
            // reads this rather than re-deriving it.
            "agents": rows
                .iter()
                .filter(|r| !r.agent.is_empty())
                .map(|r| serde_json::json!({
                    "agent": r.agent,
                    "state": r.state.label(),
                    "classification": format!("{:?}", r.state),
                    "wired_to": r.wired,
                }))
                .collect::<Vec<_>>(),
            "up": probe.is_some(),
            "detail": probe,
            "exit_code": exit,
        }));
        return Ok(());
    }

    crate::cli::header::print(output, &["boundary status"]);

    // The remedy follows the classification. Sending every non-working state to
    // `openlatch start` is what made this command useless on the one config it
    // was most often run against.
    //
    // One block per request plane: on a two-agent host the states genuinely
    // differ, and collapsing them prints one agent's remedy at the other's
    // problem.
    let multi = rows.len() > 1;
    for row in &rows {
        let wired = row.wired.clone();
        let (line, remedy): (String, Option<String>) = match &row.state {
            BoundaryState::Disabled => (
                "Boundary: disabled in config — model calls bypass OpenLatch".to_string(),
                Some("Run `openlatch boundary enable` to turn it back on.".to_string()),
            ),
            BoundaryState::Isolated => (
                format!("Boundary: isolated instance on port {port}"),
                Some(format!(
                    "This instance does not touch the machine-global agent config. Route a session \
                     through it with:\n    ANTHROPIC_BASE_URL=http://127.0.0.1:{port} claude"
                )),
            ),
            BoundaryState::Wired => (
                format!(
                    "Boundary: up on port {port}, agent wired to {}",
                    wired.as_deref().unwrap_or("it")
                ),
                None,
            ),
            BoundaryState::WiredButDown => (
                format!("Boundary: agent is wired to 127.0.0.1:{port} but nothing is listening"),
                Some(
                    "Model calls fail with ECONNREFUSED. Run `openlatch start` to bring the \
                     listener up, or `openlatch stop` to clear the wiring and go direct."
                        .to_string(),
                ),
            ),
            BoundaryState::WiredToForeign => (
                format!("Boundary: 127.0.0.1:{port} is held by a process that is NOT OpenLatch"),
                Some(format!(
                    "The agent is wired to it, so your provider API key is going to that process. \
                     Identify it (lsof -i :{port}), stop it, then run `openlatch restart`."
                )),
            ),
            BoundaryState::PreflightFailed(why) => (
                format!("Boundary: up on port {port}, preflight FAILED — {why}"),
                Some(
                    "The agent was left unwired on purpose: model calls go direct and keep \
                     working, but nothing is captured. Fix reachability to the provider; the \
                     daemon re-wires itself as soon as the check passes."
                        .to_string(),
                ),
            ),
            BoundaryState::PreflightPending => (
                format!("Boundary: up on port {port}, preflight still running"),
                Some("The agent is wired once it passes. Re-run this in a moment.".to_string()),
            ),
            BoundaryState::UpUnwired => (
                format!("Boundary: up on port {port} but the agent is not wired to it"),
                Some("Run `openlatch restart` to re-wire.".to_string()),
            ),
            BoundaryState::Down => (
                format!("Boundary: enabled in config, nothing listening on port {port}"),
                Some("Run `openlatch start`.".to_string()),
            ),
            BoundaryState::ForeignIdle => (
                format!("Boundary: 127.0.0.1:{port} is held by another process"),
                Some(format!(
                    "The agent is not wired to it, but the next `openlatch start` will refuse to \
                     bind. Identify it with `lsof -i :{port}`."
                )),
            ),
        };
        if multi {
            eprintln!("  [{}]", row.display_name);
        }
        eprintln!("  {line}");
        if let Some(remedy) = remedy {
            eprintln!("  {remedy}");
        }
    }

    if let Some(v) = probe.as_ref() {
        // The daemon reports an OBJECT now, one entry per wire format. A
        // `.as_str()` read here would silently print nothing — a diagnostic
        // going quiet is exactly the failure this line exists to prevent.
        if let Some(up) = v.get("upstream").and_then(|x| x.as_object()) {
            for (fmt, base) in up {
                if let Some(base) = base.as_str() {
                    eprintln!("  Upstream ({fmt}): {base}");
                }
            }
        }
        // Printed only when the pair is in force. A ChatGPT-plan Codex turn
        // goes here and to none of the bases above, so leaving it out would
        // make this diagnostic name every destination but the one in use.
        if let Some(base) = v.get("upstream_chatgpt").and_then(|x| x.as_str()) {
            eprintln!("  Upstream (openai-responses, ChatGPT plan): {base}");
        }
        if let Some(f) = v.get("pass_through_failures").and_then(|x| x.as_u64()) {
            eprintln!("  Pass-through failures: {f}");
        }
    }
    Ok(())
}

/// `openlatch boundary explain <finding_id>` — print a churning prefix block
/// LOCALLY (C-10b). The block content lives only in the on-disk retention store
/// on the originating host and is **never** emitted on the wire; this is the one
/// path that resolves a `finding_id` back to its content.
pub fn explain(finding_id: &str, output: &OutputConfig) -> Result<(), OlError> {
    let record = crate::boundary::retention::load(finding_id).ok_or_else(|| {
        OlError::new(
            ERR_BOUNDARY_FINDING_NOT_FOUND,
            format!("no local churn finding '{finding_id}'"),
        )
        .with_suggestion(
            "Findings resolve only on the host that produced them, and expire from the bounded \
             local store. Check the id from the `ai.openlatch.prefix.finding_id` field.",
        )
    })?;

    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "finding_id": record.finding_id,
            "captured_at": record.captured_at,
            "churn_layer": record.churn_layer,
            "churn_class": record.churn_class,
            "divergence_offset": record.divergence_offset,
            "churn_byte_len": record.churn_byte_len,
            "churn_block_index": record.churn_block_index,
            "block": record.block,
        }));
    } else {
        crate::cli::header::print(output, &["boundary explain"]);
        eprintln!("  finding      : {}", record.finding_id);
        eprintln!("  captured     : {}", record.captured_at);
        eprintln!("  layer        : {}", record.churn_layer);
        eprintln!("  class        : {}", record.churn_class);
        eprintln!(
            "  offset/len   : {} / {} (block #{})",
            record.divergence_offset, record.churn_byte_len, record.churn_block_index
        );
        eprintln!("  block (local, never emitted):");
        println!("{}", record.block);
    }
    Ok(())
}

/// Blocking GET of the boundary's admin status endpoint. `None` when the
/// listener is not up.
pub fn probe_boundary(port: u16) -> Option<serde_json::Value> {
    let resp = get_admin_status(port)?;
    if !resp.status().is_success() {
        return None;
    }
    resp.json().ok()
}

/// What the model boundary is actually doing, as one classification.
///
/// `status` and `doctor` used to answer this question separately: `doctor`
/// combined config, agent wiring and a live probe, while `status` classified on
/// port ownership alone and never read `boundary.enabled`. With the boundary
/// switched off in config and an unrelated process on 7600, `status` printed
///
/// ```text
/// Boundary:    FAILED (port held by a non-OpenLatch process — agents misconfigured/exposed) (port 7600)
/// ```
///
/// seconds after the daemon logged `agent boundary wiring removed — agents
/// connect to the provider directly`. No agent was wired to that port: a
/// security-shaped alarm raised on a configuration that was deliberately, and
/// verifiably, safe. One classifier, consumed by both commands, is what makes
/// that disagreement impossible.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum BoundaryState {
    /// `[boundary] enabled = false`. Agents talk to the provider directly by
    /// design; whoever holds the port is not our business.
    Disabled,
    /// A non-default boundary port: this instance deliberately does not touch
    /// the machine-global agent config, so wiring and listening are not
    /// supposed to line up.
    Isolated,
    /// Agent wired to our listener, and our listener answered. The good state.
    Wired,
    /// Agent wired, nothing listening — model calls fail with ECONNREFUSED.
    WiredButDown,
    /// Agent wired to a port held by someone else. The provider credential is
    /// going to that process. The real security alarm.
    WiredToForeign,
    /// Listener up, agent unwired because the preflight round trip failed. Not
    /// broken for the user (calls go direct) but nothing is captured.
    PreflightFailed(String),
    /// Listener up, preflight still running — the wiring lands when it passes.
    PreflightPending,
    /// Listener up, agent unwired for some other reason.
    UpUnwired,
    /// Not wired, nothing listening — consistent, and what `stop` leaves.
    Down,
    /// Not wired, and the port belongs to another process. Consistent for us,
    /// but it is why the next `start` will refuse to bind.
    ForeignIdle,
}

impl BoundaryState {
    /// The one-word label the `status` dashboard prints.
    pub(crate) fn label(&self) -> &'static str {
        match self {
            BoundaryState::Disabled => "disabled",
            BoundaryState::Isolated => "isolated",
            BoundaryState::Wired => "up",
            BoundaryState::WiredButDown => "down",
            BoundaryState::WiredToForeign => "failed",
            BoundaryState::PreflightFailed(_) => "preflight-failed",
            BoundaryState::PreflightPending => "preflight-pending",
            BoundaryState::UpUnwired => "unwired",
            BoundaryState::Down => "down",
            BoundaryState::ForeignIdle => "down",
        }
    }
}

/// One request plane's boundary picture: what the agent points at, and what
/// that means.
pub(crate) struct AgentBoundary {
    /// The agent's wire type, `""` on the no-agent row below.
    pub agent: &'static str,
    /// The human label a multi-agent rendering prefixes its line with.
    pub display_name: &'static str,
    /// The endpoint it names, when that endpoint is ours.
    pub wired: Option<String>,
    /// What that adds up to.
    pub state: BoundaryState,
}

/// Every request plane on this host, classified — in detection order.
///
/// One row per detected agent that HAS a request plane, because wiring is per
/// agent: one plane can be wired and green while another's round trip fails,
/// and a single row would report one of them for both.
///
/// **A host with no request plane still gets exactly one row.** The boundary's
/// own state — switched off in config, nothing listening, the port held by
/// somebody else — is worth reporting on a host with no agent installed at all,
/// and it is the state `boundary status` is most often run against. Returning
/// an empty list there is how the one command named after the subsystem goes
/// silent about it.
pub(crate) fn boundary_rows(cfg: &crate::config::Config) -> Vec<AgentBoundary> {
    let mut rows: Vec<AgentBoundary> = crate::hooks::detect_agents()
        .into_iter()
        .filter(|a| a.binding.boundary_wiring().is_some())
        .map(|a| {
            let wired = read_agent_wiring(&*a.binding);
            let state = classify_boundary(cfg, a.agent_type(), wired.as_deref());
            AgentBoundary {
                agent: a.agent_type(),
                display_name: a.binding.display_name(),
                wired,
                state,
            }
        })
        .collect();
    if rows.is_empty() {
        rows.push(AgentBoundary {
            // Matches no key in the listener's per-agent maps by construction,
            // which is the honest answer: there is no agent to have a verdict.
            agent: "",
            display_name: "The agent",
            wired: None,
            state: classify_boundary(cfg, "", None),
        });
    }
    rows
}

/// How bad a state is, on the three-tier scale every diagnostic here uses:
/// 0 working, 1 switched off / not doing anything, 2 broken.
///
/// A host is only as healthy as its worst plane. Reporting the first agent's
/// state would let a broken Codex plane hide behind a green Claude one.
pub(crate) fn boundary_severity(state: &BoundaryState) -> u8 {
    match state {
        BoundaryState::Wired | BoundaryState::Isolated => 0,
        BoundaryState::Disabled
        | BoundaryState::PreflightPending
        | BoundaryState::UpUnwired
        | BoundaryState::Down => 1,
        BoundaryState::WiredButDown
        | BoundaryState::WiredToForeign
        | BoundaryState::PreflightFailed(_)
        | BoundaryState::ForeignIdle => 2,
    }
}

/// The worst row, which is the host's answer.
pub(crate) fn worst_row(rows: &[AgentBoundary]) -> &AgentBoundary {
    rows.iter()
        .max_by_key(|r| boundary_severity(&r.state))
        .expect("boundary_rows never returns an empty list")
}

/// Classify the boundary for ONE agent, from config, that agent's wiring, and a
/// live probe.
///
/// `wired` is the endpoint the agent names when — and only when — it points at
/// our loopback; a customer's corporate gateway is not our wiring. Read it with
/// [`read_agent_wiring`], never by reaching for one convention's key.
///
/// **`agent` is not decoration.** The listener reports `preflight` and
/// `preflight_error` as objects keyed by agent type, because two agents share
/// one listener and are probed in two different formats. Reading them without
/// the key returns `None` on every host, the match falls to
/// [`BoundaryState::UpUnwired`], and every `PreflightFailed` / `PreflightPending`
/// host renders as merely unwired — with no compile error anywhere.
pub(crate) fn classify_boundary(
    cfg: &crate::config::Config,
    agent: &'static str,
    wired: Option<&str>,
) -> BoundaryState {
    if !cfg.boundary.enabled {
        return BoundaryState::Disabled;
    }
    if !cfg.boundary.owns_agent_wiring() {
        return BoundaryState::Isolated;
    }

    let port = cfg.boundary.port;
    match (wired, verify_port_ownership(port)) {
        (Some(_), PortOwnership::Owned) => BoundaryState::Wired,
        (Some(_), PortOwnership::Unreachable) => BoundaryState::WiredButDown,
        (Some(_), PortOwnership::Foreign) => BoundaryState::WiredToForeign,
        (None, PortOwnership::Owned) => {
            // "Up but unwired" stopped being a single condition once the wiring
            // was gated on a live round trip: the daemon leaves the agent
            // unwired ON PURPOSE when the boundary cannot forward, and telling
            // that operator to restart sends them in a circle. The listener
            // knows which case it is; ask it.
            let live = probe_boundary(port);
            match live
                .as_ref()
                .and_then(|v| v.get("preflight"))
                .and_then(|v| v.get(agent))
                .and_then(|v| v.as_str())
            {
                Some("failed") => BoundaryState::PreflightFailed(
                    live.as_ref()
                        .and_then(|v| v.get("preflight_error"))
                        .and_then(|v| v.get(agent))
                        .and_then(|v| v.as_str())
                        .unwrap_or("no round trip to the provider completed")
                        .to_string(),
                ),
                Some("pending") => BoundaryState::PreflightPending,
                _ => BoundaryState::UpUnwired,
            }
        }
        (None, PortOwnership::Unreachable) => BoundaryState::Down,
        (None, PortOwnership::Foreign) => BoundaryState::ForeignIdle,
    }
}

/// Is this agent wired to us, and to what?
///
/// **THE one convention reader.** Four callers ask this question — `doctor`'s
/// Boundary check, `boundary enable/disable/status`, `openlatch stop`'s
/// teardown probe and the `status` dashboard — and all four call here. Four
/// hand-written copies is how they come to disagree, which is the failure the
/// *one question, one set of detectors* invariant exists to stop.
///
/// `None` for an agent with no request plane, and `None` for an agent whose
/// endpoint is the customer's own: only OUR loopback counts as our wiring, on
/// both conventions.
pub(crate) fn read_agent_wiring(
    binding: &dyn crate::hooks::binding::AgentBinding,
) -> Option<String> {
    use crate::hooks::binding::EndpointConvention;
    match binding.boundary_wiring()?.endpoint {
        // The leaf reads the file, not the variable name.
        EndpointConvention::EnvVars { .. } => read_boundary_base_url(&binding.hook_config_path()),
        EndpointConvention::TomlProvider { provider_name, .. } => {
            crate::hooks::codex_cli::read_provider_base_url(
                &crate::hooks::codex_cli::config_toml_path(&binding.config_dir()),
                provider_name,
            )
        }
    }
}

/// Read `env.ANTHROPIC_BASE_URL` from the agent settings, but only when it is
/// OUR loopback URL — a customer's corporate gateway is not our wiring and must
/// not be reported as such.
pub(crate) fn read_boundary_base_url(settings_path: &std::path::Path) -> Option<String> {
    let raw = std::fs::read_to_string(settings_path).ok()?;
    let parsed = crate::hooks::jsonc::parse_settings_value(&raw).ok()?;
    let url = parsed
        .get("env")?
        .get("ANTHROPIC_BASE_URL")?
        .as_str()?
        .to_string();
    reqwest::Url::parse(url.trim())
        .ok()
        .filter(|u| u.host_str() == Some("127.0.0.1"))
        .map(|_| url)
}

#[cfg(test)]
mod tests {
    use super::{verify_port_ownership, PortOwnership};

    #[test]
    fn verify_port_ownership_refuses_closed_and_foreign_ports() {
        // Connection-refused branch: nothing is listening ⇒ Unreachable
        // (enable will tell the user to start the daemon first).
        //
        // This half is the platform regression gate, and it only ever fires
        // off-CI: Linux refuses a closed loopback port instantly, Windows can
        // take ~2s, so a budgeted probe there times out instead of seeing the
        // refusal — see the comment on the raw-TCP probe in
        // `verify_port_ownership`. Anything that reintroduces a
        // reason-sensitive classification (`is_connect()`, or splitting
        // timed-out back out of `Unreachable`) turns this red on Windows and
        // green on the runners.
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let closed = l.local_addr().unwrap().port();
        drop(l);
        assert_eq!(verify_port_ownership(closed), PortOwnership::Unreachable);

        // Wrong-signature branch: a NON-OpenLatch listener answers 200 with a
        // body lacking our `status`/`upstream` keys ⇒ Foreign (enable refuses,
        // so no provider credential is ever pointed at it).
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let foreign = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            use std::io::{Read, Write};
            for mut s in listener.incoming().flatten() {
                let mut buf = [0u8; 1024];
                let _ = s.read(&mut buf);
                let body = br#"{"foo":"bar"}"#;
                let head = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                     Content-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                let _ = s.write_all(head.as_bytes());
                let _ = s.write_all(body);
                let _ = s.flush();
            }
        });
        // Give the listener a moment to be ready before probing.
        std::thread::sleep(std::time::Duration::from_millis(50));
        assert_eq!(verify_port_ownership(foreign), PortOwnership::Foreign);
    }

    /// The #165 regression: with `[boundary] enabled = false` and an unrelated
    /// process on the pinned port, `status` printed
    /// `FAILED (port held by a non-OpenLatch process — agents misconfigured/exposed)`
    /// seconds after the daemon logged that it had removed the agent wiring. No
    /// agent was pointed at that port. The classifier must short-circuit on the
    /// config switch and never probe the port at all — so this test can assert
    /// it without any listener, on a port nothing is bound to.
    #[test]
    fn disabled_in_config_short_circuits_before_any_probe() {
        use crate::cli::commands::boundary::{classify_boundary, BoundaryState};

        let mut cfg = crate::config::Config::defaults();
        cfg.boundary.enabled = false;

        assert_eq!(
            classify_boundary(&cfg, "claude-code", None),
            BoundaryState::Disabled
        );
        // Even a wired-looking agent config cannot turn a disabled boundary
        // into an alarm: the daemon does not bind, so nothing of ours is there.
        assert_eq!(
            classify_boundary(&cfg, "claude-code", Some("http://127.0.0.1:7600")),
            BoundaryState::Disabled
        );
        assert_eq!(BoundaryState::Disabled.label(), "disabled");
    }

    /// A non-default boundary port means the instance never touches the
    /// machine-global agent config, so wiring and listening are not supposed to
    /// line up — checked before the probe for the same reason.
    #[test]
    fn isolated_instance_short_circuits_before_any_probe() {
        use crate::cli::commands::boundary::{classify_boundary, BoundaryState};

        let mut cfg = crate::config::Config::defaults();
        cfg.boundary.enabled = true;
        cfg.boundary.port = crate::boundary::default_boundary_port() + 1;

        assert_eq!(
            classify_boundary(&cfg, "claude-code", None),
            BoundaryState::Isolated
        );
    }
}