openlatch-client 0.1.18

OpenLatch runtime enforcement node — the capture-and-enforce client for the AI Operations Platform
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
/// Agent hook detection and installation.
///
/// Public API:
/// - [`detect_agent`] — detect which (if any) AI agent is installed
/// - [`install_hooks`] — write OpenLatch HTTP hook entries into the agent's config
/// - [`remove_hooks`] — remove all OpenLatch-owned hook entries
///
/// # Module structure
///
/// - `claude_code` — path detection and hook entry building for Claude Code
/// - `jsonc` — JSONC-preserving string surgery on `settings.json`
pub mod atomic;
pub mod binding;
pub mod bindings;
pub mod claude_code;
pub mod health;
pub mod jsonc;
pub mod staging;

use std::path::PathBuf;

use crate::core::hook_state::hmac::compute_entry_hmac;
use crate::core::hook_state::key::HmacKeyStore;
use crate::core::hook_state::marker::OpenlatchMarker;
use crate::core::hook_state::{self, HookStateFile, StateEntry};
use crate::error::{OlError, ERR_HOOK_AGENT_NOT_FOUND, ERR_HOOK_BINARY_UNRESOLVABLE};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// A detected AI agent with all paths needed for hook installation.
#[derive(Debug, Clone)]
pub enum DetectedAgent {
    /// Claude Code was found at the given directory.
    ClaudeCode {
        /// Path to the Claude Code config directory (e.g. `~/.claude/`).
        claude_dir: PathBuf,
        /// Path to `settings.json` inside the config directory.
        settings_path: PathBuf,
    },
}

/// The result of a successful [`install_hooks`] call.
#[derive(Debug)]
pub struct HookInstallResult {
    /// Per-hook-event status showing whether the entry was added or replaced.
    pub entries: Vec<HookEntryStatus>,
}

/// Status of a single hook event entry after installation.
#[derive(Debug)]
pub struct HookEntryStatus {
    /// The hook event type (e.g. `"PreToolUse"`, `"UserPromptSubmit"`, `"Stop"`).
    pub event_type: String,
    /// Whether the entry was newly added or replaced an existing OpenLatch entry.
    pub action: HookAction,
}

/// Whether a hook entry was newly created or replaced an existing one.
#[derive(Debug, Clone, PartialEq)]
pub enum HookAction {
    /// A new hook entry was appended to the array.
    Added,
    /// An existing OpenLatch-owned entry was replaced (idempotent re-install).
    Replaced,
}

/// Resolve the absolute path to the `openlatch-hook` binary that hook
/// configs should invoke.
///
/// Order of precedence:
///
/// 1. `OPENLATCH_HOOK_BIN` env var (override for tests, custom installs).
/// 2. `<openlatch_dir>/bin/openlatch-hook[.exe]` — the canonical install
///    location, populated by [`staging::stage_hook_binary`], which `init` and
///    `doctor --fix` both call before writing any hook. Resolved through
///    [`crate::config::openlatch_dir`] so it honours `$OPENLATCH_DIR`, exactly
///    like the side that writes it.
/// 3. `openlatch-hook[.exe]` next to the current running binary (typical
///    during `cargo install` or portable tarball extractions).
/// 4. Bare `"openlatch-hook"` as a last resort — relies on the hook
///    subprocess resolving it via `PATH`.
///
/// Step 4 is a path that may not exist, and writing it into a hook command is
/// what produced the #165 outage: `/bin/sh: openlatch-hook: command not found`
/// on every tool call, invisible because the hook fails open. [`install_hooks`]
/// therefore refuses any resolution that is not an existing file — callers must
/// stage the binary first rather than let this fall through.
pub fn resolve_hook_binary_path() -> PathBuf {
    let bin_name = if cfg!(windows) {
        "openlatch-hook.exe"
    } else {
        "openlatch-hook"
    };

    if let Ok(override_path) = std::env::var("OPENLATCH_HOOK_BIN") {
        if !override_path.is_empty() {
            return PathBuf::from(override_path);
        }
    }

    // `config::openlatch_dir()`, not `home/.openlatch`: the staging side writes
    // into `<ol_dir>/bin`, and `<ol_dir>` honours `$OPENLATCH_DIR` (and resolves
    // under `%APPDATA%` on Windows). Hardcoding the home-relative path here made
    // the two disagree on any non-default directory — the resolver looked in a
    // directory nothing had ever staged into, and fell through to the bare name.
    let candidate = crate::config::openlatch_dir().join("bin").join(bin_name);
    if candidate.exists() {
        return candidate;
    }

    if let Ok(current_exe) = std::env::current_exe() {
        if let Some(dir) = current_exe.parent() {
            let candidate = dir.join(bin_name);
            if candidate.exists() {
                return candidate;
            }
        }
    }

    PathBuf::from(bin_name)
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Detect which AI agent (if any) is installed on this machine.
///
/// Currently supports Claude Code only. Additional agents will be added in M4.
///
/// # Errors
///
/// Returns `OL-1400` if no supported AI agent is detected.
pub fn detect_agent() -> Result<DetectedAgent, OlError> {
    claude_code::detect()
        .map(|claude_dir| DetectedAgent::ClaudeCode {
            settings_path: claude_code::settings_json_path(&claude_dir),
            claude_dir,
        })
        .ok_or_else(|| {
            OlError::new(ERR_HOOK_AGENT_NOT_FOUND, "No AI agents detected")
                .with_suggestion("Install Claude Code (https://claude.ai/download) and try again.")
                .with_docs("https://docs.openlatch.ai/errors/OL-1400")
        })
}

/// Install OpenLatch HTTP hook entries into the detected agent's config.
///
/// The three hook events written are `PreToolUse`, `UserPromptSubmit`, and `Stop`.
/// Re-running this function is idempotent: existing OpenLatch entries are replaced
/// rather than duplicated. Hooks from other tools are never touched.
///
/// # Arguments
///
/// - `agent`: the agent returned by [`detect_agent`]
/// - `port`: the daemon's listen port (written into each hook URL)
/// - `token`: the bearer token value — the *env var name* `OPENLATCH_TOKEN` is
///   written into settings.json; the actual token is stored separately
///
/// # Errors
///
/// - `OL-1401` if settings.json cannot be read or written.
/// - `OL-1402` if settings.json contains malformed JSONC.
/// - `OL-1404` if [`resolve_hook_binary_path`] does not resolve to an existing
///   file. settings.json is left untouched: writing a command that cannot
///   resolve is worse than not writing one.
pub fn install_hooks(
    agent: &DetectedAgent,
    port: u16,
    token: &str,
) -> Result<HookInstallResult, OlError> {
    match agent {
        DetectedAgent::ClaudeCode { settings_path, .. } => {
            const TOKEN_ENV_VAR: &str = "OPENLATCH_TOKEN";
            const PORT_ENV_VAR: &str = "OPENLATCH_PORT";
            // 9 hook-lifecycle events plus 3 config-plane events
            // (ConfigChange, InstructionsLoaded, FileChanged) the daemon
            // routes into `src/daemon/config_monitor/` for native-hook +
            // FS-watcher dedup.
            const EVENT_TYPES: [&str; 12] = [
                "PreToolUse",
                "PostToolUse",
                "UserPromptSubmit",
                "Notification",
                "Stop",
                "SubagentStop",
                "PreCompact",
                "SessionStart",
                "SessionEnd",
                "ConfigChange",
                "InstructionsLoaded",
                "FileChanged",
            ];

            let openlatch_dir = crate::config::openlatch_dir();
            let hook_bin = resolve_hook_binary_path();

            // The command we are about to write into 12 hook entries must point
            // at a binary that exists. `resolve_hook_binary_path()` ends in a
            // bare `"openlatch-hook"` that relies on the agent's PATH, and when
            // that name is not on it every hook on the machine dies with exit
            // 127 — silently, because the hook fails open. Callers stage the
            // binary first (`hooks::staging::stage_hook_binary`); this is the
            // post-condition that makes "an install that cannot resolve its own
            // hook binary" impossible to write rather than merely unlikely.
            if !hook_bin.is_file() {
                return Err(OlError::new(
                    ERR_HOOK_BINARY_UNRESOLVABLE,
                    format!(
                        "Refusing to install hooks: '{}' is not an existing file",
                        hook_bin.display()
                    ),
                )
                .with_suggestion(
                    "Run 'openlatch doctor --fix' to stage the hook binary, or point \
                     OPENLATCH_HOOK_BIN at an existing one.",
                ));
            }

            let key_store = HmacKeyStore::new(&openlatch_dir);
            let hmac_key = key_store.load_or_create()?;

            let token_fp = crate::core::hook_state::key::key_fingerprint(token.as_bytes());
            let settings_path_hash = hook_state::hash_settings_path(settings_path);

            let mut entries_with_markers: Vec<(String, serde_json::Value, String)> = Vec::new();
            for &et in &EVENT_TYPES {
                let entry_id = uuid::Uuid::now_v7().to_string();
                let mut marker = OpenlatchMarker::new(entry_id.clone());

                let mut entry =
                    claude_code::build_hook_entry(et, port, TOKEN_ENV_VAR, &hook_bin, &marker);

                let hmac_value = compute_entry_hmac(&entry, &hmac_key)?;
                marker = marker.with_hmac(hmac_value.clone());

                let marker_value =
                    serde_json::to_value(&marker).expect("OpenlatchMarker serializes");
                entry["_openlatch"] = marker_value;

                entries_with_markers.push((et.to_string(), entry, entry_id));
            }

            let jsonc_entries: Vec<(String, serde_json::Value)> = entries_with_markers
                .iter()
                .map(|(et, entry, _)| (et.clone(), entry.clone()))
                .collect();

            let token_owned = token.to_string();
            let actions = std::cell::RefCell::new(Vec::new());

            atomic::atomic_rewrite_jsonc(settings_path, |root| {
                let a = jsonc::insert_hook_entries_cst(root, &jsonc_entries)?;
                jsonc::set_env_var_cst(root, TOKEN_ENV_VAR, &token_owned)?;
                // Pin the port too, not just the token.
                //
                // The hook resolves its port as OPENLATCH_PORT (its own env,
                // populated by the agent from this settings block) ->
                // <openlatch_dir>/daemon.port -> 7443. OPENLATCH_DIR is
                // deliberately NOT in a hook entry's allowedEnvVars, so a
                // daemon on a non-default directory is unreachable by the
                // middle step: the hook reads the DEFAULT directory's port
                // file and connects to the wrong daemon, or none at all.
                // Because the hook fails open — prints `{}`, exits 0, spools
                // to fallback.jsonl — the whole install looks healthy while
                // every event is dropped.
                //
                // Writing the concrete port here removes the dependency on
                // directory discovery entirely. It is already declared in each
                // entry's allowedEnvVars, so it reaches the subprocess.
                jsonc::set_env_var_cst(root, PORT_ENV_VAR, &port.to_string())?;
                *actions.borrow_mut() = a;
                Ok(())
            })?;

            let actions = actions.into_inner();

            let mut state = HookStateFile::load(&openlatch_dir)?
                .unwrap_or_else(|| HookStateFile::new("kid-01".into()));

            for (et, entry, entry_id) in &entries_with_markers {
                let hmac_val = entry["_openlatch"]["hmac"]
                    .as_str()
                    .map(str::to_string)
                    .unwrap_or_default();

                state.upsert_entry(StateEntry {
                    id: entry_id.clone(),
                    agent: "claude-code".into(),
                    settings_path_hash: settings_path_hash.clone(),
                    hook_event: et.clone(),
                    expected_entry_hmac: hmac_val,
                    daemon_port_at_install: port,
                    daemon_token_fp: token_fp.clone(),
                    v: 1,
                });
            }

            if let Err(e) = state.save(&openlatch_dir) {
                tracing::warn!(
                    code = crate::error::ERR_STATE_FILE_WRITE_FAILED,
                    error = %e,
                    "failed to write hook state file — hooks installed but state file out of sync"
                );
            }

            let entries = EVENT_TYPES
                .iter()
                .zip(actions)
                .map(|(&et, action)| HookEntryStatus {
                    event_type: et.to_string(),
                    action,
                })
                .collect();

            Ok(HookInstallResult { entries })
        }
    }
}

/// Remove all OpenLatch-owned hook entries from the detected agent's config.
///
/// Entries carrying the OpenLatch ownership marker (either the legacy
/// `"_openlatch": true` boolean or the current tamper-evident object) are
/// removed. Hooks from other tools are never touched.
///
/// # Errors
///
/// - `OL-1401` if settings.json cannot be read or written.
/// - `OL-1402` if settings.json contains malformed JSONC.
pub fn remove_hooks(agent: &DetectedAgent) -> Result<(), OlError> {
    match agent {
        DetectedAgent::ClaudeCode { settings_path, .. } => {
            if !settings_path.exists() {
                return Ok(());
            }

            atomic::atomic_rewrite_jsonc(settings_path, |root| {
                jsonc::remove_owned_entries_cst(root)
            })?;

            Ok(())
        }
    }
}

// ---------------------------------------------------------------------------
// Model-boundary config wiring (D-07 / D-01)
// ---------------------------------------------------------------------------

/// Env var name Claude Code reads for the model-provider base URL.
pub const ANTHROPIC_BASE_URL_ENV: &str = "ANTHROPIC_BASE_URL";
/// Env var name Claude Code reads for extra static request headers.
/// Newline-separated `Name: Value` entries (Anthropic SDK convention).
pub const ANTHROPIC_CUSTOM_HEADERS_ENV: &str = "ANTHROPIC_CUSTOM_HEADERS";
/// The one custom-header name OpenLatch owns inside `ANTHROPIC_CUSTOM_HEADERS`.
/// Everything else in that variable belongs to the customer and is preserved.
const INSTALL_ID_HEADER: &str = "x-openlatch-install-id";

/// `true` when a single `ANTHROPIC_CUSTOM_HEADERS` line declares the
/// OpenLatch install-id header (name compared case-insensitively).
fn is_install_id_line(line: &str) -> bool {
    line.split_once(':')
        .map(|(name, _)| name.trim().eq_ignore_ascii_case(INSTALL_ID_HEADER))
        .unwrap_or(false)
}

/// Merge our install-id line INTO an existing `ANTHROPIC_CUSTOM_HEADERS` value,
/// preserving every customer line and replacing only a prior install-id line.
/// Additive-only: corporate proxy/routing/auth headers survive untouched.
///
/// Reuses [`strip_install_id_header`] for the parse-and-drop-our-line pass, then
/// appends our current line. `kept.is_empty()` is byte-equivalent to the old
/// empty-Vec check: `strip_install_id_header` joins only non-blank customer
/// lines with `\n`, so its result is empty exactly when no customer line remains.
fn merge_install_id_header(existing: Option<&str>, install_id: &str) -> String {
    let kept = existing.map(strip_install_id_header).unwrap_or_default();
    let our_line = format!("{INSTALL_ID_HEADER}: {install_id}");
    if kept.is_empty() {
        our_line
    } else {
        format!("{kept}\n{our_line}")
    }
}

/// Strip OUR install-id line(s) from an existing `ANTHROPIC_CUSTOM_HEADERS`
/// value, returning the remaining customer lines (possibly empty).
fn strip_install_id_header(existing: &str) -> String {
    existing
        .split('\n')
        .filter(|line| !line.trim().is_empty() && !is_install_id_line(line))
        .collect::<Vec<_>>()
        .join("\n")
}

/// `true` when `value` is a loopback base URL OpenLatch would have written —
/// host `127.0.0.1`, any port, http or https. A customer-set base URL pointing
/// anywhere else must be left untouched on disable.
fn is_openlatch_loopback_base_url(value: &str) -> bool {
    reqwest::Url::parse(value.trim())
        .ok()
        .and_then(|u| u.host_str().map(|h| h == "127.0.0.1"))
        .unwrap_or(false)
}

/// Point the agent at the model-boundary listener by writing
/// `ANTHROPIC_BASE_URL=http://127.0.0.1:{port}` and a static
/// `ANTHROPIC_CUSTOM_HEADERS` install-id line into the agent's `env` block.
///
/// **Only the process holding `port` may call this.** The daemon does, right
/// after [`crate::boundary::bind_pinned`] returns `Ok` — never before, and never
/// from a process that will not go on to serve that port. Writing the base URL
/// on the strength of an intention to bind is what pointed every agent on the
/// machine at a port nobody held.
///
/// D-01 ships the plain-`http://` base URL as the default (the HTTPS +
/// `NODE_EXTRA_CA_CERTS` fallback is specified in `boundary::bind_pinned`'s
/// docs but conditional on the empirical loopback spike). `install_id` MUST be
/// PII-free — it reaches the provider on every request (F-22); the existing
/// `agent_id` is used verbatim (no new persisted field is introduced).
///
/// Uses the same JSONC-preserving atomic path (`set_env_var_cst`) that writes
/// `OPENLATCH_TOKEN`, so comments and formatting survive.
pub fn write_boundary_config(
    settings_path: &std::path::Path,
    port: u16,
    install_id: &str,
) -> Result<(), OlError> {
    let base_url = format!("http://127.0.0.1:{port}");
    atomic::atomic_rewrite_jsonc(settings_path, |root| {
        jsonc::set_env_var_cst(root, ANTHROPIC_BASE_URL_ENV, &base_url)?;
        // Additive-only: merge our install-id line into any pre-existing
        // ANTHROPIC_CUSTOM_HEADERS (corporate proxy/routing/auth headers) rather
        // than clobbering the whole value.
        let existing = jsonc::get_env_var_cst(root, ANTHROPIC_CUSTOM_HEADERS_ENV);
        let merged = merge_install_id_header(existing.as_deref(), install_id);
        jsonc::set_env_var_cst(root, ANTHROPIC_CUSTOM_HEADERS_ENV, &merged)?;
        Ok(())
    })
}

/// Remove the model-boundary wiring.
///
/// Called by the daemon when it stops holding the pinned port (teardown), or
/// when it starts with the boundary disabled (reconciliation after a SIGKILL or
/// a config change); by `openlatch stop` as a net for the escalation paths where
/// the daemon never got to run its own teardown; and by `openlatch uninstall`.
///
/// Additive-safe reversal:
///
/// - `ANTHROPIC_BASE_URL` is removed ONLY when it still points at our loopback
///   listener (`http(s)://127.0.0.1:PORT`); a customer-set base URL is left
///   untouched.
/// - `ANTHROPIC_CUSTOM_HEADERS` loses only OUR install-id line(s); any customer
///   headers survive. If nothing remains, the key is dropped entirely.
///
/// A no-op if the file or the keys are absent.
pub fn remove_boundary_config(settings_path: &std::path::Path) -> Result<(), OlError> {
    if !settings_path.exists() {
        return Ok(());
    }
    atomic::atomic_rewrite_jsonc(settings_path, |root| {
        // Only reclaim ANTHROPIC_BASE_URL if it is OUR loopback URL.
        if let Some(current) = jsonc::get_env_var_cst(root, ANTHROPIC_BASE_URL_ENV) {
            if is_openlatch_loopback_base_url(&current) {
                jsonc::remove_env_var_cst(root, ANTHROPIC_BASE_URL_ENV)?;
            }
        }
        // Strip only our install-id line from ANTHROPIC_CUSTOM_HEADERS.
        if let Some(current) = jsonc::get_env_var_cst(root, ANTHROPIC_CUSTOM_HEADERS_ENV) {
            let remainder = strip_install_id_header(&current);
            if remainder.trim().is_empty() {
                jsonc::remove_env_var_cst(root, ANTHROPIC_CUSTOM_HEADERS_ENV)?;
            } else {
                jsonc::set_env_var_cst(root, ANTHROPIC_CUSTOM_HEADERS_ENV, &remainder)?;
            }
        }
        Ok(())
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    /// Smoke-test detect_agent when ~/.claude/ does NOT exist.
    ///
    /// We override HOME so that dirs::home_dir() points to an empty tempdir.
    #[test]
    #[cfg(unix)]
    fn test_detect_agent_returns_ol_1400_when_no_claude_dir() {
        use super::detect_agent;
        use crate::error::ERR_HOOK_AGENT_NOT_FOUND;

        let dir = tempfile::tempdir().unwrap();
        // Override HOME so ~/.claude/ does not exist.
        std::env::set_var("HOME", dir.path());
        let result = detect_agent();
        std::env::remove_var("HOME");

        let err = result.unwrap_err();
        assert_eq!(
            err.code, ERR_HOOK_AGENT_NOT_FOUND,
            "Expected OL-1400, got {}",
            err.code
        );
    }

    // -----------------------------------------------------------------------
    // Boundary config wiring — additive-only guarantee (FIX 2)
    // -----------------------------------------------------------------------

    use super::{remove_boundary_config, write_boundary_config, ANTHROPIC_CUSTOM_HEADERS_ENV};

    /// Read a settings.json file back as plain JSON for assertions.
    fn read_env(path: &std::path::Path) -> serde_json::Value {
        let raw = std::fs::read_to_string(path).unwrap();
        serde_json::from_str(&raw).unwrap()
    }

    #[test]
    fn boundary_enable_preserves_existing_custom_headers() {
        // (a) A customer already ships a corporate header; enable must append
        // our install-id line, keeping theirs.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_CUSTOM_HEADERS":"x-corp-proxy: foo"}}"#,
        )
        .unwrap();

        write_boundary_config(&path, 7600, "agt_x").unwrap();

        let v = read_env(&path);
        let headers = v["env"][ANTHROPIC_CUSTOM_HEADERS_ENV].as_str().unwrap();
        assert!(
            headers.contains("x-corp-proxy: foo"),
            "customer header must survive enable: {headers}"
        );
        assert!(
            headers.contains("x-openlatch-install-id: agt_x"),
            "our install-id line must be added: {headers}"
        );
        assert_eq!(v["env"]["ANTHROPIC_BASE_URL"], "http://127.0.0.1:7600");
    }

    #[test]
    fn boundary_disable_keeps_customer_headers_and_drops_ours() {
        // (b) After enable, disable must remove ONLY our line — the corporate
        // header (and the key itself) remain.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_CUSTOM_HEADERS":"x-corp-proxy: foo"}}"#,
        )
        .unwrap();

        write_boundary_config(&path, 7600, "agt_x").unwrap();
        remove_boundary_config(&path).unwrap();

        let v = read_env(&path);
        let headers = v["env"][ANTHROPIC_CUSTOM_HEADERS_ENV].as_str().unwrap();
        assert!(
            headers.contains("x-corp-proxy: foo"),
            "customer header must remain after disable: {headers}"
        );
        assert!(
            !headers.contains("x-openlatch-install-id"),
            "our install-id line must be gone: {headers}"
        );
        // Our loopback base URL was reclaimed.
        assert!(v["env"].get("ANTHROPIC_BASE_URL").is_none());
    }

    #[test]
    fn boundary_disable_removes_headers_key_when_only_ours_existed() {
        // (c) When only our line existed, disable drops the key entirely.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        std::fs::write(&path, "{}").unwrap();

        write_boundary_config(&path, 7600, "agt_x").unwrap();
        remove_boundary_config(&path).unwrap();

        let v = read_env(&path);
        assert!(
            v["env"].get(ANTHROPIC_CUSTOM_HEADERS_ENV).is_none(),
            "an all-ours header value must be removed entirely: {v}"
        );
    }

    #[test]
    fn boundary_disable_leaves_non_loopback_base_url_untouched() {
        // (d) A customer base URL pointing at a corporate gateway must survive
        // disable (we only reclaim our own 127.0.0.1 loopback URL).
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_BASE_URL":"https://gateway.corp.example"}}"#,
        )
        .unwrap();

        remove_boundary_config(&path).unwrap();

        let v = read_env(&path);
        assert_eq!(
            v["env"]["ANTHROPIC_BASE_URL"], "https://gateway.corp.example",
            "a non-loopback base URL must be left untouched: {v}"
        );
    }
}