brgr-cli 2.15.14

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
use super::*;
use brgr_protocol::AttemptState;
use std::os::unix::fs::PermissionsExt as _;

struct Fixture {
    temp: tempfile::TempDir,
    paths: Paths,
    task: TaskId,
    attempt: AttemptId,
    receipt: PathBuf,
    report: PathBuf,
    binary: PathBuf,
}

impl Fixture {
    fn new() -> Self {
        Self::build(|temp, _, _| {
            let workspace = temp.join("work");
            fs::create_dir_all(&workspace).unwrap();
            workspace
        })
    }

    /// The task runs in a real brgr task worktree of a fresh repository, as a
    /// Git-backed task does.
    fn in_worktree() -> Self {
        Self::build(|temp, paths, task| {
            let repository = temp.join("repo");
            fs::create_dir_all(&repository).unwrap();
            let git = |directory: &Path, args: &[&str]| {
                let status = std::process::Command::new("git")
                    .current_dir(directory)
                    .args(args)
                    .status()
                    .unwrap();
                assert!(status.success(), "git {args:?}");
            };
            git(&repository, &["init", "-q", "-b", "main"]);
            fs::write(repository.join("README"), "seed\n").unwrap();
            git(&repository, &["add", "README"]);
            git(
                &repository,
                &[
                    "-c",
                    "user.name=t",
                    "-c",
                    "user.email=t@t",
                    "commit",
                    "-qm",
                    "seed",
                ],
            );
            let slug = &task.to_string()[..8];
            let workspace = paths.worktrees.join("repo").join(slug);
            git(
                &repository,
                &[
                    "worktree",
                    "add",
                    "-q",
                    "-b",
                    &format!("brgr/task-{slug}"),
                    workspace.to_str().unwrap(),
                ],
            );
            workspace.canonicalize().unwrap()
        })
    }

    fn build(workspace: impl FnOnce(&Path, &Paths, TaskId) -> PathBuf) -> Self {
        let temp = tempfile::tempdir().unwrap();
        let paths = Paths::new(Some(temp.path().join("home"))).unwrap();
        let task = TaskId::new();
        let workspace = workspace(temp.path(), &paths, task);
        let spec: TaskSpec = serde_json::from_value(serde_json::json!({
            "schema":"brgr/v1","task_id":task,"revision":1,"create_request_id":format!("recover-{task}"),
            "owner_id":"codex:recovery","objective":"Return COMPLETE","workspace":workspace,
            "route":{"harness_id":"local.fixture"},"required_capabilities":[],
            "artifact_contract":{"media_type":"text/plain","max_bytes":4096},
            "acceptance_criteria":["COMPLETE"],"budget":{"deadline_seconds":60,"max_attempts":1}
        })).unwrap();
        let mut store = Store::open(&paths.store).unwrap();
        store.record_task(&spec, "fixture").unwrap();
        if let Some(primary) = crate::workspace::primary_checkout(&workspace) {
            store
                .record_task_checkout(task, 1, &primary.to_string_lossy())
                .unwrap();
        }
        store.bind_owner(&spec.owner_id, "recovery", 1).unwrap();
        let attempt = AttemptId::new();
        store.claim_attempt(task, 1, attempt).unwrap();
        store
            .compare_and_set_attempt_state(attempt, AttemptState::Queued, AttemptState::Starting)
            .unwrap();
        store
            .compare_and_set_attempt_state(attempt, AttemptState::Starting, AttemptState::Running)
            .unwrap();
        let launch: LaunchEnvelope = serde_json::from_value(serde_json::json!({
            "spec":spec,"harness_id":"local.fixture","protocol_generation":"brgr-v1",
            "keep_pane":false,"pane_mode":true
        }))
        .unwrap();
        write_json_atomic(&paths.launch(task, 1), &launch).unwrap();
        let binary = temp.path().join("herdr");
        fs::write(&binary, r#"#!/bin/sh
d=$(/usr/bin/dirname "$0")
case "$1 $2" in
 'pane get')
  test ! -e "$d/pane-gone" || { printf '{"error":{"code":"pane_not_found","message":"pane is absent"}}\n' >&2; exit 1; }
  test ! -e "$d/pane-unavailable" || exit 7
  /bin/cat "$d/pane.json";;
 'agent get') printf '{"result":{"agent":{"pane_id":"w1:p2","terminal_id":"owned-terminal","agent_status":"%s"}}}\n' "$(/bin/cat "$d/status")";;
 'pane close') test ! -e "$d/fail-close" || exit 7; /usr/bin/touch "$d/closed";;
 *) exit 8;;
esac
"#).unwrap();
        fs::set_permissions(&binary, fs::Permissions::from_mode(0o700)).unwrap();
        fs::write(
            temp.path().join("pane.json"),
            r#"{"result":{"pane":{"pane_id":"w1:p2","terminal_id":"owned-terminal"}}}"#,
        )
        .unwrap();
        fs::write(temp.path().join("status"), "working").unwrap();
        let receipt = paths.pane_receipt(task, 1);
        let report = workspace.join("report.md");
        write_json_atomic(
            &receipt,
            &PaneReceipt {
                pane: "w1:p2".into(),
                binary: binary.clone(),
                task: Some(task),
                revision: 1,
                attempt: Some(attempt),
                name: Some("w1:p2".into()),
                terminal: Some("owned-terminal".into()),
                report: Some(report.clone()),
                ..PaneReceipt::default()
            },
        )
        .unwrap();
        Self {
            temp,
            paths,
            task,
            attempt,
            receipt,
            report,
            binary,
        }
    }

    fn unfinished(&self) -> brgr_store::UnfinishedAttempt {
        Store::open(&self.paths.store)
            .unwrap()
            .unfinished_attempts()
            .unwrap()
            .pop()
            .unwrap()
    }
}

#[test]
fn unfinished_report_waits_then_completed_digest_recovers_without_a_live_pane() {
    let fixture = Fixture::new();
    fs::write(&fixture.report, "PARTIAL").unwrap();
    let attempt = fixture.unfinished();
    let mut supervisor = brgr_core::Supervisor::open(&fixture.paths.store).unwrap();
    assert!(!collect_recovered(&fixture.paths, &attempt, &mut supervisor).unwrap());
    fs::write(&fixture.report, "COMPLETE").unwrap();
    update_receipt(&fixture.receipt, |receipt| {
        receipt.report_digest = Some(report_digest(b"COMPLETE"));
    })
    .unwrap();
    fs::remove_file(&fixture.binary).unwrap();
    assert!(collect_recovered(&fixture.paths, &attempt, &mut supervisor).unwrap());
    let result = supervisor.store().latest_result(fixture.task).unwrap();
    assert_eq!(result.attempt_id, fixture.attempt);
    assert_eq!(result.outcome, brgr_protocol::TerminalOutcome::Candidate);
    let replay = supervisor
        .recover_external_report(fixture.task, fixture.attempt, b"COMPLETE")
        .unwrap();
    assert_eq!(replay.result_id, result.result_id);
    assert_eq!(
        supervisor
            .store()
            .pending_for_session("recovery")
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn close_checks_terminal_identity_and_retries_without_discarding_the_report() {
    let fixture = Fixture::new();
    fs::write(&fixture.report, "COMPLETE").unwrap();
    fs::write(
        fixture.temp.path().join("pane.json"),
        r#"{"result":{"pane":{"pane_id":"w1:p2","terminal_id":"replacement"}}}"#,
    )
    .unwrap();
    close_leftover_pane(&fixture.paths, fixture.task, 1, false);
    assert!(!fixture.temp.path().join("closed").exists());
    fs::write(
        fixture.temp.path().join("pane.json"),
        r#"{"result":{"pane":{"pane_id":"w1:p2","terminal_id":"owned-terminal"}}}"#,
    )
    .unwrap();
    let failure = fixture.temp.path().join("fail-close");
    fs::write(&failure, "").unwrap();
    close_leftover_pane(&fixture.paths, fixture.task, 1, false);
    let pending: PaneReceipt =
        serde_json::from_slice(&fs::read(&fixture.receipt).unwrap()).unwrap();
    assert_eq!(pending.cleanup, "pending");
    fs::remove_file(failure).unwrap();
    close_leftover_pane(&fixture.paths, fixture.task, 1, false);
    let closed: PaneReceipt = serde_json::from_slice(&fs::read(&fixture.receipt).unwrap()).unwrap();
    assert_eq!(closed.cleanup, "closed");
    assert_eq!(fs::read_to_string(&fixture.report).unwrap(), "COMPLETE");
}

#[test]
fn confirmed_absent_pane_settles_cleanup_and_archives_the_handled_report() {
    let mut fixture = Fixture::new();
    fixture.report = fixture
        .temp
        .path()
        .join(format!("work/.brgr/tasks/{}-r1/report.md", fixture.task));
    fs::create_dir_all(fixture.report.parent().unwrap()).unwrap();
    fs::write(&fixture.report, "COMPLETE").unwrap();
    update_receipt(&fixture.receipt, |receipt| {
        receipt.report = Some(fixture.report.clone());
        receipt.report_digest = Some(report_digest(b"COMPLETE"));
    })
    .unwrap();
    let mut supervisor = brgr_core::Supervisor::open(&fixture.paths.store).unwrap();
    assert!(collect_recovered(&fixture.paths, &fixture.unfinished(), &mut supervisor).unwrap());
    let result = supervisor.store().latest_result(fixture.task).unwrap();
    let owner = supervisor.store().task(fixture.task).unwrap().owner_id;
    let decision: brgr_protocol::Decision = serde_json::from_value(serde_json::json!({
        "schema":"brgr/v1", "decision_id":brgr_protocol::DecisionId::new(),
        "owner_id":owner, "task_id":fixture.task, "revision":1,
        "result_id":result.result_id, "result_digest":Store::result_digest(&result).unwrap(),
        "session_id":"recovery", "binding_epoch":1, "verdict":"accepted", "reason":"COMPLETE verified"
    }))
    .unwrap();
    supervisor
        .store()
        .record_decision_and_ack(&decision)
        .unwrap();

    let unavailable = fixture.temp.path().join("pane-unavailable");
    fs::write(&unavailable, "").unwrap();
    close_leftover_pane(&fixture.paths, fixture.task, 1, false);
    cleanup_settled(&fixture.paths, fixture.task, 1).unwrap();
    let pending: PaneReceipt =
        serde_json::from_slice(&fs::read(&fixture.receipt).unwrap()).unwrap();
    assert_eq!(pending.cleanup, "pending");
    assert!(fixture.report.exists());
    fs::remove_file(unavailable).unwrap();

    fs::write(fixture.temp.path().join("pane-gone"), "").unwrap();
    cleanup_settled(&fixture.paths, fixture.task, 1).unwrap();
    let closed: PaneReceipt = serde_json::from_slice(&fs::read(&fixture.receipt).unwrap()).unwrap();
    assert_eq!(closed.cleanup, "closed");
    assert!(closed.cleanup_error.is_none());
    assert!(!fixture.temp.path().join("closed").exists());
    assert!(!fixture.report.exists());
    assert_eq!(
        fs::read_to_string(closed.archived_report.unwrap()).unwrap(),
        "COMPLETE"
    );
    cleanup_settled(&fixture.paths, fixture.task, 1).unwrap();
}

#[test]
fn a_changed_handled_report_is_refused_once_and_kept_in_place() {
    let mut fixture = Fixture::new();
    fixture.report = fixture
        .temp
        .path()
        .join(format!("work/.brgr/tasks/{}-r1/report.md", fixture.task));
    fs::create_dir_all(fixture.report.parent().unwrap()).unwrap();
    fs::write(&fixture.report, "COMPLETE").unwrap();
    update_receipt(&fixture.receipt, |receipt| {
        receipt.report = Some(fixture.report.clone());
        receipt.report_digest = Some(report_digest(b"COMPLETE"));
    })
    .unwrap();
    let mut supervisor = brgr_core::Supervisor::open(&fixture.paths.store).unwrap();
    assert!(collect_recovered(&fixture.paths, &fixture.unfinished(), &mut supervisor).unwrap());
    let result = supervisor.store().latest_result(fixture.task).unwrap();
    let owner = supervisor.store().task(fixture.task).unwrap().owner_id;
    let decision: brgr_protocol::Decision = serde_json::from_value(serde_json::json!({
        "schema":"brgr/v1", "decision_id":brgr_protocol::DecisionId::new(),
        "owner_id":owner, "task_id":fixture.task, "revision":1,
        "result_id":result.result_id, "result_digest":Store::result_digest(&result).unwrap(),
        "session_id":"recovery", "binding_epoch":1, "verdict":"accepted", "reason":"COMPLETE verified"
    }))
    .unwrap();
    supervisor
        .store()
        .record_decision_and_ack(&decision)
        .unwrap();
    fs::write(&fixture.report, "CHANGED AFTER THE DECISION").unwrap();

    fs::write(fixture.temp.path().join("pane-gone"), "").unwrap();
    cleanup_settled(&fixture.paths, fixture.task, 1).unwrap();
    let refused: PaneReceipt =
        serde_json::from_slice(&fs::read(&fixture.receipt).unwrap()).unwrap();
    assert_eq!(
        refused.archive_refused.as_deref(),
        Some("handled report changed before archival")
    );
    assert!(refused.archived_report.is_none());
    assert_eq!(
        fs::read_to_string(&fixture.report).unwrap(),
        "CHANGED AFTER THE DECISION"
    );
    cleanup_settled(&fixture.paths, fixture.task, 1).unwrap();
}

/// A decided task whose pane disappeared before brgr closed it takes the
/// pane-already-gone path, which must reclaim the worktree like the others.
#[test]
fn a_pane_that_vanished_after_the_decision_still_reclaims_the_worktree() {
    let mut fixture = Fixture::in_worktree();
    let workspace = Store::open(&fixture.paths.store)
        .unwrap()
        .task(fixture.task)
        .unwrap()
        .workspace;
    fixture.report =
        PathBuf::from(&workspace).join(format!(".brgr/tasks/{}-r1/report.md", fixture.task));
    fs::create_dir_all(fixture.report.parent().unwrap()).unwrap();
    fs::write(&fixture.report, "COMPLETE").unwrap();
    update_receipt(&fixture.receipt, |receipt| {
        receipt.report = Some(fixture.report.clone());
        receipt.report_digest = Some(report_digest(b"COMPLETE"));
    })
    .unwrap();
    let mut supervisor = brgr_core::Supervisor::open(&fixture.paths.store).unwrap();
    assert!(collect_recovered(&fixture.paths, &fixture.unfinished(), &mut supervisor).unwrap());
    let result = supervisor.store().latest_result(fixture.task).unwrap();
    let owner = supervisor.store().task(fixture.task).unwrap().owner_id;
    let decision: brgr_protocol::Decision = serde_json::from_value(serde_json::json!({
        "schema":"brgr/v1", "decision_id":brgr_protocol::DecisionId::new(),
        "owner_id":owner, "task_id":fixture.task, "revision":1,
        "result_id":result.result_id, "result_digest":Store::result_digest(&result).unwrap(),
        "session_id":"recovery", "binding_epoch":1, "verdict":"accepted", "reason":"COMPLETE verified"
    }))
    .unwrap();
    supervisor
        .store()
        .record_decision_and_ack(&decision)
        .unwrap();
    fs::write(fixture.temp.path().join("pane-gone"), "").unwrap();
    cleanup_settled(&fixture.paths, fixture.task, 1).unwrap();
    assert!(
        !Path::new(&workspace).exists(),
        "the worktree survived the pane-already-gone path"
    );
}

/// A worktree kept for its contents is assessed once. Every hook runs the
/// pending-work pass, which calls cleanup again for each closed pane; it must
/// not reassess, so removing the blocking file afterwards changes nothing.
#[test]
fn a_kept_worktree_is_not_reassessed_by_later_cleanups() {
    let mut fixture = Fixture::in_worktree();
    let workspace = PathBuf::from(
        Store::open(&fixture.paths.store)
            .unwrap()
            .task(fixture.task)
            .unwrap()
            .workspace,
    );
    fixture.report = workspace.join(format!(".brgr/tasks/{}-r1/report.md", fixture.task));
    fs::create_dir_all(fixture.report.parent().unwrap()).unwrap();
    fs::write(&fixture.report, "COMPLETE").unwrap();
    update_receipt(&fixture.receipt, |receipt| {
        receipt.report = Some(fixture.report.clone());
        receipt.report_digest = Some(report_digest(b"COMPLETE"));
    })
    .unwrap();
    let mut supervisor = brgr_core::Supervisor::open(&fixture.paths.store).unwrap();
    assert!(collect_recovered(&fixture.paths, &fixture.unfinished(), &mut supervisor).unwrap());
    let result = supervisor.store().latest_result(fixture.task).unwrap();
    let owner = supervisor.store().task(fixture.task).unwrap().owner_id;
    let decision: brgr_protocol::Decision = serde_json::from_value(serde_json::json!({
        "schema":"brgr/v1", "decision_id":brgr_protocol::DecisionId::new(),
        "owner_id":owner, "task_id":fixture.task, "revision":1,
        "result_id":result.result_id, "result_digest":Store::result_digest(&result).unwrap(),
        "session_id":"recovery", "binding_epoch":1, "verdict":"accepted", "reason":"COMPLETE verified"
    }))
    .unwrap();
    supervisor
        .store()
        .record_decision_and_ack(&decision)
        .unwrap();
    let output = workspace.join("NOTES.md");
    fs::write(&output, "written by the worker\n").unwrap();
    fs::write(fixture.temp.path().join("pane-gone"), "").unwrap();
    cleanup_settled(&fixture.paths, fixture.task, 1).unwrap();
    assert!(
        workspace.is_dir(),
        "a worktree with the worker's file was removed"
    );
    fs::remove_file(&output).unwrap();
    cleanup_settled(&fixture.paths, fixture.task, 1).unwrap();
    assert!(
        workspace.is_dir(),
        "a later cleanup reassessed a worktree already kept"
    );
}

#[test]
fn recovered_session_keeps_its_original_deadline() {
    let fixture = Fixture::new();
    rusqlite::Connection::open(fixture.paths.store.join("brgr.sqlite3"))
        .unwrap()
        .execute("UPDATE attempt_clocks SET started_at=0", [])
        .unwrap();
    assert!(stop_external(&fixture.paths, &fixture.unfinished()).unwrap());
    let result = Store::open(&fixture.paths.store)
        .unwrap()
        .latest_result(fixture.task)
        .unwrap();
    assert_eq!(result.outcome, brgr_protocol::TerminalOutcome::Failed);
    assert!(result.error.unwrap().contains("original deadline"));
    assert!(fixture.temp.path().join("closed").is_file());
}

#[test]
fn non_regular_report_does_not_block_a_recovery_probe() {
    let fixture = Fixture::new();
    assert!(
        Command::new("/usr/bin/mkfifo")
            .arg(&fixture.report)
            .status()
            .unwrap()
            .success()
    );
    let started = Instant::now();
    assert!(read_report(&fixture.report, 4096).is_err());
    assert!(started.elapsed() < Duration::from_secs(1));
}