magi-cli 0.219.1

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
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
//! End-to-end: `graph::Runner::fix_selected` — an operator routing specific,
//! already-recorded review findings to a fixer on the same branch, outside
//! the normal review round sequence.
mod common;

use common::fixture_with_split_review_vote;
use magi::graph::Runner;
use magi::queue::{Queue, Source, Task, TaskStatus};
use magi::run::{OperatorFixOutcome, RunState, RunStatus};

/// Both reviewer seats agree `approve_with_findings` with one non-blocking
/// finding each — a clean round (nothing blocked merge) that still leaves
/// two minor findings nobody acted on, exactly the "8b21" scenario this
/// feature exists for.
///
/// Returns the fixture alongside the runner: the fixture's `TempDir` deletes
/// the repository on drop, so a caller that let it go out of scope here
/// would have `fix_selected` running `git` against a directory that no
/// longer exists.
async fn ready_run_with_two_minor_findings(home: common::HomeGuard) -> (common::Fixture, Runner) {
    let fx = fixture_with_split_review_vote(home, "review-1,review-2");
    let mut runner = Runner::start(
        &fx.repo,
        "add retries".to_owned(),
        fx.config.clone(),
        magi::run::Origin::operator(),
    )
    .await
    .expect("start");
    runner.execute().await.expect("execute");
    assert_eq!(runner.state.status, RunStatus::Ready, "{:?}", runner.state);
    assert_eq!(runner.state.reviews.len(), 1);
    assert!(runner.state.reviews[0].clean);
    assert_eq!(runner.state.last_round_findings().len(), 2);
    (fx, runner)
}

fn git(repo: &std::path::Path, args: &[&str]) {
    let out = std::process::Command::new("git")
        .args(args)
        .current_dir(repo)
        .output()
        .expect("spawn git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

common::e2e! {
async fn a_selected_minor_finding_is_fixed_and_reverified_leaving_the_other_untouched() {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let ids: Vec<String> = runner
        .state
        .last_round_findings()
        .iter()
        .map(|f| f.id.clone())
        .collect();
    let (picked, left) = (ids[0].clone(), ids[1].clone());

    runner
        .fix_selected(
            std::slice::from_ref(&picked),
            "operator: worth fixing before the next release",
            false,
        )
        .await
        .expect("fix_selected");

    // The original round is untouched — no fix folded into it, no rewritten
    // severity or vote.
    assert!(runner.state.reviews[0].fix.is_none());
    assert!(runner.state.reviews[0].clean);

    assert_eq!(runner.state.operator_fixes.len(), 1);
    let request = &runner.state.operator_fixes[0];
    assert_eq!(
        request.reason,
        "operator: worth fixing before the next release"
    );
    assert!(!request.stale);
    assert_eq!(
        request.findings.len(),
        1,
        "only the picked id, never the other"
    );
    assert_eq!(request.findings[0].id, picked);
    assert_eq!(request.findings[0].outcome, OperatorFixOutcome::Addressed);

    let fix = request.fix.as_ref().expect("fix record");
    assert!(fix.committed, "the fixer must have produced a real commit");
    assert_eq!(fix.addressed, vec![picked.clone()]);
    assert!(
        !fix.addressed.contains(&left),
        "the unselected finding must never be reported as addressed"
    );

    let follow_up_id = request
        .follow_up_review_run
        .clone()
        .expect("a real change opens a follow-up review");
    let follow_up = RunState::load(&follow_up_id).expect("load follow-up run");
    assert_eq!(follow_up.status, RunStatus::Ready, "{follow_up:?}");
    assert!(
        follow_up.gate.iter().all(|o| o.ok()),
        "the follow-up run must have actually gated: {:?}",
        follow_up.gate
    );
}
}

common::e2e! {
async fn an_unknown_finding_id_refuses_the_whole_request() {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let before = runner.state.operator_fixes.len();

    let err = runner
        .fix_selected(&["R99-9-9".to_owned()], "bogus id", false)
        .await
        .unwrap_err();
    assert!(err.to_string().contains("R99-9-9"), "{err}");
    assert_eq!(
        runner.state.operator_fixes.len(),
        before,
        "a refused request must not be recorded"
    );
}
}

common::e2e! {
async fn an_empty_reason_is_refused() {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let id = runner.state.last_round_findings()[0].id.clone();

    let err = runner.fix_selected(&[id], "   ", false).await.unwrap_err();
    assert!(err.to_string().contains("reason"), "{err}");
    assert!(runner.state.operator_fixes.is_empty());
}
}

common::e2e! {
async fn a_run_that_has_not_concluded_review_refuses_a_targeted_fix() {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let id = runner.state.last_round_findings()[0].id.clone();

    runner.state.status = RunStatus::Reviewing;
    let err = runner
        .fix_selected(std::slice::from_ref(&id), "too early", false)
        .await
        .unwrap_err();
    assert!(err.to_string().contains("reviewing"), "{err}");

    runner.state.status = RunStatus::Merged;
    let err = runner
        .fix_selected(&[id], "already landed", false)
        .await
        .unwrap_err();
    assert!(err.to_string().contains("merged"), "{err}");
    assert!(err.to_string().contains("magi review"), "{err}");
}
}

common::e2e! {
async fn a_run_already_being_worked_on_by_another_process_refuses_a_targeted_fix() {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let id = runner.state.last_round_findings()[0].id.clone();

    let mut beat = magi::daemon::Status::new();
    beat.current = vec![magi::daemon::Current {
        worker: None,
        task: "some-task".to_owned(),
        run: runner.state.id.clone(),
    }];
    magi::daemon::write_status_to(&magi::run::home().join("daemon.json"), &beat)
        .expect("publish a heartbeat");

    let err = runner
        .fix_selected(std::slice::from_ref(&id), "racing the daemon", false)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("currently being worked on"),
        "{err}"
    );
    assert!(runner.state.operator_fixes.is_empty());
}
}

common::e2e! {
/// A run whose own process crashed mid-fix leaves `fix.lock` behind with no
/// live process holding it. A later `magi fix` on the same run must recover
/// on its own — there is no `magi serve`/`magi web` sweep to rely on for a
/// one-shot CLI invocation — but only once the recorded pid is confirmed
/// dead, never on a guess.
async fn a_lock_left_by_a_confirmed_dead_process_is_reclaimed() {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let id = runner.state.last_round_findings()[0].id.clone();

    let mut child = if cfg!(windows) {
        std::process::Command::new("cmd")
            .args(["/C", "exit", "0"])
            .spawn()
            .expect("spawn a short-lived child")
    } else {
        std::process::Command::new("true")
            .spawn()
            .expect("spawn a short-lived child")
    };
    let dead_pid = child.id();
    child.wait().expect("wait for the child to exit");

    std::fs::write(runner.state.dir().join("fix.lock"), format!("{dead_pid}\n"))
        .expect("plant a stale lock naming the now-dead pid");

    runner
        .fix_selected(
            std::slice::from_ref(&id),
            "recovering after a crashed fix",
            false,
        )
        .await
        .expect("a lock naming a confirmed-dead pid must be reclaimed, not trusted");
    assert_eq!(runner.state.operator_fixes.len(), 1);
}
}

common::e2e! {
/// The mirror image of the reclaim test: a lock naming a pid that is still
/// alive (this test process itself) must never be reclaimed, whatever else
/// is going on — the conservative half of the policy.
async fn a_lock_naming_a_live_process_is_never_reclaimed() {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let id = runner.state.last_round_findings()[0].id.clone();

    std::fs::write(
        runner.state.dir().join("fix.lock"),
        format!("{}\n", std::process::id()),
    )
    .expect("plant a lock naming this live test process");

    let err = runner
        .fix_selected(std::slice::from_ref(&id), "should not get through", false)
        .await
        .unwrap_err();
    assert!(err.to_string().contains("already running"), "{err}");
    assert!(runner.state.operator_fixes.is_empty());
}
}

common::e2e! {
async fn a_stale_finding_is_refused_unless_the_operator_allows_it() {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let id = runner.state.last_round_findings()[0].id.clone();
    let winner = runner.state.winner().cloned().expect("winner");

    // Move the branch out from under the recorded finding, without going
    // through magi at all — exactly what a person pushing by hand would do.
    git(
        &winner.worktree,
        &["commit", "--allow-empty", "-m", "unrelated later work"],
    );

    let err = runner
        .fix_selected(std::slice::from_ref(&id), "stale attempt", false)
        .await
        .unwrap_err();
    assert!(err.to_string().contains("moved"), "{err}");
    assert!(runner.state.operator_fixes.is_empty());

    runner
        .fix_selected(std::slice::from_ref(&id), "stale attempt, allowed", true)
        .await
        .expect("allow_stale must let it through");
    let request = &runner.state.operator_fixes[0];
    assert!(request.stale);
    assert!(request.allow_stale);
    assert_eq!(request.findings[0].id, id);
}
}

common::e2e! {
async fn a_follow_up_review_claims_and_settles_the_task_that_owns_the_run() {
    let home = common::home_lock().await;
    let fx = fixture_with_split_review_vote(home, "review-1,review-2");
    let q = Queue::open();
    let mut task = Task::new(
        "add retries".to_owned(),
        "add retries".to_owned(),
        fx.repo.clone(),
        Source::Human,
    );
    q.put(&mut task).unwrap();
    let id = task.id.clone();

    let mut runner = Runner::start(
        &fx.repo,
        "add retries".to_owned(),
        fx.config.clone(),
        magi::run::Origin::operator().serving(Some(id.clone())),
    )
    .await
    .expect("start");
    runner.execute().await.expect("execute");
    let picked = runner.state.last_round_findings()[0].id.clone();
    runner
        .fix_selected(std::slice::from_ref(&picked), "operator: fix it", false)
        .await
        .expect("fix_selected");

    let follow_up = runner.state.operator_fixes[0]
        .follow_up_review_run
        .clone()
        .expect("a follow-up review ran");
    let after = q.get(&id).unwrap();
    assert_eq!(after.runs.last(), Some(&follow_up), "{after:?}");
    assert_ne!(after.status, TaskStatus::Running, "settled, not left running");
    assert_eq!(after.status, TaskStatus::Done, "{after:?}");
    assert_eq!(
        after.runs.iter().filter(|r| **r == follow_up).count(),
        1,
        "linked once"
    );
    assert!(q.claim(&id).is_ok(), "the claim was released");
}
}

async fn unavailable_operator_fix_can_be_retried(failure: &str) {
    let home = common::home_lock().await;
    let (_fx, mut runner) = ready_run_with_two_minor_findings(home).await;
    let picked = runner.state.last_round_findings()[0].id.clone();
    let seat = format!("impl-{}", runner.state.winner().unwrap().label);
    for agent in &mut runner.state.config.agents {
        if failure == "MOCK_CONTINUATION_AUTH" {
            agent
                .env
                .insert("MOCK_FIX_INCOMPLETE_SEAT".into(), seat.clone());
            agent.env.insert("MOCK_FIX_UNCOMMITTED".into(), "1".into());
            agent.env.insert(failure.into(), "1".into());
        } else {
            agent.env.insert(failure.into(), seat.clone());
        }
    }
    runner
        .fix_selected(std::slice::from_ref(&picked), "retryable outage", false)
        .await
        .expect("deferred fix");
    assert_eq!(runner.state.status, RunStatus::Blocked);
    assert!(runner.state.resource_block.is_some());
    assert!(!runner.state.worktree_root().join("operator-fix").exists());
    let disk = RunState::load(&runner.state.id).unwrap();
    let request = disk.operator_fixes.last().unwrap();
    assert!(request.fix.as_ref().unwrap().failed.is_some());
    assert_eq!(request.findings[0].outcome, OperatorFixOutcome::Unreported);
    if failure == "MOCK_CONTINUATION_AUTH" {
        assert!(request.fix.as_ref().unwrap().committed);
        assert!(
            request.result_head.is_some(),
            "work before report loss is retained"
        );
        let retained = magi::git::git(
            &disk.repo,
            &[
                "show",
                &format!("{}:retained-fix.txt", request.result_head.as_ref().unwrap()),
            ],
        )
        .await
        .unwrap();
        assert_eq!(retained.trim(), "work before report loss");
    }
    // An explicit retry reuses the branch after cleanup and clears the
    // previous resource block, without any manual worktree repair.
    for agent in &mut runner.state.config.agents {
        agent.env.remove(failure);
        agent.env.remove("MOCK_FIX_INCOMPLETE_SEAT");
        agent.env.remove("MOCK_FIX_UNCOMMITTED");
    }
    runner
        .fix_selected(std::slice::from_ref(&picked), "availability restored", true)
        .await
        .expect("retry after recovery");
    assert!(runner.state.resource_block.is_none());
    assert!(!runner.state.worktree_root().join("operator-fix").exists());
    let retried = runner.state.operator_fixes.last().unwrap();
    assert!(retried.fix.as_ref().unwrap().failed.is_none());
    assert!(retried.follow_up_review_run.is_some());
}

common::e2e! {
async fn quota_limited_operator_fix_cleans_up_and_can_be_retried() {
    unavailable_operator_fix_can_be_retried("MOCK_QUOTA_SEAT").await;
}
}

common::e2e! {
async fn unauthenticated_operator_fix_cleans_up_and_can_be_retried() {
    unavailable_operator_fix_can_be_retried("MOCK_AUTH_SEAT").await;
}
}

common::e2e! {
async fn operator_fix_report_outage_preserves_work_and_can_be_retried() {
    unavailable_operator_fix_can_be_retried("MOCK_CONTINUATION_AUTH").await;
}
}