brgr-cli 2.15.2

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
//! `brgr head handoff`, `take` and the outgoing head's exit, against a fake Herdr.
use std::{fs, path::Path, process::Command};

use serde_json::Value;
use tempfile::TempDir;

fn brgr() -> &'static str {
    env!("CARGO_BIN_EXE_brgr")
}

const INHERITED_WORKER_ENV: &[&str] = &[
    "BRGR_HOME",
    "BRGR_BIN",
    "BRGR_OWNER_ID",
    "BRGR_SESSION_ID",
    "BRGR_PARENT_TASK_ID",
    "BRGR_PARENT_ATTEMPT_ID",
    "BRGR_WORKER_HERDR_CONTEXT",
    "CODEX_THREAD_ID",
    "CLAUDE_CODE_SESSION_ID",
    "CURSOR_CONVERSATION_ID",
];

fn brgr_command() -> Command {
    let mut command = Command::new(brgr());
    command.env("BRGR_TEST_TRUST_HERDR_PANE", "1");
    for name in INHERITED_WORKER_ENV {
        command.env_remove(name);
    }
    command
}

fn run(home: &Path, args: &[&str], envs: &[(&str, &str)]) -> std::process::Output {
    let mut command = brgr_command();
    command.arg("--home").arg(home).arg("--json").args(args);
    if matches!(args.first(), Some(&"run")) {
        command.arg("--headless");
    }
    command.env_remove("CODEX_THREAD_ID");
    command.env_remove("CLAUDE_CODE_SESSION_ID");
    command.env_remove("CURSOR_CONVERSATION_ID");
    for name in [
        "HERDR_ENV",
        "HERDR_PANE_ID",
        "HERDR_TAB_ID",
        "HERDR_WORKSPACE_ID",
        "HERDR_BIN_PATH",
        "HERDR_SOCKET_PATH",
        "HERDR_SESSION",
        "HERDR_PLUGIN_ID",
    ] {
        command.env_remove(name);
    }
    if !envs.iter().any(|(name, _)| {
        matches!(
            *name,
            "BRGR_SESSION_ID" | "CLAUDE_CODE_SESSION_ID" | "CURSOR_CONVERSATION_ID"
        )
    }) {
        command.env("BRGR_SESSION_ID", "fixture-session");
    }
    for (name, value) in envs {
        command.env(name, value);
    }
    command.output().unwrap()
}

fn json_output(output: &std::process::Output) -> Value {
    assert!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).unwrap()
}

fn gjc_fixture() -> std::path::PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../testdata/fixtures/gjc")
        .canonicalize()
        .unwrap()
}

fn gjc_home() -> (TempDir, std::path::PathBuf, std::path::PathBuf) {
    let temp = TempDir::new().unwrap();
    let home = temp.path().join("brgr");
    let workspace = temp.path().join("work");
    fs::create_dir_all(&workspace).unwrap();
    let scratch = temp.path().join("scratch");
    fs::create_dir_all(&scratch).unwrap();
    let receipt = json_output(&run(
        &home,
        &[
            "harness",
            "add",
            gjc_fixture().to_str().unwrap(),
            "--workspace",
            scratch.to_str().unwrap(),
            "--prompt",
            "BRGR_FIXTURE_OK",
        ],
        &[],
    ));
    assert!(receipt["scratch_result_digest"].as_str().is_some());
    (temp, home, workspace)
}

fn head_env() -> [(&'static str, &'static str); 2] {
    [
        ("BRGR_OWNER_ID", "codex:head-takeover"),
        ("BRGR_SESSION_ID", "session-head"),
    ]
}

fn start_task(home: &Path, workspace: &Path) -> String {
    let created = json_output(&run(
        home,
        &[
            "run",
            "BRGR_FIXTURE_OK",
            "--workspace",
            workspace.to_str().unwrap(),
            "--foreground",
        ],
        &head_env(),
    ));
    created["task_id"].as_str().unwrap().to_owned()
}

fn takeover_count(home: &Path) -> i64 {
    let database = home.join("store").join("brgr.sqlite3");
    let connection = rusqlite::Connection::open(database).unwrap();
    connection
        .query_row("SELECT COUNT(*) FROM head_takeovers", [], |row| row.get(0))
        .unwrap()
}

fn takeover_epoch(home: &Path, takeover_id: &str) -> u64 {
    let store = brgr_store::Store::open(home.join("store")).unwrap();
    store
        .takeover(takeover_id.parse().unwrap())
        .unwrap()
        .unwrap()
        .committed_epoch()
}

fn unrelated_env() -> [(&'static str, &'static str); 2] {
    [
        ("BRGR_OWNER_ID", "codex:head-takeover"),
        ("BRGR_SESSION_ID", "session-unrelated"),
    ]
}

/// A Herdr that records every call and answers the few the handoff makes.
/// `status-<pane>` files choose a pane's agent state (default `idle`).
fn fake_herdr(dir: &Path) -> std::path::PathBuf {
    let script = dir.join("herdr");
    fs::write(
        &script,
        r#"#!/bin/bash
echo "$@" >> "$FAKE_HERDR_DIR/calls.log"
if [ "$1" = "--session" ]; then shift 2; fi
case "$1 $2" in
  "pane split")
    echo '{"result":{"pane":{"pane_id":"p-new"}}}' ;;
  "pane get")
    echo "{\"result\":{\"pane\":{\"terminal_id\":\"term-$3\"}}}" ;;
  "agent get")
    s=idle
    [ -f "$FAKE_HERDR_DIR/status-$3" ] && s=$(cat "$FAKE_HERDR_DIR/status-$3")
    echo "{\"result\":{\"agent\":{\"agent\":\"claude\",\"agent_status\":\"$s\"}}}" ;;
  "pane layout") exit 1 ;;
  "pane read") ;;
  *) ;;
esac
exit 0
"#,
    )
    .unwrap();
    fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
    script
}

fn herdr_env<'a>(fake: &'a Path, dir: &'a Path, pane: &'a str) -> Vec<(&'static str, String)> {
    vec![
        ("HERDR_ENV", "1".to_owned()),
        ("HERDR_PANE_ID", pane.to_owned()),
        ("HERDR_BIN_PATH", fake.to_str().unwrap().to_owned()),
        ("FAKE_HERDR_DIR", dir.to_str().unwrap().to_owned()),
    ]
}

fn run_with(
    home: &Path,
    args: &[&str],
    base: &[(&str, &str)],
    extra: &[(&str, String)],
) -> std::process::Output {
    let mut envs: Vec<(&str, &str)> = base.to_vec();
    envs.extend(extra.iter().map(|(name, value)| (*name, value.as_str())));
    run(home, args, &envs)
}

fn calls(dir: &Path) -> String {
    fs::read_to_string(dir.join("calls.log")).unwrap_or_default()
}

fn closed_panes(dir: &Path) -> Vec<String> {
    calls(dir)
        .lines()
        .filter_map(|line| line.strip_prefix("pane close "))
        .map(str::to_owned)
        .collect()
}

fn offer_key(handoff: &Value) -> String {
    handoff["offer"].as_str().unwrap().to_owned()
}

fn head_pane_env() -> [(&'static str, &'static str); 2] {
    head_env()
}

fn incoming_session() -> [(&'static str, &'static str); 2] {
    [
        ("BRGR_OWNER_ID", "codex:head-takeover"),
        ("BRGR_SESSION_ID", "session-incoming"),
    ]
}

fn start_handoff(home: &Path, task_id: &str, fake: &Path, dir: &Path, exit_old: bool) -> Value {
    let mut args = vec![
        "head",
        "handoff",
        task_id,
        "--kind",
        "claude",
        "--goal",
        "Finish the migration",
    ];
    if exit_old {
        args.push("--exit-old");
    }
    json_output(&run_with(
        home,
        &args,
        &head_pane_env(),
        &herdr_env(fake, dir, "p-old"),
    ))
}

#[test]
fn handoff_opens_a_pane_prompts_it_and_leaves_the_binding_with_the_outgoing_head() {
    let (temp, home, workspace) = gjc_home();
    let task_id = start_task(&home, &workspace);
    let dir = temp.path().join("fake");
    fs::create_dir_all(&dir).unwrap();
    let fake = fake_herdr(&dir);
    let handoff = start_handoff(&home, &task_id, &fake, &dir, false);
    assert_eq!(handoff["incoming_pane"], "p-new");
    let log = calls(&dir);
    assert!(log.contains("pane split"), "{log}");
    assert!(log.contains("BRGR_SESSION_ID="), "{log}");
    assert!(log.contains("--env BRGR_HOME="), "{log}");
    assert!(log.contains("agent start head-"), "{log}");
    let key = offer_key(&handoff);
    assert!(
        log.contains(&format!("head take {task_id} --offer {key}")),
        "{log}"
    );
    // Opening a pane moves nothing: the outgoing head still holds command.
    assert_eq!(takeover_count(&home), 0);
    let still_head = run(&home, &["result", &task_id], &head_env());
    assert!(still_head.status.success());
}

#[test]
fn take_commits_for_the_incoming_session_and_tells_the_outgoing_pane() {
    let (temp, home, workspace) = gjc_home();
    let task_id = start_task(&home, &workspace);
    let dir = temp.path().join("fake");
    fs::create_dir_all(&dir).unwrap();
    let fake = fake_herdr(&dir);
    let key = offer_key(&start_handoff(&home, &task_id, &fake, &dir, false));
    let taken = json_output(&run_with(
        &home,
        &["head", "take", &task_id, "--offer", &key],
        &incoming_session(),
        &herdr_env(&fake, &dir, "p-new"),
    ));
    assert_eq!(taken["takeover"]["state"], "committed");
    assert_eq!(
        taken["binding_epoch"].as_u64().unwrap(),
        takeover_epoch(&home, taken["takeover"]["takeover_id"].as_str().unwrap())
    );
    assert!(
        calls(&dir).contains("agent prompt p-old"),
        "{}",
        calls(&dir)
    );
    // A repeat returns the same record and does not raise the epoch again.
    let again = json_output(&run_with(
        &home,
        &["head", "take", &task_id, "--offer", &key],
        &incoming_session(),
        &herdr_env(&fake, &dir, "p-new"),
    ));
    assert_eq!(
        again["takeover"]["takeover_id"],
        taken["takeover"]["takeover_id"]
    );
    assert_eq!(again["binding_epoch"], taken["binding_epoch"]);
    let stale = run(&home, &["result", &task_id, "--ack"], &head_env());
    assert!(!stale.status.success());
}

#[test]
fn take_refuses_the_outgoing_session_an_unknown_offer_and_a_moved_head() {
    let (temp, home, workspace) = gjc_home();
    let task_id = start_task(&home, &workspace);
    let dir = temp.path().join("fake");
    fs::create_dir_all(&dir).unwrap();
    let fake = fake_herdr(&dir);
    let key = offer_key(&start_handoff(&home, &task_id, &fake, &dir, false));
    let herdr = herdr_env(&fake, &dir, "p-new");
    let own = run_with(
        &home,
        &["head", "take", &task_id, "--offer", &key],
        &head_env(),
        &herdr,
    );
    assert!(!own.status.success());
    let unknown = run_with(
        &home,
        &["head", "take", &task_id, "--offer", "no-such-offer"],
        &incoming_session(),
        &herdr,
    );
    assert!(!unknown.status.success());
    let traversal = run_with(
        &home,
        &["head", "take", &task_id, "--offer", "../x"],
        &incoming_session(),
        &herdr,
    );
    assert!(!traversal.status.success());
    assert_eq!(takeover_count(&home), 0);
    // Another session claimed the head first; the old offer must not override it.
    json_output(&run(
        &home,
        &["head", "claim", &task_id, "--abandoned", "--goal", "g"],
        &unrelated_env(),
    ));
    let late = run_with(
        &home,
        &["head", "take", &task_id, "--offer", &key],
        &incoming_session(),
        &herdr,
    );
    assert!(!late.status.success());
    assert!(String::from_utf8_lossy(&late.stderr).contains("moved"));
}

#[test]
fn exit_old_closes_the_outgoing_pane_only_after_resume_and_a_clean_retire() {
    let (temp, home, workspace) = gjc_home();
    let task_id = start_task(&home, &workspace);
    let dir = temp.path().join("fake");
    fs::create_dir_all(&dir).unwrap();
    let fake = fake_herdr(&dir);
    let key = offer_key(&start_handoff(&home, &task_id, &fake, &dir, true));
    let herdr = herdr_env(&fake, &dir, "p-new");
    let taken = json_output(&run_with(
        &home,
        &["head", "take", &task_id, "--offer", &key],
        &incoming_session(),
        &herdr,
    ));
    let takeover_id = taken["takeover"]["takeover_id"]
        .as_str()
        .unwrap()
        .to_owned();
    // Committed is not resumed: retire is refused and the old pane stays open.
    let early = run_with(
        &home,
        &["head", "retire", &takeover_id],
        &incoming_session(),
        &herdr,
    );
    assert!(!early.status.success());
    assert!(closed_panes(&dir).is_empty(), "{}", calls(&dir));
    json_output(&run_with(
        &home,
        &["accept", &task_id, "--reason", "incoming head acted"],
        &incoming_session(),
        &herdr,
    ));
    let retired = json_output(&run_with(
        &home,
        &["head", "retire", &takeover_id],
        &incoming_session(),
        &herdr,
    ));
    assert_eq!(retired["state"], "retired");
    assert_eq!(retired["outgoing_head"]["closed"], true);
    assert_eq!(closed_panes(&dir), ["p-old"], "{}", calls(&dir));
}

#[test]
fn a_busy_outgoing_head_is_not_closed_and_the_failure_is_reported_apart_from_the_handoff() {
    let (temp, home, workspace) = gjc_home();
    let task_id = start_task(&home, &workspace);
    let dir = temp.path().join("fake");
    fs::create_dir_all(&dir).unwrap();
    let fake = fake_herdr(&dir);
    let key = offer_key(&start_handoff(&home, &task_id, &fake, &dir, true));
    fs::write(dir.join("status-p-old"), "working").unwrap();
    let herdr = herdr_env(&fake, &dir, "p-new");
    let taken = json_output(&run_with(
        &home,
        &["head", "take", &task_id, "--offer", &key],
        &incoming_session(),
        &herdr,
    ));
    let takeover_id = taken["takeover"]["takeover_id"]
        .as_str()
        .unwrap()
        .to_owned();
    json_output(&run_with(
        &home,
        &["accept", &task_id, "--reason", "incoming head acted"],
        &incoming_session(),
        &herdr,
    ));
    let retired = json_output(&run_with(
        &home,
        &["head", "retire", &takeover_id],
        &incoming_session(),
        &herdr,
    ));
    assert_eq!(retired["state"], "retired");
    assert_eq!(retired["outgoing_head"]["closed"], false);
    assert!(closed_panes(&dir).is_empty(), "{}", calls(&dir));
    // Once the old head is idle, the retry closes it.
    fs::write(dir.join("status-p-old"), "idle").unwrap();
    let exited = json_output(&run_with(
        &home,
        &["head", "exit", &takeover_id],
        &incoming_session(),
        &herdr,
    ));
    assert_eq!(exited["outgoing_head"]["closed"], true);
    assert_eq!(closed_panes(&dir), ["p-old"], "{}", calls(&dir));
}

#[test]
fn a_handoff_without_exit_old_never_closes_a_pane() {
    let (temp, home, workspace) = gjc_home();
    let task_id = start_task(&home, &workspace);
    let dir = temp.path().join("fake");
    fs::create_dir_all(&dir).unwrap();
    let fake = fake_herdr(&dir);
    let key = offer_key(&start_handoff(&home, &task_id, &fake, &dir, false));
    let herdr = herdr_env(&fake, &dir, "p-new");
    let taken = json_output(&run_with(
        &home,
        &["head", "take", &task_id, "--offer", &key],
        &incoming_session(),
        &herdr,
    ));
    let takeover_id = taken["takeover"]["takeover_id"]
        .as_str()
        .unwrap()
        .to_owned();
    json_output(&run_with(
        &home,
        &["accept", &task_id, "--reason", "incoming head acted"],
        &incoming_session(),
        &herdr,
    ));
    let retired = json_output(&run_with(
        &home,
        &["head", "retire", &takeover_id],
        &incoming_session(),
        &herdr,
    ));
    assert!(retired.get("outgoing_head").is_none());
    assert!(closed_panes(&dir).is_empty(), "{}", calls(&dir));
}