ebman 0.37.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
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
//! Optional Unix-socket control plane. When `ebman` is launched with
//! `--control-socket PATH`, this module opens a listener at PATH and accepts
//! one-shot requests:
//!
//! - `SCREEN\n` → returns a plain-text rendering of the current TUI frame.
//! - `KEY <SPEC>\n` → injects a synthesised key event into the run loop.
//!   Spec syntax: `Down`, `Up`, `Enter`, `Esc`, `Tab`, `BackTab`,
//!   `Backspace`, `Home`, `End`, `PageUp`, `PageDown`, `Space`, `F1`–`F12`,
//!   a single character, or `Char(j)`. Combine with `Ctrl+`, `Shift+`, `Alt+`.
//! - `CMD <text>\n` → runs the given `:command` (leading colon optional).
//! - `STATE\n` → returns a flat JSON object with current mode / profile /
//!   region / env count / selected env / load state.
//!
//! Each TCP connection is a single request → response → close cycle, so the
//! `ebman ctl …` subcommand can stay stateless (and so the server is robust
//! against half-disconnected clients).
//!
//! Security: the listener creates the socket with `0600` permissions so only
//! the current user can connect. Anyone with read access to that socket has
//! full control of the running ebman process, including dispatch of
//! destructive AWS actions — keep the socket path private.

use std::path::{Path, PathBuf};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::buffer::Buffer;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::UnixListener;
use tokio::sync::{mpsc, oneshot};

/// One request received over the control socket. The main run loop drains
/// these from an mpsc channel and dispatches them inside `tokio::select!`.
#[derive(Debug)]
pub enum ControlOp {
    /// Request a plain-text dump of the current TUI buffer. Reply via the
    /// oneshot with the rendered text (newline-separated rows).
    Screen(oneshot::Sender<String>),
    /// Inject a synthesised key event. The run loop dispatches it through
    /// the usual `handle_event(Event::Key(_))` path so all bindings apply.
    Key(KeyEvent),
    /// Run a `:command` body (with or without the leading colon).
    Command(String),
    /// Request a JSON snapshot of high-level App state.
    State(oneshot::Sender<String>),
    /// Re-exec the binary at `std::env::current_exe()` with the original
    /// argv. The run loop exits cleanly and `main()` then performs the
    /// `exec`, so the parent shell's terminal is reused by the new process.
    /// Pair with a prior `cargo build --release` to pick up source changes.
    Reload,
}

/// Open the Unix socket at `path` and spawn a listener task that translates
/// inbound text requests into `ControlOp` messages on `tx`. Silently returns
/// on bind failure after logging the error — the TUI must keep running.
pub fn spawn_listener(path: PathBuf, tx: mpsc::UnboundedSender<ControlOp>) {
    tokio::spawn(async move {
        let _ = std::fs::remove_file(&path);
        let listener = match UnixListener::bind(&path) {
            Ok(l) => l,
            Err(e) => {
                tracing::error!(error = %e, path = %path.display(), "control socket bind failed");
                return;
            }
        };
        restrict_socket_perms(&path);
        tracing::info!(path = %path.display(), "control socket listening");
        // Our own uid, read off the socket file we just created —
        // avoids a libc dependency for geteuid().
        let own_uid = socket_owner_uid(&path);
        loop {
            let (stream, _) = match listener.accept().await {
                Ok(s) => s,
                Err(e) => {
                    tracing::warn!(error = %e, "accept on control socket failed");
                    continue;
                }
            };
            // Peer-credential check on EVERY connection: the 0600
            // chmod happens after bind, and a connection racing that
            // window could sit in the backlog with the umask-default
            // perms. SO_PEERCRED closes the race (and hardens the
            // socket beyond file perms generally — the socket drives
            // arbitrary TUI commands including `readonly off`).
            if !peer_is_owner(&stream, own_uid) {
                tracing::warn!("control socket: rejected connection from another uid");
                continue;
            }
            let tx2 = tx.clone();
            tokio::spawn(async move {
                let _ = handle_connection(stream, tx2).await;
            });
        }
    });
}

#[cfg(unix)]
fn restrict_socket_perms(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}

#[cfg(not(unix))]
fn restrict_socket_perms(_path: &Path) {}

/// The uid owning the freshly-bound socket file — i.e. our own uid.
/// `None` (metadata failed / non-unix) fails open to the perms-only
/// posture that shipped before the peer check.
#[cfg(unix)]
fn socket_owner_uid(path: &Path) -> Option<u32> {
    use std::os::unix::fs::MetadataExt;
    std::fs::metadata(path).ok().map(|m| m.uid())
}

#[cfg(not(unix))]
fn socket_owner_uid(_path: &Path) -> Option<u32> {
    None
}

/// Whether a peer uid may drive this socket: the owner, or root.
///
/// Root is allowed because it could read the socket regardless, so
/// refusing it buys nothing.
///
/// Split out of [`peer_is_owner`] because it is the whole authorisation
/// decision and the socket around it made it unreachable. The
/// 2026-08-26 mutation sweep left every operator in it alive, including
/// `==` flipped to `!=` — which admits everyone EXCEPT the owner, on a
/// socket whose own comment notes it "drives arbitrary TUI commands
/// including `readonly off`".
pub(crate) fn uid_is_allowed(peer_uid: u32, own_uid: u32) -> bool {
    peer_uid == own_uid || peer_uid == 0
}

/// SO_PEERCRED check: the connecting process must run as the same uid
/// that owns the socket. Root (uid 0) is also allowed — it could read
/// the socket regardless.
#[cfg(unix)]
fn peer_is_owner(stream: &tokio::net::UnixStream, own_uid: Option<u32>) -> bool {
    let Some(own) = own_uid else { return true };
    match stream.peer_cred() {
        Ok(cred) => uid_is_allowed(cred.uid(), own),
        // Can't read peer creds: refuse rather than trust.
        Err(_) => false,
    }
}

#[cfg(not(unix))]
fn peer_is_owner(_stream: &tokio::net::UnixStream, _own_uid: Option<u32>) -> bool {
    true
}

async fn handle_connection(
    stream: tokio::net::UnixStream,
    tx: mpsc::UnboundedSender<ControlOp>,
) -> std::io::Result<()> {
    let (read_half, mut write_half) = stream.into_split();
    let mut reader = BufReader::new(read_half);
    let mut line = String::new();
    reader.read_line(&mut line).await?;
    let line = line.trim();
    if line.is_empty() {
        write_half.write_all(b"ERR empty request\n").await?;
        return Ok(());
    }
    let (head, tail) = match line.split_once(' ') {
        Some((h, t)) => (h, t),
        None => (line, ""),
    };
    match head.to_ascii_uppercase().as_str() {
        "SCREEN" => {
            let (otx, orx) = oneshot::channel();
            if tx.send(ControlOp::Screen(otx)).is_err() {
                write_half.write_all(b"ERR app dropped channel\n").await?;
                return Ok(());
            }
            match orx.await {
                Ok(text) => {
                    write_half.write_all(text.as_bytes()).await?;
                    if !text.ends_with('\n') {
                        write_half.write_all(b"\n").await?;
                    }
                }
                Err(_) => {
                    write_half.write_all(b"ERR snapshot cancelled\n").await?;
                }
            }
        }
        "STATE" => {
            let (otx, orx) = oneshot::channel();
            if tx.send(ControlOp::State(otx)).is_err() {
                write_half.write_all(b"ERR app dropped channel\n").await?;
                return Ok(());
            }
            match orx.await {
                Ok(text) => {
                    write_half.write_all(text.as_bytes()).await?;
                    write_half.write_all(b"\n").await?;
                }
                Err(_) => {
                    write_half.write_all(b"ERR state cancelled\n").await?;
                }
            }
        }
        "KEY" => match parse_key_spec(tail) {
            Some(ke) => {
                let _ = tx.send(ControlOp::Key(ke));
                write_half.write_all(b"OK\n").await?;
            }
            None => {
                write_half
                    .write_all(format!("ERR invalid key spec: {tail}\n").as_bytes())
                    .await?;
            }
        },
        "RELOAD" => {
            // Reply OK *before* the run loop tears down the TUI so the
            // client sees the exit signal cleanly. Best-effort; if mpsc
            // send fails the app is already shutting down.
            let _ = tx.send(ControlOp::Reload);
            write_half.write_all(b"OK\n").await?;
        }
        "CMD" => {
            let cmd = tail.trim().trim_start_matches(':').to_string();
            if cmd.is_empty() {
                write_half.write_all(b"ERR empty command\n").await?;
            } else {
                let _ = tx.send(ControlOp::Command(cmd));
                write_half.write_all(b"OK\n").await?;
            }
        }
        other => {
            write_half
                .write_all(
                    format!(
                        "ERR unknown op '{other}' (try: SCREEN | KEY <spec> | CMD <text> | STATE)\n"
                    )
                    .as_bytes(),
                )
                .await?;
        }
    }
    Ok(())
}

/// Render a ratatui [`Buffer`] to plain text by walking its cells row by row.
/// Trailing whitespace per line is stripped so the output is grep-friendly.
pub(crate) fn render_buffer_as_text(buf: &Buffer) -> String {
    let mut lines: Vec<String> = Vec::with_capacity(buf.area.height as usize);
    for y in 0..buf.area.height {
        let mut row = String::new();
        for x in 0..buf.area.width {
            let cell = &buf[(x, y)];
            row.push_str(cell.symbol());
        }
        lines.push(row.trim_end().to_string());
    }
    lines.join("\n")
}

/// Default control-socket path if the user doesn't pass one explicitly.
/// `~/.cache/ebman/control.sock`. The `ebman ctl` subcommand uses the same
/// default so the two halves rendezvous without any flag.
pub(crate) fn default_socket_path() -> PathBuf {
    let mut p = crate::util::cache_dir();
    p.push("control.sock");
    p
}

/// Parse a key spec into a crossterm `KeyEvent`. See the module-level docs
/// for the grammar. Returns `None` if no terminal key code could be parsed.
pub(crate) fn parse_key_spec(spec: &str) -> Option<KeyEvent> {
    let trimmed = spec.trim();
    if trimmed.is_empty() {
        return None;
    }
    let mut mods = KeyModifiers::NONE;
    let mut code: Option<KeyCode> = None;
    for piece in trimmed.split('+') {
        let piece = piece.trim();
        if piece.is_empty() {
            continue;
        }
        let lower = piece.to_ascii_lowercase();
        match lower.as_str() {
            "ctrl" | "control" | "^" => mods |= KeyModifiers::CONTROL,
            "shift" => mods |= KeyModifiers::SHIFT,
            "alt" | "meta" | "option" => mods |= KeyModifiers::ALT,
            "up" => code = Some(KeyCode::Up),
            "down" => code = Some(KeyCode::Down),
            "left" => code = Some(KeyCode::Left),
            "right" => code = Some(KeyCode::Right),
            "enter" | "return" => code = Some(KeyCode::Enter),
            "esc" | "escape" => code = Some(KeyCode::Esc),
            "tab" => code = Some(KeyCode::Tab),
            "backtab" => code = Some(KeyCode::BackTab),
            "backspace" => code = Some(KeyCode::Backspace),
            "delete" | "del" => code = Some(KeyCode::Delete),
            "home" => code = Some(KeyCode::Home),
            "end" => code = Some(KeyCode::End),
            "pageup" => code = Some(KeyCode::PageUp),
            "pagedown" => code = Some(KeyCode::PageDown),
            "space" => code = Some(KeyCode::Char(' ')),
            _ => {
                // Function keys: F1..F12 (case-insensitive)
                if let Some(num) = lower.strip_prefix('f').and_then(|n| n.parse::<u8>().ok()) {
                    if (1..=12).contains(&num) {
                        code = Some(KeyCode::F(num));
                        continue;
                    }
                }
                // `Char(x)` explicit form preserves case.
                if let Some(inner) = piece
                    .strip_prefix("Char(")
                    .and_then(|s| s.strip_suffix(')'))
                {
                    if let Some(c) = inner.chars().next() {
                        code = Some(KeyCode::Char(c));
                        continue;
                    }
                }
                // Single-character fallback preserves original case so the
                // caller can distinguish `J` (events cursor) from `j` (table move).
                if piece.chars().count() == 1 {
                    let c = piece.chars().next()?;
                    code = Some(KeyCode::Char(c));
                }
            }
        }
    }
    // `shift+tab` means BackTab. The loop splits on `+` before matching,
    // so the `"shift+tab"` alternative that used to sit beside
    // `"backtab"` was unreachable — the pieces are `shift` and `tab`, and
    // the spec came out as Tab+SHIFT. That is not a cosmetic difference:
    // the form handler matches `KeyCode::BackTab` to move BACK a field
    // and `KeyCode::Tab` to move forward, so `ebman ctl key shift+tab`
    // walked the wrong way. Normalising here rather than special-casing
    // the string keeps `Shift+Tab`, `tab+shift` and `SHIFT+TAB` all
    // working.
    if code == Some(KeyCode::Tab) && mods.contains(KeyModifiers::SHIFT) {
        code = Some(KeyCode::BackTab);
    }
    code.map(|c| KeyEvent::new(c, mods))
}

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

    #[test]
    fn parse_single_char_is_case_sensitive() {
        let k = parse_key_spec("j").unwrap();
        assert_eq!(k.code, KeyCode::Char('j'));
        let k = parse_key_spec("J").unwrap();
        assert_eq!(k.code, KeyCode::Char('J'));
    }

    #[test]
    fn parse_arrow_keys() {
        assert_eq!(parse_key_spec("Down").unwrap().code, KeyCode::Down);
        assert_eq!(parse_key_spec("up").unwrap().code, KeyCode::Up);
    }

    #[test]
    fn parse_ctrl_combinations() {
        let k = parse_key_spec("Ctrl+R").unwrap();
        assert_eq!(k.code, KeyCode::Char('R'));
        assert!(k.modifiers.contains(KeyModifiers::CONTROL));
    }

    #[test]
    fn parse_function_keys() {
        assert_eq!(parse_key_spec("F2").unwrap().code, KeyCode::F(2));
        assert_eq!(parse_key_spec("f12").unwrap().code, KeyCode::F(12));
        // Out of range → no parse.
        assert!(parse_key_spec("F13").is_none());
    }

    #[test]
    fn parse_explicit_char_form() {
        let k = parse_key_spec("Char(:)").unwrap();
        assert_eq!(k.code, KeyCode::Char(':'));
    }

    #[test]
    fn parse_space_keyword() {
        assert_eq!(parse_key_spec("Space").unwrap().code, KeyCode::Char(' '));
    }

    #[test]
    fn parse_empty_is_none() {
        assert!(parse_key_spec("").is_none());
        assert!(parse_key_spec("   ").is_none());
    }
}

#[cfg(test)]
mod peer_auth_tests {
    use super::{peer_is_owner, uid_is_allowed};

    // ── mutation-sweep triage, 2026-08-26 ────────────────────────────
    //
    // The peer-credential check is the authorisation on a socket that,
    // by its own comment, "drives arbitrary TUI commands including
    // `readonly off`". Every operator in it survived the sweep.

    /// The owner and root, and nobody else.
    #[test]
    fn only_the_owner_and_root_may_drive_the_socket() {
        assert!(uid_is_allowed(501, 501), "the owner");
        assert!(uid_is_allowed(0, 501), "root could read the socket anyway");
        assert!(uid_is_allowed(0, 0), "root owning it is still root");

        // `==` flipped to `!=` on the first comparison admits everyone
        // EXCEPT the owner. This is the case that catches it.
        assert!(
            !uid_is_allowed(502, 501),
            "another user must not drive this socket"
        );
        assert!(!uid_is_allowed(1, 501), "nor another system account");
        // `||` flipped to `&&` would refuse the owner — checked by the
        // first assertion — and `== 0` flipped to `!= 0` would admit
        // every non-root uid, checked by these.
        assert!(!uid_is_allowed(65534, 501), "nor nobody(65534)");
    }

    /// The wiring: a real socket pair, with the check reading real peer
    /// credentials rather than a number we passed in.
    #[tokio::test]
    async fn peer_is_owner_reads_real_peer_credentials() {
        let (a, _b) = tokio::net::UnixStream::pair().expect("socket pair");
        // Safe: getuid() cannot fail and takes no arguments.
        let me = unsafe { libc::getuid() };

        assert!(peer_is_owner(&a, Some(me)), "our own uid owns this socket");
        assert!(
            peer_is_owner(&a, None),
            "no owner recorded (non-unix socket_owner_uid) means no check \
             to make — the file permissions are the only gate there"
        );

        // A different uid is refused. Skipped when running as root,
        // where the `uid == 0` arm legitimately allows everything.
        if me != 0 {
            assert!(
                !peer_is_owner(&a, Some(me.wrapping_add(1))),
                "a socket owned by someone else must refuse us"
            );
        }
    }

    /// The listener must still refuse before handing the connection on.
    ///
    /// `if !peer_is_owner(..)` had its `!` deletable, which inverts the
    /// gate: only *non*-owners would get through. Neither test above
    /// notices — they exercise the decision, not the call site.
    #[test]
    fn the_listener_refuses_before_serving() {
        let src = std::fs::read_to_string("src/control.rs").expect("read control.rs");
        // Anchor on the definition at column zero. The first version of
        // this guard searched for `pub(crate) fn spawn_listener` — the
        // wrong visibility — and `split_once` happily matched the
        // occurrence inside THIS test, so the slice it checked was its
        // own assertion string. It passed against the very mutation it
        // exists to catch.
        let listener = src
            .split_once("\npub fn spawn_listener")
            .expect("spawn_listener moved or was renamed")
            .1;
        let listener = listener.split("\n}\n").next().unwrap_or(listener);
        assert!(
            !listener.contains("mod peer_auth_tests"),
            "the slice ran past the function into this test module, so it \
             would be checking its own source"
        );
        assert!(
            listener.contains("if !peer_is_owner(&stream, own_uid) {"),
            "spawn_listener must refuse a connection whose peer is not the \
             socket owner, BEFORE spawning handle_connection. Dropping the \
             `!` inverts the gate and serves only other users."
        );
        assert!(
            listener.contains("continue;"),
            "and the refusal must skip the connection rather than fall \
             through to serving it"
        );
    }
}

#[cfg(test)]
mod key_spec_tests {
    use super::parse_key_spec;
    use crossterm::event::{KeyCode, KeyModifiers};

    // ── mutation-sweep triage, 2026-08-26 ────────────────────────────
    //
    // 16 survivors, 14 of them deletable name→KeyCode arms. Asserting
    // twenty pairs would be a copy of the table; instead the table is
    // now documented in docs/headless.md as the contract a script
    // writes against, and this pins the parser to it in both
    // directions. Deleting an arm makes a multi-character name fall
    // through to the single-char fallback, which rejects it — so
    // "every documented name parses" catches all fourteen.

    /// Every name the docs advertise must parse.
    #[test]
    fn every_documented_key_name_parses() {
        let docs = std::fs::read_to_string("docs/headless.md").expect("read headless.md");
        let table = docs
            .split_once("### `ctl key` spec vocabulary")
            .expect("the ctl key vocabulary section is gone from the docs")
            .1;
        let table = table.split("\n##").next().unwrap_or(table);

        // Pull every `backtick`-quoted token out of the table rows,
        // remembering which row it came from: a modifier is not a spec
        // on its own — `ctrl` alone names no key and is correctly
        // rejected — so those are tested as `<mod>+x`.
        let mut names: Vec<(String, bool)> = Vec::new();
        for line in table.lines().filter(|l| l.trim_start().starts_with('|')) {
            let is_modifier_row = line.contains("| modifiers |");
            let mut rest = line;
            while let Some((_, after)) = rest.split_once('`') {
                let Some((tok, tail)) = after.split_once('`') else {
                    break;
                };
                rest = tail;
                // Skip prose tokens and the placeholder forms.
                if tok.contains(' ') || tok.contains('') || tok == "Char(x)" {
                    continue;
                }
                names.push((tok.to_string(), is_modifier_row));
            }
        }
        assert!(
            names.len() > 20,
            "only {} names scraped from the docs table — the scrape is \
             broken and this test would pass on nothing: {names:?}",
            names.len()
        );

        for (name, is_modifier) in &names {
            let spec = if *is_modifier {
                format!("{name}+x")
            } else {
                name.clone()
            };
            assert!(
                parse_key_spec(&spec).is_some(),
                "docs/headless.md advertises `{name}` as a ctl key spec, \
                 and the parser rejects {spec:?}"
            );
        }

        // A modifier on its own names no key and must stay rejected —
        // otherwise the `+x` above would be hiding a parser that accepts
        // anything.
        for (name, is_modifier) in &names {
            if *is_modifier {
                assert!(
                    parse_key_spec(name).is_none(),
                    "`{name}` is a modifier, not a key — it must not parse alone"
                );
            }
        }
    }

    /// And nothing the parser accepts is missing from the docs.
    #[test]
    fn every_key_name_the_parser_accepts_is_documented() {
        let src = std::fs::read_to_string("src/control.rs").expect("read control.rs");
        let body = src
            .split_once("\npub(crate) fn parse_key_spec")
            .expect("parse_key_spec moved or was renamed")
            .1;
        let body = body.split("\n}\n").next().unwrap_or(body);
        assert!(
            !body.contains("mod key_spec_tests"),
            "the slice ran past the function into this test module"
        );

        let docs = std::fs::read_to_string("docs/headless.md").expect("read headless.md");
        let mut undocumented = Vec::new();
        // Match-arm literals: `"name" =>` and `"a" | "b" =>`.
        for line in body.lines() {
            let trimmed = line.trim();
            if !trimmed.contains("=>") || !trimmed.starts_with('"') {
                continue;
            }
            let pat = trimmed.split("=>").next().unwrap_or("");
            for tok in pat.split('|') {
                let name = tok.trim().trim_matches('"').trim();
                if name.is_empty() {
                    continue;
                }
                if !docs.contains(&format!("`{name}`")) {
                    undocumented.push(name.to_string());
                }
            }
        }
        assert!(
            undocumented.is_empty(),
            "parse_key_spec accepts these and docs/headless.md doesn't \
             mention them, so a script author can only find them by \
             reading the source: {undocumented:?}"
        );
    }

    /// Modifiers accumulate. `|=` flipped to `&=` drops everything set
    /// before it, so a combo silently loses a modifier.
    #[test]
    fn modifiers_accumulate_in_any_order() {
        let k = parse_key_spec("ctrl+shift+alt+x").expect("parses");
        assert_eq!(k.code, KeyCode::Char('x'));
        assert!(k.modifiers.contains(KeyModifiers::CONTROL), "ctrl kept");
        assert!(k.modifiers.contains(KeyModifiers::SHIFT), "shift kept");
        assert!(k.modifiers.contains(KeyModifiers::ALT), "alt kept");

        // Order must not matter.
        let k = parse_key_spec("alt+ctrl+r").expect("parses");
        assert!(k.modifiers.contains(KeyModifiers::CONTROL));
        assert!(k.modifiers.contains(KeyModifiers::ALT));
        assert!(
            !k.modifiers.contains(KeyModifiers::SHIFT),
            "and only what was asked for"
        );
    }

    /// `shift+tab` is BackTab, not Tab-with-shift.
    ///
    /// The `"shift+tab"` alternative used to sit beside `"backtab"` in
    /// the match, where `split('+')` made it unreachable — so the spec
    /// produced Tab+SHIFT. The TUI binds BackTab to reverse cycling in
    /// three places (form fields, detail tabs, scope), all of which
    /// match `KeyCode::Tab` for the forward direction, so
    /// `ebman ctl key shift+tab` walked forwards.
    #[test]
    fn shift_tab_is_backtab() {
        for spec in [
            "shift+tab",
            "Shift+Tab",
            "tab+shift",
            "SHIFT+TAB",
            "backtab",
        ] {
            let k = parse_key_spec(spec).unwrap_or_else(|| panic!("{spec} must parse"));
            assert_eq!(
                k.code,
                KeyCode::BackTab,
                "{spec} must be BackTab — the TUI moves BACKWARD on it and \
                 forward on Tab"
            );
        }
        // A plain tab is still forward.
        assert_eq!(parse_key_spec("tab").unwrap().code, KeyCode::Tab);
    }

    /// A spec that names no key, or names one that doesn't exist, is
    /// rejected rather than guessed at.
    #[test]
    fn a_spec_with_no_key_is_rejected() {
        assert!(parse_key_spec("ctrl").is_none(), "modifiers alone");
        assert!(parse_key_spec("ctrl+shift").is_none());
        assert!(parse_key_spec("").is_none());
        assert!(parse_key_spec("   ").is_none());
        assert!(parse_key_spec("f13").is_none(), "out of the F1..F12 range");
        assert!(parse_key_spec("f0").is_none());
        assert!(parse_key_spec("pgup").is_none(), "not a name we accept");
    }
}