mur-common 2.91.0

Shared types and traits for the MUR ecosystem
Documentation
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
//! CLI-spawn backend registry.
//!
//! One row per coding CLI MUR can drive. The registry is data, not code
//! paths: Gemini CLI was replaced by Antigravity inside a year, and the
//! design records that hardcoding per-CLI flags guarantees rewriting this on
//! the next replacement.
//!
//! A row exists only when every field is known. `agy`'s home env var and the
//! `codex` / `agy` streaming envelopes are still open questions in
//! `docs/superpowers/specs/2026-09-16-cli-spawn-backends-design.md`, so those
//! rows are absent rather than half-filled — an unknown field here would be
//! read as fact by every consumer.
//!
//! Nothing in this module spawns a process or reads the user's CLI config.

/// How a backend's MCP configuration reaches the CLI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpMount {
    /// Flags on every invocation; nothing is written to disk.
    PerCall,
    /// Written once into the backend's private home.
    Persistent,
}

/// Whether MUR may actually drive this backend.
///
/// Separate from binary presence on purpose. The spec's activation gate reads:
/// "Failure or unknown results keep the backend disabled; binary presence is
/// insufficient." A disabled backend is still listed and still rendered — it
/// is the panel that carries the explanation and the controls, so hiding it
/// would strand the user exactly as hiding a subscription provider did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Activation {
    Enabled,
    /// `reason` is shown to the user. It names the unmet requirement.
    Disabled {
        reason: &'static str,
    },
}

/// One CLI-spawn backend, as data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliBackend {
    /// Stable identifier used in paths and UI keys.
    pub key: &'static str,
    /// Executable name, resolved against the user's shell PATH by the caller.
    pub binary: &'static str,
    /// Flags that put the CLI in headless mode.
    pub headless_invocation: &'static [&'static str],
    /// Flags that select a machine-readable streaming envelope.
    pub stream_flags: &'static [&'static str],
    /// Flags that disable the CLI's own built-in tools.
    pub tool_disable_flags: &'static [&'static str],
    pub mcp_mount: McpMount,
    /// Environment variable that relocates this CLI's home.
    pub home_env_var: &'static str,
    pub activation: Activation,
    /// Free text for the panel: what is known, and what is not.
    pub capability_notes: &'static str,
}

/// `claude`, measured at 2.1.273 by running it, not only by reading `--help`.
///
/// `tool_disable_flags` is `--tools ""`, not `--disallowedTools`: the latter
/// is a named deny list, and denying `Bash` merely sent the model to `Glob`.
///
/// Both halves of the disable are required. `--tools ""` alone left 44 tools
/// mounted — every MCP server in the user's own config — so the flags below
/// are the pair, and `--strict-mcp-config` is load-bearing. Verified from the
/// `system init` event's `tools` array, which reported `[]`.
///
/// Enabled as of the CLI-spawn backend. The reason moved three times before
/// it could be: the tool probe, then serving tools over MCP, then the spawn. The
/// probe is answered; MUR does now serve its tools over MCP (`tools/list`,
/// `tools/call`, and the shim that forwards to them). What is missing is the
/// other half: nothing writes the per-turn `--mcp-config` and nothing runs
/// the CLI, so this row describes a backend that could work rather than one
/// that does.
///
/// Keep this sentence true. A row whose stated reason outlives the thing it
/// described is worse than a bare `false` — it explains itself confidently
/// and wrongly, and a user reading the panel has no way to tell.
pub const CLAUDE: CliBackend = CliBackend {
    key: "claude",
    binary: "claude",
    headless_invocation: &["-p"],
    stream_flags: &["--output-format", "stream-json"],
    tool_disable_flags: &["--tools", "", "--strict-mcp-config"],
    mcp_mount: McpMount::PerCall,
    home_env_var: "CLAUDE_CONFIG_DIR",
    activation: Activation::Enabled,
    capability_notes: "--tools \"\" disables built-ins but NOT the user's own MCP \
                       servers; --strict-mcp-config is what empties the tool list",
};

/// `codex`, measured at 0.154.0 by running it (#1339).
///
/// Disabled, and for a reason no probe can close. Its shell is core — there
/// is no flag that removes it, and `-s read-only` restricts the filesystem
/// rather than establishing action safety — so a spawned `codex` can execute
/// commands that never pass MUR's handler, entitlements or HITL gate. The
/// design admits it only behind a *verified* process sandbox inherited by
/// child processes, and no such sandbox exists yet.
///
/// It has a row rather than being absent because absence says nothing. A
/// user who has `codex` installed should see it listed with this reason, not
/// silently missing — the same lesson as the subscription rail in #1334.
///
/// `stream_flags` is `--json`, not `--output-format stream-json`: measured,
/// and it carries completed items only, so a codex-backed turn cannot stream
/// partial output even once the sandbox exists.
pub const CODEX: CliBackend = CliBackend {
    key: "codex",
    binary: "codex",
    headless_invocation: &["exec"],
    stream_flags: &["--json"],
    tool_disable_flags: &[],
    mcp_mount: McpMount::Persistent,
    home_env_var: "CODEX_HOME",
    activation: Activation::Disabled {
        reason: "codex's built-in shell cannot be disabled and the spawn path does not yet apply MUR's sandbox to it",
    },
    capability_notes: "prompt arrives on stdin; --json emits completed items \
                       with no incremental deltas; MCP mounts persistently, so \
                       a per-turn config must be written into the private home",
};

/// `agy`, measured at 1.2.3 by running it (#1339, #1340).
///
/// Disabled for the same reason as `codex` and not a different one: it has
/// execution it cannot be asked to give up — 57 built-in tools, enumerated by
/// its own `init` event, including `run_command`, `write_to_file` and a full
/// browser-control set — and the spawn path does not yet apply MUR's sandbox.
/// Containment does not care whether a tool is "disabled"; it cares what the
/// process can do. So this is the same blocker, not a worse one.
///
/// Its own `--sandbox` is not a mitigation. Probed with the approval layer
/// removed, it still read outside the workspace, read `$HOME`, wrote outside
/// the workspace and reached the public internet.
///
/// `home_env_var` is `HOME`, and that is an honest value rather than a
/// missing one — an earlier note here called it "no honest value", conflating
/// "no dedicated variable" with "no usable value". Setting `HOME` does
/// relocate agy's config, measured. What it also does is relocate everything
/// else that process resolves under `HOME`, which is a blunter instrument
/// than `CODEX_HOME` and is the one way this row is genuinely worse than
/// `codex`'s.
pub const AGY: CliBackend = CliBackend {
    key: "agy",
    binary: "agy",
    headless_invocation: &["-p"],
    stream_flags: &["--output-format", "stream-json"],
    tool_disable_flags: &[],
    mcp_mount: McpMount::Persistent,
    home_env_var: "HOME",
    activation: Activation::Disabled {
        reason: "agy's 57 built-in tools cannot be disabled and the spawn path does not yet apply MUR's sandbox to it",
    },
    capability_notes: "HOME is the only lever and it moves everything, not just \
                       config; `-p` swallows a following flag as its prompt, so \
                       use `-p=<prompt>`; MCP mounts persistently at \
                       $HOME/.gemini/config/mcp_config.json",
};

/// Every backend whose record is complete. Absence is a statement: a CLI
/// missing here has an unanswered probe, not a missing implementation.
pub const REGISTRY: &[CliBackend] = &[CLAUDE, CODEX, AGY];

/// Look up a backend by key.
pub fn backend(key: &str) -> Option<&'static CliBackend> {
    REGISTRY.iter().find(|b| b.key == key)
}

/// A backend whose binary was found, plus whether MUR may drive it.
///
/// `usable == false` is a backend that is present and listed but must not be
/// spawned; the caller renders it with `Activation::Disabled`'s reason. It is
/// deliberately not filtered out — the disabled entry is what carries the
/// explanation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackendAvailability {
    pub backend: &'static CliBackend,
    pub path: std::path::PathBuf,
    pub usable: bool,
}

/// Which backends the user actually has, given a binary resolver.
///
/// `resolve` is injected rather than calling a `which` helper directly: this
/// crate is consumed by the Hub, the runtime and the CLI, each of which
/// resolves binaries differently (the Hub must ask an interactive login shell,
/// because a Finder-launched app inherits a bare PATH). Injection also makes
/// every case below testable without touching the real PATH.
pub fn available<F>(resolve: F) -> Vec<BackendAvailability>
where
    F: Fn(&str) -> Option<std::path::PathBuf>,
{
    REGISTRY
        .iter()
        .filter_map(|b| {
            resolve(b.binary).map(|path| BackendAvailability {
                backend: b,
                path,
                usable: matches!(b.activation, Activation::Enabled),
            })
        })
        .collect()
}

/// `<mur_home>/cli-homes/<key>/` — this backend's private CLI home.
///
/// `mur_home` is a parameter rather than a call to `trust::mur_home()` so the
/// path is a pure function of its inputs and every test runs against a temp
/// dir. Same shape as `local_llm::local_model_dir`.
pub fn home_dir(mur_home: &std::path::Path, key: &str) -> std::path::PathBuf {
    mur_home.join("cli-homes").join(key)
}

/// Create this backend's private home if absent and return the environment
/// variable that points the CLI at it.
///
/// The home starts empty and stays MUR's: the user authenticates once inside
/// it, and their own `~/.claude` / `~/.codex` is never read or written. We do
/// not copy `auth.json` — two holders of one refresh-token lineage each
/// rotating would log the user out of their own CLI, which is why the gateway
/// is the sole token holder on the other track.
pub fn ensure_home(
    mur_home: &std::path::Path,
    b: &CliBackend,
) -> std::io::Result<(&'static str, std::path::PathBuf)> {
    let dir = home_dir(mur_home, b.key);
    std::fs::create_dir_all(&dir)?;
    Ok((b.home_env_var, dir))
}

/// The flags that make a spawned CLI see MUR's tools and nothing else.
///
/// One constant, not three arguments assembled at the call site. Measured
/// 2026-09-16: `--tools ""` alone still left 44 tools mounted — every MCP
/// server in the user's own config — and none of those pass MUR's handler,
/// entitlements or HITL gate. `--strict-mcp-config` is what empties the
/// list, so the three travel together or the isolation is not there.
pub const ISOLATION_FLAGS: &[&str] = &["--tools", "", "--strict-mcp-config"];

/// The `--mcp-config` document for one turn.
///
/// Names the shim, the agent socket it dials back on, and the task it
/// belongs to. `task_id` is what binds a spawned `bash` job to an owner and
/// routes an approval prompt, so it is an argument rather than something the
/// shim could infer.
pub fn mcp_config_json(
    shim_bin: &str,
    socket: &std::path::Path,
    task_id: &str,
) -> serde_json::Value {
    serde_json::json!({
        "mcpServers": {
            "mur": {
                "command": shim_bin,
                "args": [
                    "mcp-shim",
                    "--socket", socket.to_string_lossy(),
                    "--task-id", task_id,
                ],
            }
        }
    })
}

/// Marks a model registry `provider` as naming the CLI-spawn track.
///
/// The gateway track already selects on `provider` (`claude` and `codex`
/// dispatch to loopback clients), so the CLI track uses the same field
/// rather than inventing a second way to say which track an agent is on.
/// The prefix keeps the two readable side by side — `claude` is the
/// gateway, `cli:claude` is the spawn — and cannot be confused with a
/// vendor slug, which a `-cli` suffix would have to be parsed off a name
/// that may itself contain dashes.
pub const PROVIDER_PREFIX: &str = "cli:";

/// The backend a registry `provider` names, if it names one.
///
/// Returns the row whether or not it is enabled. Activation is the caller's
/// gate to apply and to report: a disabled backend must produce a turn that
/// explains itself, which it cannot do if this returns `None` and the
/// provider merely looks unknown.
pub fn from_provider(provider: &str) -> Option<&'static CliBackend> {
    let key = provider.strip_prefix(PROVIDER_PREFIX)?;
    backend(key)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn claude_row_matches_the_measured_capabilities() {
        assert_eq!(CLAUDE.binary, "claude");
        assert_eq!(CLAUDE.headless_invocation, &["-p"]);
        assert_eq!(CLAUDE.stream_flags, &["--output-format", "stream-json"]);
        assert_eq!(
            CLAUDE.tool_disable_flags,
            &["--tools", "", "--strict-mcp-config"]
        );
        assert_eq!(CLAUDE.mcp_mount, McpMount::PerCall);
        assert_eq!(CLAUDE.home_env_var, "CLAUDE_CONFIG_DIR");
    }

    #[test]
    fn claude_is_enabled_once_the_spawn_path_exists() {
        // The gate is not "a probe answered"; it is that every isolation
        // requirement was demonstrated. The boxes are in the plan.
        assert!(matches!(CLAUDE.activation, Activation::Enabled));
    }

    #[test]
    fn the_tool_disable_carries_both_halves() {
        // Regression guard for the measured hazard: `--tools ""` on its own
        // left 44 of the user's own MCP tools mounted. Dropping
        // --strict-mcp-config here would silently reopen that hole.
        assert!(CLAUDE.tool_disable_flags.contains(&"--tools"));
        assert!(CLAUDE.tool_disable_flags.contains(&"--strict-mcp-config"));
        assert!(
            !CLAUDE.tool_disable_flags.contains(&"--disallowedTools"),
            "--disallowedTools is a named deny list, not a disable"
        );
    }

    #[test]
    fn every_row_is_fully_specified() {
        // The rule the registry exists to enforce: no half-filled row. A
        // backend with an unknown field belongs outside the registry, not
        // inside it with a plausible-looking guess.
        for b in REGISTRY {
            assert!(!b.key.is_empty(), "{}: empty key", b.key);
            assert!(!b.binary.is_empty(), "{}: empty binary", b.key);
            assert!(
                !b.headless_invocation.is_empty(),
                "{}: no headless flags",
                b.key
            );
            assert!(!b.stream_flags.is_empty(), "{}: no stream flags", b.key);
            assert!(!b.home_env_var.is_empty(), "{}: no home env var", b.key);
        }
    }

    #[test]
    fn unprobed_backends_are_absent_rather_than_guessed() {
        // Both probes are answered (#1339); what differs is what the answers
        // did. `codex`'s made a row possible — it has all five required
        // fields — so it is registered and disabled, not absent.
        //
        // `agy`'s answer is what keeps it out, and structurally: it has no
        // home environment variable at all, only `HOME`, so there is no
        // honest value for `home_env_var` and the completeness rule above
        // would reject the row. Absence here is the measurement, not a gap.
        // Every probed backend now has a row. Absence is reserved for a CLI
        // nobody has measured — it is a statement about knowledge, not about
        // safety, and both of these are disabled rather than missing.
        assert!(backend("agy").is_some(), "agy's record is complete");
        assert!(backend("codex").is_some(), "codex's record is complete");
        assert!(backend("nope").is_none());
    }

    #[test]
    fn lookup_finds_claude_and_rejects_unknown_keys() {
        assert_eq!(backend("claude"), Some(&CLAUDE));
        assert!(backend("nope").is_none());
    }

    use std::path::PathBuf;

    fn found(_: &str) -> Option<PathBuf> {
        Some(PathBuf::from("/opt/homebrew/bin/claude"))
    }

    fn missing(_: &str) -> Option<PathBuf> {
        None
    }

    #[test]
    fn an_absent_binary_produces_no_entry() {
        // "Backends whose binary is absent do not appear in the UI at all."
        assert!(available(missing).is_empty());
    }

    #[test]
    fn a_present_binary_is_listed_with_the_path_that_was_resolved() {
        // Every registered backend, each carrying the path the resolver gave
        // for it. Asserted over the whole registry rather than over a count,
        // so adding a row does not break a test about path plumbing.
        let got = available(found);
        assert_eq!(got.len(), REGISTRY.len());
        for a in &got {
            assert_eq!(a.path, PathBuf::from("/opt/homebrew/bin/claude"));
        }
        assert!(got.iter().any(|a| a.backend.key == "claude"));
    }

    #[test]
    fn a_disabled_backend_would_be_listed_and_not_usable() {
        // The distinction `available()` exists to hold: absent means gone,
        // disabled means shown-and-not-usable. It used to be asserted through
        // the `claude` row, which was disabled at the time; now that `claude`
        // is enabled there is no disabled row to borrow, so the mapping is
        // asserted directly rather than deleted along with its example.
        let disabled = CliBackend {
            activation: Activation::Disabled {
                reason: "for the test",
            },
            ..CLAUDE
        };
        let entry = BackendAvailability {
            backend: &CLAUDE,
            path: PathBuf::from("/opt/homebrew/bin/claude"),
            usable: matches!(disabled.activation, Activation::Enabled),
        };
        assert!(!entry.usable, "a disabled backend must never be usable");
    }

    #[test]
    fn usable_tracks_activation_and_nothing_else() {
        // Guards against a future row being enabled by the mere fact that its
        // binary resolved.
        for a in available(found) {
            assert_eq!(
                a.usable,
                matches!(a.backend.activation, Activation::Enabled)
            );
        }
    }

    #[test]
    fn home_dir_is_namespaced_under_cli_homes() {
        let got = home_dir(std::path::Path::new("/tmp/murhome"), "claude");
        assert_eq!(got, PathBuf::from("/tmp/murhome/cli-homes/claude"));
    }

    #[test]
    fn ensure_home_creates_the_dir_and_returns_the_env_var() {
        let tmp = std::env::temp_dir().join(format!("mur-cli-home-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&tmp);
        let (var, dir) = ensure_home(&tmp, &CLAUDE).expect("create");
        assert_eq!(var, "CLAUDE_CONFIG_DIR");
        assert_eq!(dir, tmp.join("cli-homes").join("claude"));
        assert!(dir.is_dir());
        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn ensure_home_is_idempotent() {
        let tmp = std::env::temp_dir().join(format!("mur-cli-home-idem-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&tmp);
        ensure_home(&tmp, &CLAUDE).expect("first");
        let marker = home_dir(&tmp, "claude").join("settings.json");
        std::fs::write(&marker, b"{}").expect("write marker");
        ensure_home(&tmp, &CLAUDE).expect("second");
        assert_eq!(std::fs::read(&marker).expect("read marker"), b"{}");
        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn ensure_home_never_touches_the_users_own_cli_config() {
        // The Global Constraint, asserted rather than assumed. A stand-in for
        // ~/.claude sits OUTSIDE the mur home; creating the private home must
        // leave its bytes untouched.
        let base = std::env::temp_dir().join(format!("mur-cli-iso-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let user_cfg = base.join("user-claude");
        std::fs::create_dir_all(&user_cfg).expect("user cfg");
        let cred = user_cfg.join(".credentials.json");
        std::fs::write(&cred, b"user-token").expect("seed");

        ensure_home(&base.join("murhome"), &CLAUDE).expect("create");

        assert_eq!(std::fs::read(&cred).expect("still there"), b"user-token");
        assert!(
            !base
                .join("murhome")
                .join("cli-homes")
                .join("claude")
                .join(".credentials.json")
                .exists()
        );
        std::fs::remove_dir_all(&base).ok();
    }

    #[test]
    fn the_isolation_flags_stay_together() {
        // Each of the three is load-bearing and the middle row of the table
        // in the plan is why: dropping --strict-mcp-config re-mounts the
        // user's own MCP servers, and the spawn still looks correct.
        assert_eq!(ISOLATION_FLAGS, &["--tools", "", "--strict-mcp-config"]);
    }

    #[test]
    fn the_mcp_config_names_the_shim_the_socket_and_the_task() {
        let v = mcp_config_json(
            "/usr/local/bin/mur_agent_x",
            std::path::Path::new("/tmp/x/agent.sock"),
            "t-9",
        );
        let s = &v["mcpServers"]["mur"];
        assert_eq!(s["command"], "/usr/local/bin/mur_agent_x");
        let args: Vec<String> = s["args"]
            .as_array()
            .expect("args")
            .iter()
            .map(|a| a.as_str().unwrap_or_default().to_string())
            .collect();
        assert_eq!(args[0], "mcp-shim");
        assert!(args.contains(&"/tmp/x/agent.sock".to_string()));
        assert!(args.contains(&"t-9".to_string()));
    }

    #[test]
    fn the_config_declares_exactly_one_server() {
        // `--strict-mcp-config` means this document is the whole tool
        // surface. A second entry here would be a second unaudited source.
        let v = mcp_config_json("bin", std::path::Path::new("/s"), "t");
        assert_eq!(v["mcpServers"].as_object().expect("obj").len(), 1);
    }

    #[test]
    fn a_prefixed_provider_names_the_backend() {
        assert_eq!(from_provider("cli:claude").map(|b| b.key), Some("claude"));
    }

    #[test]
    fn the_gateway_providers_are_not_the_cli_track() {
        // `claude` and `codex` already mean the loopback gateway. If this
        // ever matched them, putting an agent on the gateway would silently
        // spawn a CLI instead.
        assert!(from_provider("claude").is_none());
        assert!(from_provider("codex").is_none());
        assert!(from_provider("openai").is_none());
    }

    #[test]
    fn an_unknown_backend_is_none_even_when_prefixed() {
        // `cli:agy` resolves now that agy has a row — that is the point of
        // giving it one. An agent pointed there gets "disabled, and here is
        // why" instead of the unknown-provider path, which reads as a typo.
        assert_eq!(from_provider("cli:agy").map(|b| b.key), Some("agy"));
        assert!(from_provider("cli:nope").is_none());
    }

    #[test]
    fn a_disabled_backend_still_resolves() {
        // The caller needs the row to report *why* it is off. Returning
        // `None` would make a disabled backend indistinguishable from a typo.
        let disabled = CliBackend {
            activation: Activation::Disabled {
                reason: "for the test",
            },
            ..CLAUDE
        };
        assert!(matches!(disabled.activation, Activation::Disabled { .. }));
        assert!(from_provider("cli:claude").is_some());
    }

    #[test]
    fn codex_is_listed_and_never_usable() {
        // The distinction the registry exists to express: present, so a user
        // with `codex` installed sees it and its reason; not usable, because
        // its shell cannot be disabled and no verified sandbox exists.
        let c = backend("codex").expect("codex is registered");
        match c.activation {
            Activation::Disabled { reason } => {
                assert!(reason.contains("sandbox"), "{reason}");
                // Not "no sandbox exists" — one does, in
                // `mur-agent-runtime/src/sandbox/`. What is missing is its
                // application to the spawn path, and the reason must say
                // which, or it sends the next reader off to build one.
                assert!(reason.contains("does not yet apply"), "{reason}");
                assert!(reason.contains("shell"), "{reason}");
            }
            Activation::Enabled => panic!("codex must not be enabled without a verified sandbox"),
        }
        assert!(
            available(found)
                .iter()
                .any(|a| a.backend.key == "codex" && !a.usable)
        );
    }

    #[test]
    fn cli_codex_resolves_so_the_refusal_can_name_itself() {
        // An agent pointed at `cli:codex` must get "disabled, and here is
        // why" — not the unknown-provider path, which reads as a typo. This
        // is the guard that was deferred while `from_provider` lived on an
        // unmerged branch; it belongs beside the row it protects.
        assert_eq!(from_provider("cli:codex").map(|b| b.key), Some("codex"));
    }

    #[test]
    fn agy_is_listed_and_never_usable() {
        // Same shape as codex's guard. The reason must name the blocker, not
        // the absence of one, or the next reader is told to solve the wrong
        // problem — which is what "no honest value for home_env_var" did.
        let a = backend("agy").expect("agy is registered");
        match a.activation {
            Activation::Disabled { reason } => {
                assert!(reason.contains("built-in tools"), "{reason}");
                assert!(reason.contains("does not yet apply"), "{reason}");
            }
            Activation::Enabled => panic!("agy must not be enabled: 57 built-ins, none disablable"),
        }
        assert!(
            available(found)
                .iter()
                .any(|a| a.backend.key == "agy" && !a.usable)
        );
    }

    #[test]
    fn home_is_a_real_lever_for_agy_not_a_placeholder() {
        // Measured (#1339): setting HOME relocates agy's config. The row says
        // `HOME` because that works, not because nothing else would fit.
        assert_eq!(AGY.home_env_var, "HOME");
        let (var, dir) = ensure_home(std::path::Path::new("/tmp/mur-agy-x"), &AGY).expect("home");
        assert_eq!(var, "HOME");
        assert!(dir.ends_with("cli-homes/agy"));
        std::fs::remove_dir_all("/tmp/mur-agy-x").ok();
    }
}