brgr-cli 2.15.9

Let Codex or Claude Code hand work to other coding agents, each in its own Herdr pane: the brgr CLI and Herdr plugin.
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
//! Whether `HERDR_PANE_ID` names the pane this process actually runs in.
//!
//! A process inherits `HERDR_PANE_ID` from whatever started it, and that is not
//! always its pane. Codex runs tool commands and hooks in a shared app-server
//! daemon, detached from every terminal, which keeps the Herdr environment of
//! the pane that first started it — a pane that may be closed, or may belong to
//! another Codex session. Trusting it made pane mode split beside a pane that
//! no longer existed (`pane_not_found`), and could have bound one Codex
//! session's completion notices to another session's pane.
//!
//! A process running in a Herdr pane descends from that pane's shell, which the
//! Herdr server started. So the claim is trusted only when walking up the
//! process tree reaches a `herdr` process, and no ancestor on the way carries a
//! different `HERDR_PANE_ID`. A daemon's chain ends at launchd and never
//! reaches Herdr.

use serde_json::Value;
use std::{
    collections::HashMap,
    env, fs,
    io::{Read as _, Seek as _},
    path::Path,
    process::Command,
};

/// The caller's Herdr pane, when this process provably runs inside it.
pub(crate) fn verified() -> Option<String> {
    if let Some(pane) = crate::invocation::current().pane.as_deref() {
        return named(pane);
    }
    let native = inherited();
    if native.is_some() {
        return native;
    }
    crate::current_session()
        .ok()
        .flatten()
        .and_then(|session| for_session(&session, crate::invocation::current().pane.as_deref()))
}

/// `--source-pane PANE`, checked against the caller's own session.
pub(crate) fn named(pane: &str) -> Option<String> {
    crate::current_session()
        .ok()
        .flatten()
        .and_then(|session| for_session(&session, Some(pane)))
        .or_else(|| crate::workflow::trusts_recorded_pane(pane).then(|| pane.to_owned()))
}

/// A pane that is alive and runs a harness that can receive `FROM BRGR`. It
/// proves the pane exists, not that the caller owns it, so it is only a check
/// on a pane some other step already verified.
pub(crate) fn live_owner_pane(pane: &str) -> Option<String> {
    live_kind(pane)
        .as_deref()
        .is_some_and(owner_inbox_kind)
        .then(|| pane.to_owned())
}

fn inherited() -> Option<String> {
    if env::var("HERDR_ENV").as_deref() != Ok("1") {
        return None;
    }
    let pane = env::var("HERDR_PANE_ID")
        .ok()
        .filter(|pane| !pane.trim().is_empty())?;
    #[cfg(debug_assertions)]
    if env::var("BRGR_TEST_TRUST_HERDR_PANE").as_deref() == Ok("1") {
        return Some(pane);
    }
    runs_inside(&pane).then_some(pane)
}

/// The Codex pane that runs `session`, proven from what the panes show.
///
/// Herdr's own record of which session a pane runs is not trusted: Codex runs
/// its hooks in a shared daemon whose environment names another session's pane,
/// so the record can bind a new session to the wrong pane. Instead the panes'
/// screens are read: Codex prints each command it runs, and a `brgr` command
/// carries its session, so exactly one Codex pane showing that call is the
/// caller's. Zero or several matches prove nothing, and nothing is guessed.
pub(crate) fn for_session(session: &str, explicit: Option<&str>) -> Option<String> {
    if let Some(pane) = traced(session) {
        return explicit
            .is_none_or(|expected| expected == pane)
            .then_some(pane);
    }
    // A pane this process provably runs inside needs no screen. Codex, Claude,
    // and Cursor owners all run in that pane; Codex's shared daemon is the
    // case that still needs a screen trace above.
    if let Some(pane) = explicit
        && inherited().as_deref() == Some(pane)
        && live_kind(pane).as_deref().is_some_and(owner_inbox_kind)
    {
        return Some(pane.to_owned());
    }
    bridge_receipt(session, explicit)
}

/// Herdr agent kinds that can receive `FROM BRGR` via `herdr agent prompt`.
pub(crate) fn owner_inbox_kind(kind: &str) -> bool {
    matches!(kind, "codex" | "claude" | "cursor")
}

/// The Herdr agent kind of the pane this process runs in, when that is known.
pub(crate) fn inherited_agent_kind() -> Option<String> {
    live_kind(&inherited()?)
}

/// Marks a launch whose caller pane is not known yet: Codex prints a command
/// only after it has finished, so the pane cannot be proven while the very
/// call that starts the task is still running.
const PENDING: &str = "session:";

pub(crate) fn pending_marker(session: &str) -> String {
    format!("{PENDING}{session}")
}

pub(crate) fn pending_session(caller: &str) -> Option<&str> {
    caller.strip_prefix(PENDING)
}

/// Waits for the call that started a task to finish and show up in its pane,
/// then returns that pane. `None` after `limit` means no Codex pane ever
/// showed it, and the caller must fail rather than guess.
pub(crate) fn wait_for_session(session: &str, limit: std::time::Duration) -> Option<String> {
    let started = std::time::Instant::now();
    loop {
        if let Some(pane) = traced(session) {
            return Some(pane);
        }
        if started.elapsed() >= limit {
            return None;
        }
        std::thread::sleep(std::time::Duration::from_millis(700));
    }
}

/// Codex shows `• Ran brgr --owner-session <id> ...` for a command it ran. A
/// narrow pane cuts the line, so the first characters of the id are enough.
const TRACE_PREFIX: usize = 13;

fn traced(session: &str) -> Option<String> {
    // A hook runs on every prompt under a tight time budget, and the call that
    // would show the session cannot be on a screen yet at session start.
    if crate::invocation::is_hook() {
        return None;
    }
    let prefix: String = session.chars().take(TRACE_PREFIX).collect();
    if prefix.chars().count() < TRACE_PREFIX {
        return None;
    }
    let agents = herdr_json(&["agent", "list"])?;
    let mut found = Vec::new();
    for item in agents.pointer("/result/agents")?.as_array()? {
        if item.get("agent").and_then(Value::as_str) != Some("codex") {
            continue;
        }
        let pane = item.get("pane_id").and_then(Value::as_str)?;
        let screen = herdr_text(&[
            "pane",
            "read",
            pane,
            "--source",
            "recent-unwrapped",
            "--lines",
            "1500",
        ])?;
        if shows_brgr_call(&screen, &prefix) {
            found.push(pane.to_owned());
        }
    }
    match found.as_slice() {
        [only] => Some(only.clone()),
        _ => None,
    }
}

/// The Codex release whose command lines these traces were checked against.
/// `brgr doctor` reports an installed Codex that differs from it.
pub(crate) const VERIFIED_CODEX: &str = "codex-cli 0.160";

/// A line where Codex says it ran (or is running) `brgr` with this session.
/// The id alone is not enough: any pane can print it.
fn shows_brgr_call(screen: &str, prefix: &str) -> bool {
    screen.lines().any(|line| {
        let line = line
            .trim_start()
            .trim_start_matches(['•', '└', '│'])
            .trim_start();
        ["Ran ", "Running ", "Run "]
            .iter()
            .find_map(|verb| line.strip_prefix(verb))
            .is_some_and(|command| command.contains(prefix) && invokes_brgr(command))
    })
}

/// Whether a shown command line runs brgr: as `brgr`, a path ending in
/// `/brgr`, or `$BRGR_BIN`, as the program of any `&&`, `;` or `|` segment,
/// after any `NAME=value` assignments. A command that only mentions brgr as an
/// argument (`grep brgr notes`) does not.
fn invokes_brgr(command: &str) -> bool {
    command.split(['&', ';', '|']).any(|segment| {
        segment
            .split_whitespace()
            .find(|word| !word.contains('='))
            .is_some_and(|program| {
                let program = program.trim_matches(['"', '\'']);
                program == "brgr"
                    || program.ends_with("/brgr")
                    || program == "$BRGR_BIN"
                    || program == "${BRGR_BIN}"
            })
    })
}

/// The installed Codex and whether it is the release the trace was checked
/// against. Informational: a newer Codex usually prints the same lines.
pub(crate) fn codex_trace_status() -> Value {
    let installed = std::process::Command::new("codex")
        .arg("--version")
        .output()
        .ok()
        .filter(|output| output.status.success())
        .and_then(|output| String::from_utf8(output.stdout).ok())
        .map(|text| text.trim().to_owned())
        .filter(|text| !text.is_empty());
    let verified = installed.as_deref().is_some_and(|version| {
        version == VERIFIED_CODEX || version.starts_with(&format!("{VERIFIED_CODEX}."))
    });
    serde_json::json!({
        "codex": installed,
        "verified_with": VERIFIED_CODEX,
        "verified": verified,
    })
}

fn live_kind(pane: &str) -> Option<String> {
    herdr_json(&["agent", "get", pane]).and_then(|live| {
        let agent = live.pointer("/result/agent")?;
        (agent.get("pane_id").and_then(Value::as_str) == Some(pane))
            .then(|| {
                agent
                    .get("agent")
                    .and_then(Value::as_str)
                    .map(str::to_owned)
            })
            .flatten()
    })
}

fn bridge_receipt(session: &str, explicit: Option<&str>) -> Option<String> {
    // Optional native frontend receipts also cover Codex versions where Herdr
    // has not reported the session yet. Match the exact session and live PID.
    let cwd = env::current_dir().ok()?;
    let mut roots = vec![cwd.clone()];
    if let Some(primary) = crate::workspace::primary_checkout(&cwd) {
        roots.push(primary);
    }
    for root in roots {
        let Ok(entries) = fs::read_dir(root.join(".agent-progress/bridges")) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().is_none_or(|v| v != "json") {
                continue;
            }
            let Ok(metadata) = fs::symlink_metadata(&path) else {
                continue;
            };
            if !metadata.is_file() || metadata.len() > 65_536 {
                continue;
            }
            let Some(record) = fs::read(&path)
                .ok()
                .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
            else {
                continue;
            };
            if record.get("native_session").and_then(Value::as_str) != Some(session)
                || record.get("session").and_then(Value::as_str) != Some(session)
            {
                continue;
            }
            let Some(pane) = record.get("pane").and_then(Value::as_str) else {
                continue;
            };
            if explicit.is_some_and(|expected| expected != pane) {
                continue;
            }
            let Some(pid) = record.get("pid").and_then(Value::as_u64) else {
                continue;
            };
            let Some(process) = herdr_json(&["pane", "process-info", "--pane", pane]) else {
                continue;
            };
            if contains_pid(&process, pid) {
                return Some(pane.to_owned());
            }
        }
    }
    None
}

fn contains_pid(value: &Value, pid: u64) -> bool {
    match value {
        Value::Object(fields) => fields.iter().any(|(key, value)| {
            (matches!(key.as_str(), "pid" | "foreground_process_group")
                && value.as_u64() == Some(pid))
                || contains_pid(value, pid)
        }),
        Value::Array(values) => values.iter().any(|v| contains_pid(v, pid)),
        _ => false,
    }
}

fn herdr_output(args: &[&str]) -> Option<Vec<u8>> {
    let binary = binary()?;
    let mut command = Command::new(binary);
    if let Ok(session) = env::var("HERDR_SESSION") {
        command.args(["--session", &session]);
    }
    let mut out = tempfile::tempfile().ok()?;
    let err = tempfile::tempfile().ok()?;
    let mut child = command
        .args(args)
        .stdin(std::process::Stdio::null())
        .stdout(out.try_clone().ok()?)
        .stderr(err)
        .spawn()
        .ok()?;
    let started = std::time::Instant::now();
    let status = loop {
        if let Some(status) = child.try_wait().ok()? {
            break status;
        }
        let budget = if crate::invocation::is_hook() {
            200
        } else {
            2000
        };
        if started.elapsed() > std::time::Duration::from_millis(budget) {
            let _ = child.kill();
            let _ = child.wait();
            return None;
        }
        std::thread::sleep(std::time::Duration::from_millis(5));
    };
    if !status.success() || out.metadata().ok()?.len() > 1024 * 1024 {
        return None;
    }
    out.rewind().ok()?;
    let mut bytes = Vec::new();
    out.take(1024 * 1024 + 1).read_to_end(&mut bytes).ok()?;
    Some(bytes)
}

fn herdr_json(args: &[&str]) -> Option<Value> {
    serde_json::from_slice(&herdr_output(args)?).ok()
}

fn herdr_text(args: &[&str]) -> Option<String> {
    Some(String::from_utf8_lossy(&herdr_output(args)?).into_owned())
}

pub(crate) fn binary() -> Option<std::ffi::OsString> {
    #[cfg(test)]
    if let Some(path) = tests::HERDR.with(|slot| slot.borrow().clone()) {
        return Some(path.into_os_string());
    }
    if let Some(path) = env::var_os("HERDR_BIN_PATH") {
        return Some(path);
    }
    let path = env::var_os("PATH")?;
    env::split_paths(&path)
        .map(|dir| dir.join("herdr"))
        .find(|p| p.is_file())
        .and_then(|p| p.canonicalize().ok())
        .map(std::path::PathBuf::into_os_string)
}

/// Walks this process's ancestors to the Herdr server.
fn runs_inside(pane: &str) -> bool {
    let Some(table) = process_table() else {
        return false;
    };
    let mut pid = std::process::id();
    for _ in 0..64 {
        let Some((parent, command)) = table.get(&pid) else {
            return false;
        };
        if Path::new(command)
            .file_name()
            .is_some_and(|name| name == "herdr")
        {
            return true;
        }
        if pane_in_environment(pid).is_some_and(|claimed| claimed != pane) {
            return false;
        }
        if *parent <= 1 {
            return false;
        }
        pid = *parent;
    }
    false
}

/// Every process's parent and executable, from one `ps` call.
fn process_table() -> Option<HashMap<u32, (u32, String)>> {
    let output = Command::new("/bin/ps")
        .args(["-A", "-o", "pid=,ppid=,comm="])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout);
    Some(
        text.lines()
            .filter_map(|line| {
                let mut fields = line.split_whitespace();
                let pid = fields.next()?.parse().ok()?;
                let parent = fields.next()?.parse().ok()?;
                let command = fields.collect::<Vec<_>>().join(" ");
                Some((pid, (parent, command)))
            })
            .collect(),
    )
}

/// The `HERDR_PANE_ID` in a process's environment, when `ps` can read it.
/// `ps -E` prints the arguments before the environment, so the last match is
/// the environment's.
fn pane_in_environment(pid: u32) -> Option<String> {
    let output = Command::new("/bin/ps")
        .args(["-E", "-ww", "-o", "command=", "-p", &pid.to_string()])
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&output.stdout);
    let (_, rest) = text.rsplit_once(" HERDR_PANE_ID=")?;
    rest.split_whitespace().next().map(str::to_owned)
}

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

    const SESSION: &str = "01a0fb33-447c-7ba0-9f37-ba04f33ce809";

    #[test]
    fn a_ran_line_with_the_session_is_the_trace() {
        let ran = format!("• Ran brgr --as {SESSION} run \"Run the sh…");
        assert!(shows_brgr_call(&ran, "01a0fb33-447c"));
        // A pane too narrow for the whole id still shows its first characters.
        assert!(shows_brgr_call(
            "• Ran brgr --as 01a0fb33-447c…",
            "01a0fb33-447c"
        ));
        assert!(shows_brgr_call(
            &format!("• Running brgr --as {SESSION} status"),
            "01a0fb33-447c"
        ));
    }

    #[test]
    fn a_path_variable_or_cd_prefixed_call_is_a_trace() {
        for line in [
            format!("• Ran /Users/me/.local/bin/brgr --as {SESSION} status"),
            format!("• Ran $BRGR_BIN --as {SESSION} result"),
            format!("• Ran cd /repo && brgr --as {SESSION} run \"x\""),
            format!("• Ran BRGR_HOME=/tmp/h brgr --as {SESSION} status"),
            format!("  └ Run brgr --as {SESSION} wait"),
        ] {
            assert!(shows_brgr_call(&line, "01a0fb33-447c"), "{line}");
        }
    }

    #[test]
    fn brgr_as_an_argument_is_not_a_trace() {
        assert!(!shows_brgr_call(
            &format!("• Ran grep brgr notes.txt {SESSION}"),
            "01a0fb33-447c"
        ));
        assert!(!shows_brgr_call(
            &format!("• Ran echo brgr --as {SESSION}"),
            "01a0fb33-447c"
        ));
    }

    #[test]
    fn the_bare_id_or_another_command_is_not_a_trace() {
        // Any pane can print the id: a chat message, a pasted log, a Claude pane.
        assert!(!shows_brgr_call(
            &format!("the session is {SESSION}"),
            "01a0fb33-447c"
        ));
        assert!(!shows_brgr_call(
            &format!("• Ran echo {SESSION}"),
            "01a0fb33-447c"
        ));
        assert!(!shows_brgr_call(
            "• Ran brgr --as 11111111-2222 run",
            "01a0fb33-447c"
        ));
        // The user's own prompt quoting a command is not a command Codex ran.
        assert!(!shows_brgr_call(
            &format!("› please run brgr --as {SESSION} status"),
            "01a0fb33-447c"
        ));
    }

    /// A fake Herdr that lists Codex, Claude and shell panes and serves their
    /// screens from files, so `traced` runs end to end.
    fn fake_herdr(screens: &[(&str, &str, &str)]) -> (tempfile::TempDir, std::path::PathBuf) {
        use std::os::unix::fs::PermissionsExt as _;
        let temp = tempfile::tempdir().unwrap();
        let mut agents = Vec::new();
        for (pane, kind, screen) in screens {
            fs::write(temp.path().join(pane.replace(':', "_")), screen).unwrap();
            agents.push(format!(r#"{{"pane_id":"{pane}","agent":"{kind}"}}"#));
        }
        fs::write(
            temp.path().join("list.json"),
            format!(r#"{{"result":{{"agents":[{}]}}}}"#, agents.join(",")),
        )
        .unwrap();
        let binary = temp.path().join("herdr");
        fs::write(
            &binary,
            "#!/bin/sh\nd=$(/usr/bin/dirname \"$0\")\nif [ \"$1\" = --session ]; then shift 2; fi\ncase \"$1 $2\" in\n 'agent list') /bin/cat \"$d/list.json\";;\n 'pane read') f=$(printf %s \"$3\" | /usr/bin/sed 's/:/_/'); /bin/cat \"$d/$f\";;\n *) exit 2;;\nesac\n",
        )
        .unwrap();
        fs::set_permissions(&binary, fs::Permissions::from_mode(0o700)).unwrap();
        (temp, binary)
    }

    fn trace_with(screens: &[(&str, &str, &str)]) -> Option<String> {
        let (_temp, binary) = fake_herdr(screens);
        with_herdr(&binary, || traced(SESSION))
    }

    thread_local! {
        pub(super) static HERDR: std::cell::RefCell<Option<std::path::PathBuf>> =
            const { std::cell::RefCell::new(None) };
    }

    fn with_herdr<T>(binary: &Path, run: impl FnOnce() -> T) -> T {
        HERDR.with(|slot| *slot.borrow_mut() = Some(binary.to_path_buf()));
        let out = run();
        HERDR.with(|slot| *slot.borrow_mut() = None);
        out
    }

    /// `herdr_output` forwards `HERDR_SESSION` as `--session`. The fixture must
    /// still serve `agent list` and `pane read` when that flag is present, so
    /// these tests do not depend on the variable being unset.
    #[test]
    fn a_session_flag_does_not_hide_the_fixture_panes() {
        let (_temp, binary) = fake_herdr(&[("w1:p2", "codex", "idle")]);
        let list = Command::new(&binary)
            .args(["--session", "ambient-session", "agent", "list"])
            .output()
            .unwrap();
        assert!(
            list.status.success(),
            "{}",
            String::from_utf8_lossy(&list.stderr)
        );
        let agents: Value = serde_json::from_slice(&list.stdout).unwrap();
        assert_eq!(
            agents
                .pointer("/result/agents/0/pane_id")
                .and_then(Value::as_str),
            Some("w1:p2")
        );
        let screen = Command::new(&binary)
            .args(["--session", "ambient-session", "pane", "read", "w1:p2"])
            .output()
            .unwrap();
        assert!(screen.status.success());
        assert_eq!(String::from_utf8_lossy(&screen.stdout), "idle");
    }

    #[test]
    fn exactly_one_codex_pane_showing_the_call_is_the_callers() {
        let ran = format!("• Ran brgr --as {SESSION} run \"x\"");
        let found = trace_with(&[
            ("w1:p1", "codex", "• Ran echo hello"),
            ("w1:p2", "codex", &ran),
            ("w1:p3", "codex", "idle"),
        ]);
        assert_eq!(found.as_deref(), Some("w1:p2"));
    }

    #[test]
    fn no_pane_or_two_panes_prove_nothing() {
        let ran = format!("• Ran brgr --as {SESSION} run \"x\"");
        assert_eq!(trace_with(&[("w1:p1", "codex", "nothing")]), None);
        assert_eq!(
            trace_with(&[("w1:p1", "codex", &ran), ("w1:p2", "codex", &ran)]),
            None
        );
    }

    /// D14: Herdr's record said this session ran in the wrong pane, because the
    /// Codex hook reported the shared daemon's pane. The record is ignored.
    #[test]
    fn a_poisoned_herdr_session_record_does_not_move_the_session() {
        let ran = format!("• Ran brgr --as {SESSION} run \"x\"");
        let (temp, binary) = fake_herdr(&[
            ("w6G:p1", "codex", "other work"),
            ("w5G:p30", "codex", &ran),
        ]);
        fs::write(
            temp.path().join("list.json"),
            format!(
                r#"{{"result":{{"agents":[{{"pane_id":"w6G:p1","agent":"codex","agent_session":{{"value":"{SESSION}"}}}},{{"pane_id":"w5G:p30","agent":"codex"}}]}}}}"#
            ),
        )
        .unwrap();
        let found = with_herdr(&binary, || for_session(SESSION, None));
        assert_eq!(found.as_deref(), Some("w5G:p30"));
        // A caller that names the poisoned pane is refused, not believed.
        let named = with_herdr(&binary, || for_session(SESSION, Some("w6G:p1")));
        assert_eq!(named, None);
    }

    #[test]
    fn a_pane_that_is_not_codex_never_counts() {
        // This session's own conversation printed the id in a Claude pane.
        let ran = format!("• Ran brgr --as {SESSION} run \"x\"");
        let found = trace_with(&[("w1:p1", "claude", &ran), ("w1:p2", "codex", &ran)]);
        assert_eq!(found.as_deref(), Some("w1:p2"));
    }

    /// This test process's own chain: either it never reaches Herdr (CI), or it
    /// does through a pane whose id is not the one claimed here.
    #[test]
    fn an_unrelated_pane_claim_is_not_trusted() {
        assert!(!runs_inside("w999:p999-not-a-real-pane"));
    }

    #[test]
    fn the_process_table_includes_this_process() {
        let table = process_table().unwrap();
        assert!(table.contains_key(&std::process::id()));
    }
}