brgr-cli 2.15.3

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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use std::{
    env,
    fs::{self, OpenOptions, TryLockError},
    os::unix::fs::OpenOptionsExt as _,
    os::unix::process::CommandExt as _,
    path::{Path, PathBuf},
    process::{Command, Stdio},
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use anyhow::{Context as _, Result, bail};
use brgr_protocol::{OwnerId, TaskId, TaskSpec, TerminalOutcome};
use brgr_store::{NotificationTarget, QuestionTarget, Store, StoreError};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::time::{sleep, timeout};
use uuid::Uuid;

use crate::{Paths, plugin_bridge};

const POLL_INTERVAL: Duration = Duration::from_millis(500);
/// The longest wait between delivery attempts while the owner stays busy.
const MAX_BACKOFF: Duration = Duration::from_secs(3);
const MAX_LIFETIME: Duration = Duration::from_hours(24);
const HERDR_TIMEOUT: Duration = Duration::from_secs(5);

pub async fn register_current_surface(
    paths: &Paths,
    store: &Store,
    owner_id: &OwnerId,
    session_id: &str,
) -> Result<bool> {
    if owner_id.as_str().starts_with("worker:") {
        return register_worker_surface(paths, store, owner_id, session_id);
    }
    let Some(kind) = owner_agent(owner_id.as_str()) else {
        return Ok(false);
    };
    // A hook Codex runs from its shared app-server daemon carries the Herdr
    // environment of whichever pane started that daemon. Registering that pane
    // would push this session's notices into another session.
    let (Some(pane), Some(binary)) = (
        crate::caller_pane::for_session(session_id, crate::invocation::current().pane.as_deref())
            .or_else(|| {
                (crate::current_session().ok().flatten().as_deref() == Some(session_id))
                    .then(crate::caller_pane::verified)
                    .flatten()
            }),
        crate::caller_pane::binary(),
    ) else {
        return Ok(false);
    };
    let binary = PathBuf::from(binary);
    if pane.is_empty() || !binary.is_absolute() || !binary.is_file() {
        return Ok(false);
    }
    let (bound_session, epoch) = store
        .owner_binding(owner_id)?
        .context("Codex owner has no session binding")?;
    if bound_session != session_id {
        return Ok(false);
    }
    let binary = binary
        .to_str()
        .context("Herdr executable path is not UTF-8")?;
    let herdr_session = env::var("HERDR_SESSION").ok();
    let agent = recorded_agent(binary, herdr_session.as_deref(), &pane).await?;
    let recorded_kind = agent.get("agent").and_then(Value::as_str);
    if recorded_kind.is_some_and(|found| !crate::caller_pane::owner_inbox_kind(found)) {
        eprintln!(
            "brgr: Herdr agent {} is not an owner inbox; FROM BRGR will not arrive. Use `brgr watch`.",
            recorded_kind.unwrap_or("unknown")
        );
        return Ok(false);
    }
    if recorded_kind != Some(kind)
        || agent.get("pane_id").and_then(Value::as_str) != Some(pane.as_ref())
    {
        bail!("recorded Herdr pane is not the current owner agent");
    }
    // Herdr keeps no session id for a Claude Code or Cursor agent. The Claude
    // Code process this command runs under is recorded instead; Cursor runs in
    // the pane. Codex is bound to its exact session below.
    if kind != "codex" {
        if kind == "claude"
            && let Some(owner) = claude_ancestor(&pane)
        {
            record_claude_owner(paths, session_id, &owner)?;
        }
        store.register_owner_surface(
            owner_id,
            session_id,
            epoch,
            &pane,
            herdr_session.as_deref(),
            binary,
        )?;
        return Ok(true);
    }
    ensure_codex_session_reported(binary, herdr_session.as_deref(), &pane, session_id, &agent)
        .await?;
    store.register_owner_surface(
        owner_id,
        session_id,
        epoch,
        &pane,
        herdr_session.as_deref(),
        binary,
    )?;
    Ok(true)
}

async fn ensure_codex_session_reported(
    binary: &str,
    herdr_session: Option<&str>,
    pane: &str,
    session_id: &str,
    agent: &Value,
) -> Result<()> {
    match agent
        .pointer("/agent_session/value")
        .and_then(Value::as_str)
    {
        Some(observed) if observed == session_id => Ok(()),
        Some(_) => bail!("recorded Herdr Codex session differs from the owner binding"),
        None => {
            let mut report = surface_command(binary, herdr_session);
            report.args([
                "pane",
                "report-agent-session",
                pane,
                "--source",
                "herdr:codex",
                "--agent",
                "codex",
                "--agent-session-id",
                session_id,
            ]);
            let output = timeout(HERDR_TIMEOUT, report.kill_on_drop(true).output())
                .await
                .context("Herdr Codex session report timed out")??;
            if !output.status.success() {
                bail!("Herdr did not accept the Codex session report");
            }
            let reported = recorded_agent(binary, herdr_session, pane).await?;
            if reported.get("agent").and_then(Value::as_str) != Some("codex")
                || reported.get("pane_id").and_then(Value::as_str) != Some(pane)
                || reported
                    .pointer("/agent_session/value")
                    .and_then(Value::as_str)
                    != Some(session_id)
            {
                bail!("Herdr did not bind the exact Codex session to the pane");
            }
            Ok(())
        }
    }
}

fn register_worker_surface(
    paths: &Paths,
    store: &Store,
    owner_id: &OwnerId,
    session_id: &str,
) -> Result<bool> {
    let attempt = owner_id
        .as_str()
        .trim_start_matches("worker:")
        .parse::<brgr_protocol::AttemptId>()?;
    let parent = store
        .unfinished_attempts()?
        .into_iter()
        .find(|item| item.attempt_id == attempt)
        .context("parent worker attempt is not active")?;
    let source =
        crate::pane_adapter::session_status(paths, parent.task.task_id, parent.task.revision)
            .context("parent has no native TUI session")?;
    let pane = source
        .get("pane")
        .and_then(Value::as_str)
        .context("parent TUI pane is missing")?;
    let binary = crate::caller_pane::binary().context("Herdr executable missing")?;
    let (bound, epoch) = store
        .owner_binding(owner_id)?
        .context("worker owner binding missing")?;
    if bound != session_id {
        bail!("worker session differs from owner binding");
    }
    store.register_owner_surface(
        owner_id,
        session_id,
        epoch,
        pane,
        env::var("HERDR_SESSION").ok().as_deref(),
        binary.to_str().context("Herdr path is not UTF-8")?,
    )?;
    Ok(true)
}

pub fn spawn_registration_and_delivery(paths: &Paths, task: &TaskSpec, session: Option<&str>) {
    if crate::config::Config::load(&paths.config)
        .is_ok_and(|config| config.calling(&task.route.harness_id).notifications == Some(false))
    {
        return;
    }
    if session.is_none()
        || (crate::invocation::current().pane.is_none()
            && (env::var("HERDR_ENV").as_deref() != Ok("1")
                || env::var_os("HERDR_PANE_ID").is_none()))
        || !(task.owner_id.as_str().starts_with("codex:")
            || task.owner_id.as_str().starts_with("claude:")
            || task.owner_id.as_str().starts_with("cursor:")
            || task.owner_id.as_str().starts_with("worker:"))
        || crate::caller_pane::binary().is_none()
    {
        return;
    }
    if let Err(error) = spawn_for_task(paths, task.task_id) {
        eprintln!("brgr completion notification remains queued: {error}");
    }
}

async fn recorded_agent(binary: &str, herdr_session: Option<&str>, pane: &str) -> Result<Value> {
    let mut get = surface_command(binary, herdr_session);
    get.args(["agent", "get", pane]);
    let output = timeout(HERDR_TIMEOUT, get.kill_on_drop(true).output())
        .await
        .context("Herdr Codex pane lookup timed out")??;
    if !output.status.success() || output.stdout.len() > 65_536 {
        bail!("recorded Codex pane is unavailable");
    }
    let state: Value = serde_json::from_slice(&output.stdout)?;
    state
        .pointer("/result/agent")
        .cloned()
        .context("Herdr did not return a Codex agent")
}

fn surface_command(binary: &str, herdr_session: Option<&str>) -> tokio::process::Command {
    let mut command = tokio::process::Command::new(binary);
    if let Some(session) = herdr_session {
        command.arg("--session").arg(session);
    }
    command
}

pub fn spawn_for_task(paths: &Paths, task: TaskId) -> Result<()> {
    if !notifications_enabled(paths, task)? {
        return Ok(());
    }
    let mut command = Command::new(env::current_exe()?);
    let log = OpenOptions::new()
        .create(true)
        .append(true)
        .mode(0o600)
        .open(paths.runs.join(format!("{task}.notify.log")))?;
    if let Ok(store) = Store::open(&paths.store)
        && let Ok(spec) = store.task(task)
        && let Ok(Some((session, _))) = store.owner_binding(&spec.owner_id)
    {
        command.args(["--owner-session", &session]);
        if let Some(pane) = fs::read(paths.launch(task, spec.revision))
            .ok()
            .and_then(|bytes| serde_json::from_slice::<crate::LaunchEnvelope>(&bytes).ok())
            .and_then(|launch| launch.source_pane)
            .filter(|pane| crate::caller_pane::pending_session(pane).is_none())
        {
            command.args(["--source-pane", &pane]);
        }
    }
    command
        .arg("--home")
        .arg(&paths.home)
        .arg("__notify")
        .arg(task.to_string())
        .env_remove(plugin_bridge::BRIDGE_DIR_ENV)
        .env_remove(plugin_bridge::BRIDGE_HOST_HOME_ENV)
        .env_remove(plugin_bridge::BRIDGE_HOST_WORKSPACE_ENV)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::from(log));
    command.process_group(0);
    command
        .spawn()
        .context("brgr notification dispatcher could not start")?;
    Ok(())
}

pub async fn deliver_pending(paths: &Paths, task: TaskId) -> Result<()> {
    if !notifications_enabled(paths, task)? {
        return Ok(());
    }
    let lock = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .mode(0o600)
        .open(paths.runs.join(format!("{task}.notify.lock")))?;
    match lock.try_lock() {
        Ok(()) => {}
        Err(TryLockError::WouldBlock) => return Ok(()),
        Err(error) => return Err(error.into()),
    }
    // Keep this descriptor alive throughout delivery. The OS releases the
    // lock after a crash, so a later hook may resume the durable queue.
    let _lock = lock;
    let started = Instant::now();
    let store = open_store(paths, started).await?;
    // A finished task with nothing left to send exits before anything else:
    // proving the owner's pane reads every Codex pane, which takes seconds.
    if settled(&store, task)? {
        return Ok(());
    }
    let mut registered = register_for_task(paths, &store, task).await;
    let mut next_try = Instant::now() + Duration::from_secs(2);
    let mut gap = Duration::from_secs(2);
    let database = paths.store.join("brgr.sqlite3");
    let mut backoff = POLL_INTERVAL;
    while started.elapsed() < MAX_LIFETIME {
        // An open connection keeps reading a deleted database, so a dispatcher
        // whose control home was removed polled a dead store for a day. Test
        // suites delete their homes; each run left one such process behind.
        if !database.exists() {
            return Ok(());
        }
        // The owner's pane may only be provable once the call that started this
        // task has finished and shown up on its screen, so keep trying.
        if !registered && Instant::now() >= next_try {
            registered = register_for_task(paths, &store, task).await;
            gap = (gap * 2).min(Duration::from_mins(1));
            next_try = Instant::now() + gap;
        }
        deliver_questions(paths, &store, task).await;
        let pending = match store.pending_notifications_for_task(task) {
            Ok(pending) => pending,
            Err(error) if error.is_retryable_database_contention() => {
                sleep(POLL_INTERVAL).await;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        if pending.is_empty() {
            match settled(&store, task) {
                Ok(true) => return Ok(()),
                Ok(false) => {}
                Err(error) => return Err(error),
            }
            sleep(POLL_INTERVAL).await;
            continue;
        }
        let mut failed = false;
        for notice in pending {
            let token = Uuid::new_v4().to_string();
            let now = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs())?;
            let claimed = match store.claim_notification(notice.result_id, &token, now, 20) {
                Ok(claimed) => claimed,
                Err(error) if error.is_retryable_database_contention() => continue,
                Err(error) => return Err(error.into()),
            };
            let Some(target) = claimed else {
                continue;
            };
            match try_deliver(paths, &target).await {
                Ok(()) => mark_delivered(&store, &target, &token).await?,
                Err(error) => {
                    failed = true;
                    if let Err(release_error) = store.release_notification_claim(
                        notice.result_id,
                        &token,
                        &error.to_string(),
                    ) && !release_error.is_retryable_database_contention()
                    {
                        return Err(release_error.into());
                    }
                }
            }
        }
        // A busy owner is retried at a growing interval, not twice a second.
        backoff = if failed {
            (backoff * 2).min(MAX_BACKOFF)
        } else {
            POLL_INTERVAL
        };
        sleep(backoff).await;
    }
    Ok(())
}

/// The prompt was accepted. Keep the lease while retrying its receipt, so
/// transient database contention does not trigger another prompt.
async fn mark_delivered(store: &Store, target: &NotificationTarget, token: &str) -> Result<()> {
    let started = Instant::now();
    loop {
        match store.mark_notification_delivered(target, token) {
            Ok(()) | Err(StoreError::NotificationClaimStale) => return Ok(()),
            Err(error)
                if error.is_retryable_database_contention()
                    && started.elapsed() < Duration::from_secs(15) =>
            {
                sleep(POLL_INTERVAL).await;
            }
            Err(error) => return Err(error.into()),
        }
    }
}

fn notifications_enabled(paths: &Paths, task: TaskId) -> Result<bool> {
    let store = Store::open(&paths.store)?;
    let spec = store.task(task)?;
    Ok(crate::config::Config::load(&paths.config)?
        .calling(&spec.route.harness_id)
        .notifications
        != Some(false))
}

async fn open_store(paths: &Paths, started: Instant) -> Result<Store> {
    loop {
        match Store::open(&paths.store) {
            Ok(store) => return Ok(store),
            Err(error)
                if error.is_retryable_database_contention() && started.elapsed() < MAX_LIFETIME =>
            {
                sleep(POLL_INTERVAL).await;
            }
            Err(error) => return Err(error.into()),
        }
    }
}

/// Whether the task's run is over and nothing is left to send.
fn settled(store: &Store, task: TaskId) -> Result<bool> {
    let pending = match store.pending_notifications_for_task(task) {
        Ok(pending) => pending,
        Err(error) if error.is_retryable_database_contention() => return Ok(false),
        Err(error) => return Err(error.into()),
    };
    if !pending.is_empty() {
        return Ok(false);
    }
    match store.latest_result(task) {
        Ok(result)
            if result.outcome != TerminalOutcome::Failed
                || store.run_completed(result.result_id).unwrap_or(false) =>
        {
            // Result and notification commit together. Re-read after seeing
            // the result so a concurrent terminal commit cannot be missed.
            match store.pending_notifications_for_task(task) {
                Ok(pending) => Ok(pending.is_empty()),
                Err(error) if error.is_retryable_database_contention() => Ok(false),
                Err(error) => Err(error.into()),
            }
        }
        // A failed spawn may receive a bounded automatic retry. Its first
        // result is not proof that this task's run is finished.
        Ok(_) | Err(StoreError::TaskNotFound(_)) => Ok(false),
        Err(error) => Err(error.into()),
    }
}

/// Registers the task owner's pane when it can be proven now.
async fn register_for_task(paths: &Paths, store: &Store, task: TaskId) -> bool {
    let Ok(spec) = store.task(task) else {
        return false;
    };
    let Ok(Some((session, _))) = store.owner_binding(&spec.owner_id) else {
        return false;
    };
    // Already proven and recorded (a Claude Code owner's shell does it at
    // admission): rescanning every Codex pane would only repeat it.
    if store
        .owner_surface_pane(&spec.owner_id, &session)
        .ok()
        .flatten()
        .is_some()
    {
        return true;
    }
    register_current_surface(paths, store, &spec.owner_id, &session)
        .await
        .unwrap_or(false)
}

/// The owner's Codex pane, as the store recorded it for the bound session.
struct OwnerPane<'a> {
    herdr_bin: &'a str,
    herdr_session: Option<&'a str>,
    pane_id: &'a str,
    session_id: &'a str,
    owner_kind: &'a str,
}

/// The Claude Code process that registered an owner session's pane.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct ClaudeOwnerProcess {
    pane: String,
    pid: u32,
    birth: String,
}

fn claude_owner_path(paths: &Paths, session_id: &str) -> Option<PathBuf> {
    (!session_id.is_empty()
        && session_id
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || character == '-'))
    .then(|| paths.runs.join(format!("claude-owner-{session_id}.json")))
}

fn record_claude_owner(paths: &Paths, session_id: &str, owner: &ClaudeOwnerProcess) -> Result<()> {
    if let Some(path) = claude_owner_path(paths, session_id) {
        crate::write_json_atomic(&path, &serde_json::to_value(owner)?)?;
    }
    Ok(())
}

/// The nearest ancestor of this process that is Claude Code: the session
/// whose shell ran this brgr command.
fn claude_ancestor(pane: &str) -> Option<ClaudeOwnerProcess> {
    let mut pid = std::process::id();
    for _ in 0..32 {
        let parent: u32 = crate::supervision::ps_field(&pid.to_string(), "ppid")
            .ok()?
            .parse()
            .ok()?;
        if parent <= 1 {
            return None;
        }
        let command = crate::supervision::ps_field(&parent.to_string(), "comm").ok()?;
        if Path::new(&command)
            .file_name()
            .is_some_and(|name| name == "claude")
        {
            return Some(ClaudeOwnerProcess {
                pane: pane.to_owned(),
                pid: parent,
                birth: crate::supervision::ps_field(&parent.to_string(), "lstart").ok()?,
            });
        }
        pid = parent;
    }
    None
}

/// Fails when the Claude Code process that registered this owner session no
/// longer runs, or registered another pane. A session registered before this
/// record existed keeps the pane-and-kind check alone.
fn claude_owner_present(paths: &Paths, session_id: &str, pane: &str) -> Result<()> {
    let Some(bytes) = claude_owner_path(paths, session_id).and_then(|path| fs::read(path).ok())
    else {
        return Ok(());
    };
    let owner: ClaudeOwnerProcess = serde_json::from_slice(&bytes)?;
    let alive = crate::supervision::ps_field(&owner.pid.to_string(), "lstart")
        .is_ok_and(|birth| birth == owner.birth);
    if owner.pane != pane || !alive {
        bail!("the Claude Code session that owns this task no longer runs in pane {pane}");
    }
    Ok(())
}

/// The Herdr agent kind an owner runs as.
fn owner_agent(owner_id: &str) -> Option<&'static str> {
    if owner_id.starts_with("claude:") {
        Some("claude")
    } else if owner_id.starts_with("cursor:") {
        Some("cursor")
    } else if owner_id.starts_with("codex:") {
        Some("codex")
    } else {
        None
    }
}

async fn try_deliver(paths: &Paths, target: &NotificationTarget) -> Result<()> {
    let task = target.task_id;
    // A run that did not produce a candidate is a failure the owner must act
    // on, not a result to verify, so it is announced as one with its reason.
    let failure = Store::open(&paths.store)
        .ok()
        .and_then(|store| store.latest_result(task).ok())
        .filter(|result| {
            result.result_id == target.result_id
                && matches!(
                    result.outcome,
                    TerminalOutcome::Failed | TerminalOutcome::Lost
                )
        });
    let body = if let Some(result) = failure {
        format!(
            "FROM BRGR\n{}",
            json!({
                "type": "brgr_failure",
                "completion_id": target.result_id,
                "task_id": task,
                "outcome": if result.outcome == TerminalOutcome::Lost { "lost" } else { "failed" },
                "reason": result.error.as_deref().unwrap_or("no error text"),
                "instruction": format!("A brgr run failed. Inspect it with `brgr result {task}`. Retry with `brgr revise {task} \"corrected request\"`, or dismiss it with `brgr result {task} --ack`. Do not treat this notification as acceptance.")
            })
        )
    } else {
        format!(
            "FROM BRGR\n{}",
            json!({
                "type": "brgr_completion",
                "completion_id": target.result_id,
                "task_id": task,
                "instruction": "Read the sealed brgr result, verify its criteria, and decide or acknowledge it. Do not treat this notification as acceptance."
            })
        )
    };
    prompt_owner(
        paths,
        &OwnerPane {
            herdr_bin: &target.herdr_bin,
            herdr_session: target.herdr_session.as_deref(),
            pane_id: &target.pane_id,
            session_id: &target.session_id,
            owner_kind: owner_agent(target.owner_id.as_str()).unwrap_or("codex"),
        },
        &body,
    )
    .await
}

/// Tells the owner's idle Codex pane that a worker is waiting on its answer.
///
/// Only completions used to reach the owner, so a worker's question sat until
/// the worker's own wait timed out. Best effort each poll: a busy or missing
/// pane leaves the question pending for the next one, and `brgr status --tree`
/// still shows it.
async fn deliver_questions(paths: &Paths, store: &Store, task: TaskId) {
    let Ok(pending) = store.pending_question_notices(task) else {
        return;
    };
    for target in pending {
        if deliver_question(paths, &target).await.is_ok() {
            let _ = store.record_question_notice(&target.message_id, &target.session_id);
        }
    }
}

async fn deliver_question(paths: &Paths, target: &QuestionTarget) -> Result<()> {
    let task = target.task_id;
    let message = &target.message_id;
    let body = format!(
        "FROM BRGR\n{}",
        json!({
            "type": if target.kind=="question" {"brgr_question"} else {"brgr_message"},
            "message_id": message,
            "task_id": task,
            "body": target.body,
            "instruction": format!(
                "Read this worker message or `brgr message list {task} --for owner`. For a task question reply with `brgr message send {task} --to worker --kind reply --reply-to {message} --body <answer>`. For a native input notice use `brgr input {task} --key <key>` or `--text <text>`. Acknowledge the read message with `brgr message ack {task} {message} --for owner`. Repeated message_id identifies the same message."
            )
        })
    );
    prompt_owner(
        paths,
        &OwnerPane {
            herdr_bin: &target.herdr_bin,
            herdr_session: target.herdr_session.as_deref(),
            pane_id: &target.pane_id,
            session_id: &target.session_id,
            owner_kind: owner_agent(&target.owner_id).unwrap_or("codex"),
        },
        &body,
    )
    .await
}

async fn prompt_owner(paths: &Paths, pane: &OwnerPane<'_>, body: &str) -> Result<()> {
    if let Some(id) = pane.session_id.strip_prefix("worker:") {
        let attempt = id.parse::<brgr_protocol::AttemptId>()?;
        let parent = Store::open(&paths.store)?
            .unfinished_attempts()?
            .into_iter()
            .find(|item| item.attempt_id == attempt)
            .context("parent worker session ended")?;
        return crate::pane_adapter::deliver_owner_notice(
            paths,
            parent.task.task_id,
            parent.task.revision,
            pane.pane_id,
            body,
        );
    }
    let binary = Path::new(pane.herdr_bin);
    if !binary.is_absolute() || !binary.is_file() {
        bail!("recorded Herdr executable is unavailable");
    }
    let mut get = herdr_command(pane);
    get.args(["agent", "get", pane.pane_id]);
    let output = timeout(HERDR_TIMEOUT, get.kill_on_drop(true).output())
        .await
        .context("Herdr agent identity lookup timed out")??;
    if !output.status.success() || output.stdout.len() > 65_536 {
        bail!("recorded parent pane is unavailable");
    }
    let state: Value = serde_json::from_slice(&output.stdout)?;
    let agent = state
        .pointer("/result/agent")
        .context("Herdr did not return an agent")?;
    if agent.get("agent").and_then(Value::as_str) != Some(pane.owner_kind)
        || agent.get("pane_id").and_then(Value::as_str) != Some(pane.pane_id)
        || (pane.owner_kind == "codex"
            && agent
                .pointer("/agent_session/value")
                .and_then(Value::as_str)
                != Some(pane.session_id))
    {
        bail!("recorded parent agent identity changed");
    }
    if pane.owner_kind == "claude" {
        claude_owner_present(paths, pane.session_id, pane.pane_id)?;
    }
    if !matches!(
        agent.get("agent_status").and_then(Value::as_str),
        Some("idle" | "done")
    ) {
        bail!("parent agent is not idle");
    }
    let mut prompt = herdr_command(pane);
    prompt.args(["agent", "prompt", pane.pane_id, body]);
    let output = timeout(HERDR_TIMEOUT, prompt.kill_on_drop(true).output())
        .await
        .context("Herdr parent prompt timed out")??;
    if !output.status.success() {
        bail!("Herdr did not accept the parent prompt");
    }
    Ok(())
}

fn herdr_command(pane: &OwnerPane<'_>) -> tokio::process::Command {
    let mut command = tokio::process::Command::new(pane.herdr_bin);
    if let Some(session) = pane.herdr_session {
        command.arg("--session").arg(session);
    }
    command
}

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

    #[test]
    fn a_claude_owner_is_present_only_while_its_process_runs_in_its_pane() {
        let temp = tempfile::tempdir().unwrap();
        let paths = Paths::new(Some(temp.path().join("brgr"))).unwrap();
        fs::create_dir_all(&paths.runs).unwrap();
        let session = "6b0e2a7c-1f7e-4c55-9d8f-0a1b2c3d4e5f";
        // Nothing recorded: the pane-and-kind check alone applies.
        claude_owner_present(&paths, session, "w1:p1").unwrap();
        let me = std::process::id();
        let birth = crate::supervision::ps_field(&me.to_string(), "lstart").unwrap();
        let owner = ClaudeOwnerProcess {
            pane: "w1:p1".into(),
            pid: me,
            birth,
        };
        record_claude_owner(&paths, session, &owner).unwrap();
        claude_owner_present(&paths, session, "w1:p1").unwrap();
        assert!(claude_owner_present(&paths, session, "w1:p2").is_err());
        record_claude_owner(
            &paths,
            session,
            &ClaudeOwnerProcess {
                birth: "Thu Jan  1 00:00:00 1970".into(),
                ..owner
            },
        )
        .unwrap();
        assert!(claude_owner_present(&paths, session, "w1:p1").is_err());
        assert!(claude_owner_path(&paths, "../escape").is_none());
    }

    #[test]
    fn owner_agent_kind_matches_the_owner_prefix() {
        assert_eq!(owner_agent("claude:abc"), Some("claude"));
        assert_eq!(owner_agent("cursor:abc"), Some("cursor"));
        assert_eq!(owner_agent("codex:abc"), Some("codex"));
        assert_eq!(owner_agent("worker:1"), None);
    }
}