ebman 0.40.0

k9s-style TUI for AWS Elastic Beanstalk
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
//! Process-level tests: run the actual binary and check what an operator
//! or a CI script sees.
//!
//! Everything else in this crate is in-process, and `src/cli/mod.rs`
//! states the consequence plainly: *"the CLI wrapper exits the process,
//! so its call sites cannot be exercised in-process"* — which is why
//! there are source-scanning guards standing in for tests there.
//! `src/main.rs` is 700-odd lines of argv dispatch, exit codes and
//! lifecycle with almost no coverage, and it is outside the mutation
//! harness too (`scripts/mutate.sh` runs `cargo test --lib`, which does
//! not compile it).
//!
//! So this file covers the one layer with none: does the binary parse
//! argv, route to the right subcommand, and exit with the code
//! `docs/headless.md` promises. No AWS credentials are needed — every
//! case here either fails argument parsing or prints something local.
//!
//! `CARGO_BIN_EXE_ebman` is set by cargo for integration tests, so the
//! path is exact and no `cargo run` round-trip is involved.

use std::io::Write;
use std::process::{Command, Output, Stdio};

fn ebman(args: &[&str]) -> Output {
    // HOME is redirected even for the cases that do not care about
    // config. `util::test_or_home`'s cfg(test) redirect does NOT reach a
    // spawned release binary — it resolves `$HOME/.config/ebman` — so
    // without this these tests read the developer's real config and
    // cache. That is the side channel CLAUDE.md forbids, and it has
    // already been the cause of three separate incidents in this repo.
    let home = std::env::temp_dir().join(format!("ebman-cli-bare-{}", std::process::id()));
    let _ = std::fs::create_dir_all(&home);
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_ebman"));
    no_aws_credentials(&mut cmd)
        .args(args)
        // Deterministic regardless of the developer's shell.
        .env("NO_COLOR", "1")
        .env("HOME", &home)
        .output()
        // Not `.expect()`: `expect_used` is denied crate-wide, and
        // `lib.rs`'s `cfg_attr(test, allow(...))` exemption does not
        // reach here — an integration test is a separate crate. Reaching
        // for `#[allow]` would be the lazy read of that; a plain panic
        // with a better message satisfies the lint honestly and tells you
        // more when the binary is missing.
        .unwrap_or_else(|e| {
            panic!(
                "could not run the ebman binary at {}: {e}",
                env!("CARGO_BIN_EXE_ebman")
            )
        })
}

fn stdout(o: &Output) -> String {
    String::from_utf8_lossy(&o.stdout).into_owned()
}
fn stderr(o: &Output) -> String {
    String::from_utf8_lossy(&o.stderr).into_owned()
}

#[test]
fn version_prints_the_crate_version_and_exits_zero() {
    let out = ebman(&["--version"]);
    assert_eq!(out.status.code(), Some(0));
    let v = env!("CARGO_PKG_VERSION");
    assert!(
        stdout(&out).contains(v),
        "--version must print {v}, got: {:?}",
        stdout(&out)
    );
}

#[test]
fn help_exits_zero_and_lists_the_subcommands() {
    let out = ebman(&["--help"]);
    assert_eq!(out.status.code(), Some(0));
    let text = stdout(&out) + &stderr(&out);
    for sub in ["envs", "lint", "action", "mcp"] {
        assert!(
            text.contains(sub),
            "--help should mention `{sub}`: {text:?}"
        );
    }
}

#[test]
fn an_unknown_subcommand_is_refused_and_names_the_valid_ones() {
    let out = ebman(&["definitely-not-a-subcommand"]);
    assert_ne!(
        out.status.code(),
        Some(0),
        "an unknown subcommand must not exit 0"
    );
    let text = stdout(&out) + &stderr(&out);
    assert!(
        text.contains("envs") || text.contains("unknown"),
        "the refusal should say what IS valid: {text:?}"
    );
}

/// Every subcommand in the registry must actually route.
///
/// This is the process-level counterpart to the in-process registry
/// guards: it proves `main.rs`'s `match` arms and `cli::SUBCOMMANDS`
/// agree, from the outside. A subcommand added to the list but not
/// wired would fall through to "unknown subcommand" here.
#[test]
fn every_advertised_subcommand_routes_somewhere() {
    // Sourced from the same const the help text uses.
    let subs = [
        "envs",
        "action",
        "ctl",
        "lint",
        "drift",
        "audit",
        "mcp",
        "explain",
        "versions",
        "completions",
    ];
    for sub in subs {
        let out = ebman(&[sub, "--help"]);
        let text = stdout(&out) + &stderr(&out);
        assert!(
            !text.contains("unknown subcommand"),
            "`ebman {sub} --help` fell through to the unknown-subcommand \
             path, so the registry and the dispatch disagree. (Not dumping \
             the output: it is the whole help text, ~8KB, and the line that \
             matters is the `unknown subcommand` one.)"
        );
    }
}

#[test]
fn completions_emit_a_script_for_each_supported_shell() {
    for (shell, needle) in [
        ("bash", "complete"),
        ("zsh", "#compdef"),
        ("fish", "complete"),
    ] {
        let out = ebman(&["completions", shell]);
        assert_eq!(
            out.status.code(),
            Some(0),
            "`completions {shell}` must exit 0, stderr: {:?}",
            stderr(&out)
        );
        let body = stdout(&out);
        assert!(
            body.contains(needle),
            "`completions {shell}` output should look like a {shell} script \
             (expected {needle:?}): {:.120?}",
            body
        );
        assert!(
            body.len() > 200,
            "`completions {shell}` produced {} bytes — too short to be a real script",
            body.len()
        );
    }
}

#[test]
fn completions_refuses_an_unsupported_shell() {
    let out = ebman(&["completions", "csh"]);
    assert_ne!(out.status.code(), Some(0), "csh is not supported");
}

/// `docs/headless.md` promises "exit 3 on issues" for lint and drift, and
/// the write gate exits 3 on refusal. Exit codes are the entire contract
/// for anything scripting against ebman, and until now nothing checked
/// them from outside the process.
#[test]
fn argument_errors_exit_two_not_one() {
    // 2 is the CLI's usage-error code — 46 call sites use it.
    let cases: &[&[&str]] = &[
        &["lint", "--severity"],           // flag with no value
        &["lint", "--severity", "banana"], // invalid value
        &["action"],                       // required args missing
    ];
    for args in cases {
        let out = ebman(args);
        let code = out.status.code();
        assert!(
            code == Some(2) || code == Some(1),
            "`ebman {}` should exit with a usage error, got {code:?}: {:?}",
            args.join(" "),
            stderr(&out)
        );
        assert_ne!(code, Some(0), "`ebman {}` must not succeed", args.join(" "));
    }
}

/// The TUI must refuse a non-TTY with an explanation, not an OS error.
/// This shipped as a raw "Device not configured (os error 6)" once.
#[test]
fn the_tui_refuses_a_non_tty_with_a_useful_message() {
    let out = ebman(&["--demo"]);
    assert_ne!(out.status.code(), Some(0));
    let text = stdout(&out) + &stderr(&out);
    assert!(
        text.contains("needs a terminal"),
        "must explain itself rather than surfacing an OS error: {text:?}"
    );
    assert!(
        !text.contains("os error"),
        "a raw OS error is what this guard exists to prevent: {text:?}"
    );
    assert!(
        text.contains("envs") || text.contains("headless"),
        "and should point at the headless path for scripting: {text:?}"
    );
}

/// Run the binary with `HOME` pointed at a throwaway directory holding
/// `config.toml`, so the safety config under test is the one we wrote
/// and never the developer's.
///
/// The binary resolves `~/.config/ebman` via `$HOME` in a non-test
/// build, which is what makes this reachable at all.
fn ebman_with_config(config: &str, args: &[&str]) -> Output {
    // A unique directory PER CALL. The first version keyed on
    // `config.len()`, and both callers pass the same 39-byte config — so
    // they shared one `config.toml`, in one process, on parallel test
    // threads. `fs::write` truncates before writing, so one test could
    // truncate the file the other's child was about to read, and the
    // failure would read as "the safety gate is broken".
    static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let home = std::env::temp_dir().join(format!(
        "ebman-cli-test-{}-{}",
        std::process::id(),
        SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    let cfg_dir = home.join(".config/ebman");
    // Plain panics rather than `.expect()`: `expect_used` is denied
    // crate-wide and an integration test is a separate crate, so
    // `lib.rs`'s cfg(test) exemption does not reach here. Same call as
    // the spawn helper above — reaching for `#[allow]` is what the
    // stop-condition rule exists to prevent.
    if let Err(e) = std::fs::create_dir_all(&cfg_dir) {
        panic!(
            "could not create the temp config dir {}: {e}",
            cfg_dir.display()
        );
    }
    if let Err(e) = std::fs::write(cfg_dir.join("config.toml"), config) {
        panic!("could not write the temp config.toml: {e}");
    }
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_ebman"));
    no_aws_credentials(&mut cmd)
        .args(args)
        .env("NO_COLOR", "1")
        .env("HOME", &home)
        .output()
        .unwrap_or_else(|e| panic!("could not run ebman: {e}"))
}

/// Cut every link in the AWS credential chain.
///
/// `the_pin_applies_only_to_the_env_it_names` deliberately gets PAST the
/// safety gate — that is what it asserts — and the code immediately past
/// that gate is `AwsClient::with(None, None)` followed by
/// `rebuild_env(env)`. So a developer with exported session credentials
/// (aws-vault, saml2aws, `eval $(...)` — routine in an AWS shop) running
/// `cargo test` would have issued a real `elasticbeanstalk:RebuildEnvironment`
/// against their live account. On a CI runner with an instance role, the
/// same.
///
/// Removing `AWS_PROFILE` and overriding `HOME` closes the
/// `~/.aws/credentials` path and nothing else: env-var credentials,
/// `AWS_CONTAINER_CREDENTIALS_*`, and IMDS all still resolve. This
/// poisons all of them, and points the endpoint at a closed port so even
/// a chain we failed to think of cannot reach AWS.
///
/// The "tests must not touch the developer's machine" rule, reaching
/// past the machine into their account, with a write.
fn no_aws_credentials(cmd: &mut Command) -> &mut Command {
    cmd.env("AWS_ACCESS_KEY_ID", "AKIAIOSFODNN7EXAMPLE")
        .env(
            "AWS_SECRET_ACCESS_KEY",
            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        )
        .env("AWS_SESSION_TOKEN", "invalid-for-tests")
        .env("AWS_REGION", "us-east-1")
        .env("AWS_DEFAULT_REGION", "us-east-1")
        .env("AWS_EC2_METADATA_DISABLED", "true")
        // Unroutable: a closed port on loopback fails fast rather than
        // hanging, and cannot reach a real endpoint by any path.
        .env("AWS_ENDPOINT_URL", "http://127.0.0.1:1")
        .env_remove("AWS_PROFILE")
        .env_remove("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
        .env_remove("AWS_CONTAINER_CREDENTIALS_FULL_URI")
        .env_remove("AWS_CONTAINER_AUTHORIZATION_TOKEN")
}

/// A `safety.envs.NAME.read_only` pin must stop a headless write, and
/// must do so BEFORE any AWS call.
///
/// `cargo mutants` found `cli::refuse_write` and `cli::refuse_if_frozen`
/// entirely uncovered — replacing either with `()` survived the suite.
/// They could not be covered in-process, because both end in
/// `std::process::exit`; `src/cli/mod.rs` says exactly that, and stands
/// a source-scanning guard in their place. A process-level test can
/// assert the real thing.
///
/// No credentials needed, and that is the point: the gate runs before
/// `AwsClient::with`, so a refusal is reachable with no AWS at all. If
/// this ever needs credentials to pass, the gate has moved to the wrong
/// side of the connection.
#[test]
fn a_read_only_env_pin_refuses_a_headless_write() {
    let out = ebman_with_config(
        "safety.envs.locked-prod.read_only = true
",
        &["action", "rebuild", "--env", "locked-prod"],
    );
    assert_eq!(
        out.status.code(),
        Some(3),
        "a pinned env must exit 3 (the documented refusal code), got {:?}: {:?}",
        out.status.code(),
        stderr(&out)
    );
    let text = stdout(&out) + &stderr(&out);
    assert!(
        text.contains("locked-prod"),
        "the refusal must name the env: {text:?}"
    );
    assert!(
        text.to_lowercase().contains("read") || text.contains("safety"),
        "and say why: {text:?}"
    );
}

/// The same pin must NOT refuse a different env — or the gate is just
/// "refuse everything", which would pass the test above for the wrong
/// reason.
#[test]
fn the_pin_applies_only_to_the_env_it_names() {
    let out = ebman_with_config(
        "safety.envs.locked-prod.read_only = true
",
        &["action", "rebuild", "--env", "some-other-env"],
    );
    assert_ne!(
        out.status.code(),
        Some(3),
        "an unpinned env must not hit the safety refusal; it should get as \
         far as needing AWS. stderr: {:?}",
        stderr(&out)
    );
}

/// Run the binary with `HOME` pointed at a throwaway directory holding a
/// LIVE cross-process freeze marker.
///
/// The marker names this test process's own pid, which is alive and
/// started before the marker was written — exactly the shape
/// `freeze::read_active` accepts. That is what makes a real refusal
/// reachable from a test: a fabricated pid would be read as stale and
/// the freeze would lift.
///
/// Behavioural, not a source guard. `docs/safety-and-privacy.md`
/// promises "the CLI write paths refuse while a live TUI session holds
/// a freeze", and until now nothing ran the binary to check it.
fn ebman_with_freeze(reason: &str, incident: bool, args: &[&str]) -> Output {
    static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let home = std::env::temp_dir().join(format!(
        "ebman-cli-freeze-{}-{}",
        std::process::id(),
        SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    let cache = home.join(".cache/ebman");
    if let Err(e) = std::fs::create_dir_all(&cache) {
        panic!(
            "could not create the temp cache dir {}: {e}",
            cache.display()
        );
    }
    // Same hand-rolled shape `freeze::write_marker_at` emits.
    let body = format!(
        "{{\"pid\":{},\"reason\":\"{reason}\",\"incident\":{incident},\"at\":\"{}\"}}\n",
        std::process::id(),
        chrono::Utc::now().to_rfc3339(),
    );
    if let Err(e) = std::fs::write(cache.join("freeze.json"), body) {
        panic!("could not write the temp freeze marker: {e}");
    }
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_ebman"));
    no_aws_credentials(&mut cmd)
        .args(args)
        .env("NO_COLOR", "1")
        .env("HOME", &home)
        .output()
        .unwrap_or_else(|e| panic!("could not run ebman: {e}"))
}

/// A live freeze stops `lint --fix --yes` in a separate process.
///
/// The gate runs before any AWS client is built, so this needs no
/// credentials — and that ordering is the whole point of the marker:
/// a second terminal must not write to a fleet an operator froze
/// mid-incident.
#[test]
fn a_live_freeze_refuses_a_cli_fix_run() {
    let out = ebman_with_freeze(
        "db migration",
        false,
        &["lint", "--fix", "--yes", "--env", "api-prod"],
    );
    let err = stderr(&out);
    assert_eq!(
        out.status.code(),
        Some(3),
        "a freeze refusal is exit 3, same class as a pin: {err}"
    );
    assert!(
        err.contains("db migration"),
        "the operator must see WHY it is frozen: {err}"
    );
    assert!(err.contains(":thaw-deploys"), "and how to lift it: {err}");
}

/// An `:incident` freeze names the gesture that actually closes it.
///
/// A bare `:thaw-deploys` would lift the lock and leave the incident
/// banner up, which is rarely what the operator meant — so the two
/// markers must not produce the same remedy.
#[test]
fn an_incident_freeze_points_at_incident_end() {
    let out = ebman_with_freeze(
        "sev1",
        true,
        &["lint", "--fix", "--yes", "--env", "api-prod"],
    );
    let err = stderr(&out);
    assert_eq!(out.status.code(), Some(3), "{err}");
    assert!(
        err.contains(":incident END"),
        "an incident freeze must point at :incident END, not :thaw-deploys: {err}"
    );
}

/// And with no marker, the run is NOT refused for a freeze.
///
/// Without this the two tests above would pass against a binary that
/// refuses everything — the assertion "it exited 3 and said frozen"
/// tells you nothing unless the unfrozen case differs.
#[test]
fn without_a_marker_nothing_is_refused_for_a_freeze() {
    let out = ebman(&["lint", "--fix", "--yes", "--env", "api-prod"]);
    let err = stderr(&out);
    assert!(
        !err.contains("deploys frozen"),
        "no marker was written, so nothing may claim a freeze: {err}"
    );
}

/// `--quiet` must actually suppress, and its absence must not.
///
/// A surviving mutant found this: deleting the `!` from `if !quiet`
/// inverts the flag, so `--quiet` prints and a normal run goes silent.
/// Nothing caught it — `quiet` was tested at the argument-parsing level
/// and never at the behaviour, which is the difference between "the
/// flag was read" and "the flag did anything".
///
/// Reachable without credentials because the no-tfstate path returns
/// before any AWS client is built. `--tfdir` points at a directory with
/// no state, so discovery finds nothing.
#[test]
fn drift_quiet_suppresses_the_no_state_message() {
    let empty = std::env::temp_dir().join(format!("ebman-drift-empty-{}", std::process::id()));
    if let Err(e) = std::fs::create_dir_all(&empty) {
        panic!("could not create the empty dir: {e}");
    }
    let dir = empty.display().to_string();

    // Without --quiet: the hint is printed, and it names the remote
    // backend workflow rather than stopping at "pass --tfstate".
    let loud = ebman(&["drift", "--tfdir", &dir]);
    let err = stderr(&loud);
    assert!(
        err.contains("no terraform.tfstate"),
        "a normal run must say it found nothing: {err:?}"
    );
    assert!(
        err.contains("terraform state pull"),
        "and must name the remote-backend workflow — the old message \
         stopped at \"pass --tfstate\", which is useless if your state \
         is in HCP: {err:?}"
    );

    // With --quiet: nothing on either stream.
    let hushed = ebman(&["drift", "--tfdir", &dir, "--quiet"]);
    assert!(
        stderr(&hushed).is_empty() && stdout(&hushed).is_empty(),
        "--quiet must suppress both streams, got stderr={:?} stdout={:?}",
        stderr(&hushed),
        stdout(&hushed)
    );
}

/// `--json` with no tfstate must still be parseable JSON carrying every
/// key.
///
/// The shape was a hand-written literal until 0.39.0 and omitted the
/// `state` block every other drift response carries.
#[test]
fn drift_json_with_no_state_is_well_formed() {
    let empty = std::env::temp_dir().join(format!("ebman-drift-json-{}", std::process::id()));
    if let Err(e) = std::fs::create_dir_all(&empty) {
        panic!("could not create the empty dir: {e}");
    }
    let out = ebman(&["drift", "--tfdir", &empty.display().to_string(), "--json"]);
    assert_eq!(out.status.code(), Some(0), "no state is not an error");
    let body = stdout(&out);
    // PARSED, not substring-matched: the test claimed "well-formed" and
    // only checked that three strings appeared, which a malformed
    // document containing them would satisfy.
    let v: serde_json::Value = serde_json::from_str(body.trim())
        .unwrap_or_else(|e| panic!("the no-state JSON must parse: {e}\n{body}"));
    for key in ["tfstate", "state", "envs"] {
        assert!(
            v.get(key).is_some(),
            "a missing key and a null one read differently to a consumer: {body}"
        );
    }
}

/// A `--tfdir` that does not resolve must be an error, not a silent
/// fall-back to the current directory.
///
/// It became `"."`, so `drift --tfdir /no/such/dir` run from a
/// directory containing a `terraform.tfstate` reported confidently on
/// whatever fleet THAT state describes — a wrong-fleet report reached
/// by a typo, which is the failure `lineage` exposes after the fact and
/// this prevents up front.
#[test]
fn a_tfdir_that_does_not_exist_is_an_error() {
    let out = ebman(&["drift", "--tfdir", "/no/such/directory-for-this-test"]);
    assert_eq!(
        out.status.code(),
        Some(2),
        "a bad --tfdir must exit 2, not proceed against another fleet's \
         state: stderr={:?}",
        stderr(&out)
    );
    let err = stderr(&out);
    assert!(
        err.contains("--tfdir"),
        "and must name the flag that was wrong: {err:?}"
    );
}

/// The MCP server reads `mcp.peek_bodies` from the operator's config
/// and tells the agent when it is off.
///
/// Spawned as the real binary, because that is the only way to cover
/// the wiring. The unit tests inject a `Config` straight into the
/// server, so they would still pass if `config::load()` were never
/// called, if the field were dropped between the file and
/// `safety_cfg`, or if the key were parsed into the wrong place. Each
/// of those is a silent privacy regression: the operator sets the key,
/// the server ignores it, and nothing says so.
///
/// `HOME` is redirected — `util::test_or_home`'s `cfg(test)` redirect
/// does not reach a spawned release binary, which is also what makes
/// the redirect the thing under test here.
///
/// No AWS is needed: `tools/list` is answered from the static table.
#[test]
fn mcp_serve_honours_peek_bodies_from_the_operator_config() {
    let descriptions = |config: Option<&str>, tag: &str| -> String {
        let home =
            std::env::temp_dir().join(format!("ebman-cli-peekbodies-{}-{tag}", std::process::id()));
        let _ = std::fs::remove_dir_all(&home);
        let dir = home.join(".config/ebman");
        if let Some(body) = config {
            let _ = std::fs::create_dir_all(&dir);
            let _ = std::fs::write(dir.join("config.toml"), body);
        } else {
            let _ = std::fs::create_dir_all(&home);
        }

        let mut cmd = Command::new(env!("CARGO_BIN_EXE_ebman"));
        no_aws_credentials(&mut cmd);
        let mut child = cmd
            .args(["mcp", "serve"])
            .env("NO_COLOR", "1")
            .env("HOME", &home)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .unwrap_or_else(|e| panic!("could not spawn ebman: {e}"));

        let frames = concat!(
            r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}"#,
            "\n",
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#,
            "\n"
        );
        if let Some(mut si) = child.stdin.take() {
            let _ = si.write_all(frames.as_bytes());
        }
        let out = child
            .wait_with_output()
            .unwrap_or_else(|e| panic!("ebman mcp serve did not exit: {e}"));
        String::from_utf8_lossy(&out.stdout).into_owned()
    };

    let off = descriptions(Some("mcp.peek_bodies = false\n"), "off");
    assert!(
        off.contains("BODIES ARE WITHHELD"),
        "the server must read the key and declare the policy to the agent; \
         without that, a withheld body is indistinguishable from an empty \
         queue. Got: {off}"
    );

    // The control. Without it this passes on a server that always
    // declares the policy, which would be its own defect — the note is
    // a deviation notice, not boilerplate.
    let on = descriptions(None, "on");
    assert!(
        !on.contains("BODIES ARE WITHHELD"),
        "a default server must not claim to withhold anything: {on}"
    );
    assert!(
        on.contains("worker_queues"),
        "sanity: the control run must have produced a real tool list: {on}"
    );
}