magi-cli 0.278.0

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
415
//! `magi run` / `magi review` always file a task. With no loop alive the task
//! is claimed and executed in this process through the daemon's own attempt;
//! with a live loop it is filed urgent and left to that loop.

mod common;

use common::{Judges, fixture, home_lock};
use magi::config::{BuildCache, MergeMode};
use magi::daemon::{self, Opts, Status};
use magi::direct::{self, Filed, Filing};
use magi::queue::{Queue, RunOverrides, Source, Task, TaskStatus};
use magi::run::{RunState, RunStatus};

fn run_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:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

fn review_filing(fx: &common::Fixture, branch: &str, config: std::path::PathBuf) -> Filing {
    Filing {
        title: format!("review {branch}"),
        instruction: format!("Review the branch `{branch}`."),
        repo: fx.repo.clone(),
        source: Source::Human,
        issue: None,
        solo: false,
        overrides: RunOverrides {
            merge: Some("none".to_owned()),
            config: Some(config),
            ..RunOverrides::default()
        },
        sources: Default::default(),
        review_of: Some(branch.to_owned()),
    }
}

fn write_config(fx: &common::Fixture) -> std::path::PathBuf {
    let mut config = fx.config.clone();
    config.disk.min_free_bytes = 0;
    config.disk.auto_fold = false;
    config.disk.cache_limit_bytes = 0;
    config.merge.mode = MergeMode::Local;
    let path = fx.tmp.path().join("magi.toml");
    std::fs::write(&path, toml::to_string(&config).unwrap()).unwrap();
    path
}

common::e2e! {
async fn release_with_pruned_history_starts_a_fresh_attempt() {
    let home = home_lock().await;
    let fx = fixture(home, Judges::Unanimous, false);
    let mut config = fx.config.clone();
    config.disk.retained_attempt_limit = 2;
    let config_path = fx.tmp.path().join("magi.toml");
    std::fs::write(&config_path, toml::to_string(&config).unwrap()).unwrap();

    let mut task = Task::new(
        "Add note".into(),
        "Add note".into(),
        fx.repo.clone(),
        Source::Human,
    );
    task.solo = true;
    let mut finished = RunState::new(
        fx.repo.clone(),
        "main".into(),
        String::new(),
        task.instruction.clone(),
        config,
    );
    finished.status = RunStatus::Ready;
    finished.reserve().unwrap();
    let pruned = "20260101-000000-aaaa".to_owned();
    let history = vec![pruned.clone(), finished.id];
    task.runs.clone_from(&history);
    task.hold_machine(Some("Cannot verify existing public owner".into()));

    let queue = Queue::open();
    queue.put(&mut task).unwrap();
    let _claim = queue.claim(&task.id).unwrap();
    task.release_operator("test", None);
    queue.put(&mut task).unwrap();
    let opts = Opts {
        repo: fx.repo.clone(),
        config: Some(config_path),
        worktrees_root: Some(fx.tmp.path().join("wt")),
        ..Opts::default()
    };
    daemon::run_claimed(&opts, &queue, &mut task).await;

    let stored = queue.get(&task.id).unwrap();
    let hold = stored.hold_reason.as_deref().unwrap_or_default();
    assert!(
        !hold.contains("Cannot verify") && !hold.contains("recovery-backlog"),
        "{hold}"
    );
    assert_eq!(stored.attempts, 1, "{:?}", stored.hold_reason);
    assert_eq!(stored.runs.len(), history.len() + 1);
    assert_eq!(&stored.runs[..history.len()], history.as_slice());
    assert!(!magi::run::run_dir(&pruned).exists());
}
}

#[test]
fn standalone_attempt_future_leaves_room_on_the_default_thread_stack() {
    let opts = Opts::default();
    let queue = Queue::at(std::path::PathBuf::from("unused-queue"));
    let mut task = magi::queue::Task::new(
        "review".into(),
        "review".into(),
        std::path::PathBuf::from("unused-repo"),
        Source::Human,
    );
    // Construction does no I/O. Bound the frame rather than increasing the
    // Windows test thread's stack to accommodate duplicated attempt futures.
    let future = daemon::run_claimed(&opts, &queue, &mut task);
    let bytes = std::mem::size_of_val(&future);
    assert!(
        bytes < 64 * 1024,
        "standalone attempt future occupies {bytes} bytes"
    );
}

common::e2e! {
async fn a_review_with_no_loop_runs_against_its_own_claimed_task() {
    let home = home_lock().await;
    let fx = fixture(home, Judges::Unanimous, false);
    run_git(&fx.repo, &["checkout", "-q", "-b", "feat/by-hand"]);
    std::fs::write(fx.repo.join("note.txt"), "by hand\n").unwrap();
    run_git(&fx.repo, &["add", "-A"]);
    run_git(&fx.repo, &["commit", "-q", "-m", "add note"]);
    run_git(&fx.repo, &["checkout", "-q", "main"]);

    let config = write_config(&fx);
    let queue = Queue::open();
    let filed = direct::file(
        &queue,
        &magi::run::home(),
        jiff::Timestamp::now(),
        std::process::id(),
        review_filing(&fx, "feat/by-hand", config.clone()),
        false,
    )
    .expect("file");
    let Filed::Standalone { mut task, claim } = filed else {
        panic!("no loop is alive");
    };
    assert!(
        queue.claim(&task.id).is_err(),
        "a second process cannot claim a standalone run's task"
    );
    let opts = Opts {
        repo: fx.repo.clone(),
        config: Some(config),
        worktrees_root: Some(fx.tmp.path().join("wt")),
        ..Opts::default()
    };
    daemon::run_claimed(&opts, &queue, &mut task).await;
    drop(claim);

    let stored = queue.get(&task.id).unwrap();
    assert_eq!(stored.status, TaskStatus::Held, "{:?}", stored.last_error);
    assert!(
        stored.has_awaiting_landing_cause(),
        "unlanded Ready holds awaiting landing: {:?}",
        stored.hold_reason
    );
    assert_eq!(stored.attempts, 1, "counted as the daemon counts");
    assert_eq!(stored.runs.len(), 1, "the run is linked to its task");
    let state = magi::run::RunState::load(&stored.runs[0]).unwrap();
    assert_eq!(state.status, RunStatus::Ready);
    assert_eq!(
        state.config.merge.mode,
        MergeMode::None,
        "--merge none rode on the task and beat the config's mode"
    );
    assert!(state.judgements.is_empty(), "a review does not compete");
    assert_eq!(
        state.origin.as_ref().and_then(|o| o.task.clone()),
        Some(stored.id.clone())
    );
}
}

common::e2e! {
async fn a_review_of_a_missing_branch_fails_instead_of_competing() {
    let home = home_lock().await;
    let fx = fixture(home, Judges::Unanimous, false);
    let config = write_config(&fx);
    let queue = Queue::open();
    let filed = direct::file(
        &queue,
        &magi::run::home(),
        jiff::Timestamp::now(),
        std::process::id(),
        review_filing(&fx, "feat/nope", config.clone()),
        false,
    )
    .expect("file");
    let Filed::Standalone { mut task, claim } = filed else {
        panic!("no loop is alive");
    };
    let opts = Opts {
        repo: fx.repo.clone(),
        config: Some(config),
        worktrees_root: Some(fx.tmp.path().join("wt")),
        ..Opts::default()
    };
    daemon::run_claimed(&opts, &queue, &mut task).await;
    drop(claim);
    let stored = queue.get(&task.id).unwrap();
    assert!(stored.runs.is_empty(), "no competition was bought");
    assert_eq!(
        stored.status,
        TaskStatus::Held,
        "held, so a later loop does not retry it behind the operator's back"
    );
}
}

common::e2e! {
async fn a_live_loop_gets_an_urgent_task_and_nothing_runs_here() {
    let home = home_lock().await;
    let fx = fixture(home, Judges::Unanimous, false);
    let mut status = Status::new();
    status.pid = std::process::id().wrapping_add(1);
    daemon::write_status_to(&daemon::status_path(), &status).unwrap();

    let queue = Queue::open();
    let filed = direct::file(
        &queue,
        &magi::run::home(),
        jiff::Timestamp::now(),
        std::process::id(),
        review_filing(&fx, "feat/by-hand", fx.tmp.path().join("magi.toml")),
        false,
    )
    .expect("file");
    let Filed::Daemon { task, .. } = filed else {
        panic!("a loop is alive");
    };
    let stored = queue.get(&task.id).unwrap();
    assert!(stored.urgent);
    assert_eq!(stored.status, TaskStatus::Queued);
    assert!(stored.runs.is_empty());
    assert!(magi::run::list_ids().is_empty(), "no run was minted here");
    assert!(queue.claim(&task.id).is_ok(), "the loop's to claim");
}
}

common::e2e! {
async fn cli_persists_build_cache_choices_and_reports_the_effective_dry_run_mode() {
    let home = home_lock().await;
    let fx = fixture(home, Judges::Unanimous, false);
    run_git(&fx.repo, &["remote", "set-head", "origin", "main"]);
    let home = magi::run::home();
    let queue = Queue::open();
    let cli = || {
        let mut command = common::magi_cli(&home);
        command.current_dir(&fx.repo);
        command
    };

    let added = cli()
        .args([
            "task", "add", "--force", "--json", "--build-cache", "isolated",
            "Create the example",
        ])
        .output()
        .unwrap();
    assert!(
        added.status.success(),
        "{}",
        String::from_utf8_lossy(&added.stderr)
    );
    let task: Task = serde_json::from_slice(&added.stdout).unwrap();
    let stored = queue.get(&task.id).unwrap();
    assert_eq!(
        stored.overrides.unwrap().build_cache,
        Some(BuildCache::Isolated)
    );

    let show = |json: bool| {
        let mut command = cli();
        command.args(["task", "show", &task.id]);
        if json { command.arg("--json"); }
        let out = command.output().unwrap();
        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
        out.stdout
    };
    let effective = || {
        let view: serde_json::Value = serde_json::from_slice(&show(true)).unwrap();
        view["effective_build_cache"].clone()
    };
    assert_eq!(effective(), serde_json::json!({"mode": "isolated", "source": "task-override"}));
    let change = |mode| cli().args(["task", "build-cache", &task.id, mode]).output().unwrap();
    let claim = queue.claim(&task.id).unwrap();
    let refused = change("shared");
    assert!(!refused.status.success());
    assert!(String::from_utf8_lossy(&refused.stderr).contains("claimed"));
    drop(claim);
    let changed = change("shared");
    assert!(changed.status.success(), "{}", String::from_utf8_lossy(&changed.stderr));
    let mut stored = queue.get(&task.id).unwrap();
    assert_eq!(stored.overrides.as_ref().unwrap().build_cache, Some(BuildCache::Shared));
    stored.set_urgent(true).unwrap();
    stored.hold_manual(Some("waiting for operator".into()));
    queue.put(&mut stored).unwrap();
    assert_eq!(effective(), serde_json::json!({"mode": "shared", "source": "task-override"}));
    let cleared = change("default");
    assert!(cleared.status.success(), "{}", String::from_utf8_lossy(&cleared.stderr));
    let mut stored = queue.get(&task.id).unwrap();
    assert_eq!(stored.overrides.as_ref().and_then(|o| o.build_cache), None);
    assert_eq!(stored.status, TaskStatus::Held);
    // Still urgent, but this fixture configures no shared build cache, so
    // there is nothing to isolate from and the configured mode stands. The
    // urgent -> isolated path is covered by `isolated_build_cache` and by
    // `urgent_build_cache_precedes_config_but_not_an_explicit_choice`.
    assert_eq!(effective(), serde_json::json!({"mode": "shared", "source": "config"}));
    assert!(String::from_utf8_lossy(&show(false)).contains("shared (config)"));
    stored.set_urgent(false).unwrap();
    queue.put(&mut stored).unwrap();
    assert_eq!(effective(), serde_json::json!({"mode": "shared", "source": "config"}));
    stored.succeed(magi::queue::CompletionContext::new(
        magi::queue::CompletionActor::Cli,
        None,
        &home,
        &stored,
    ));
    queue.put(&mut stored).unwrap();
    let refused = change("isolated");
    assert!(!refused.status.success());
    assert!(String::from_utf8_lossy(&refused.stderr).contains("only queued or held tasks"));

    let mut cfg = fx.config.clone();
    cfg.verify.build_cache = BuildCache::Isolated;
    let config = fx.tmp.path().join("isolated.toml");
    std::fs::write(&config, toml::to_string(&cfg).unwrap()).unwrap();
    let planned = cli()
        .args(["run", "--force", "--dry-run", "--build-cache", "shared", "--config"])
        .arg(&config)
        .arg("Prepare the sample patch")
        .output()
        .unwrap();
    assert!(
        planned.status.success(),
        "{}",
        String::from_utf8_lossy(&planned.stderr)
    );
    assert!(String::from_utf8_lossy(&planned.stdout).contains("build cache: shared"));

    let planned_task = queue
        .list()
        .into_iter()
        .find(|task| task.instruction == "Prepare the sample patch")
        .unwrap();
    assert_eq!(
        planned_task.overrides.unwrap().build_cache,
        Some(BuildCache::Shared)
    );
    assert_eq!(planned_task.attempts, 0);
    let run = &planned_task.runs[0];
    let state = magi::run::RunState::load(run).unwrap();
    assert_eq!(state.config.verify.build_cache, BuildCache::Shared);

    let resumed = cli()
        .args(["run", "--resume", run, "--dry-run"])
        .output()
        .unwrap();
    assert!(
        resumed.status.success(),
        "{}",
        String::from_utf8_lossy(&resumed.stderr)
    );
    assert!(String::from_utf8_lossy(&resumed.stdout).contains("build cache: shared"));

    run_git(&fx.repo, &["checkout", "-q", "-b", "feat/build-cache"]);
    std::fs::write(fx.repo.join("note.txt"), "review this\n").unwrap();
    run_git(&fx.repo, &["add", "note.txt"]);
    run_git(&fx.repo, &["commit", "-q", "-m", "add note"]);
    run_git(&fx.repo, &["checkout", "-q", "main"]);
    let reviewed = cli()
        .args([
            "review", "feat/build-cache", "--force", "--build-cache", "shared", "--config",
        ])
        .arg(&config)
        .output()
        .unwrap();
    assert!(
        reviewed.status.success(),
        "{}\n{}",
        String::from_utf8_lossy(&reviewed.stdout),
        String::from_utf8_lossy(&reviewed.stderr)
    );
    let review = queue
        .list()
        .into_iter()
        .find(|task| task.review_of.as_deref() == Some("feat/build-cache"))
        .unwrap();
    assert_eq!(
        review.overrides.unwrap().build_cache,
        Some(BuildCache::Shared)
    );
    let state = magi::run::RunState::load(&review.runs[0]).unwrap();
    assert_eq!(state.config.verify.build_cache, BuildCache::Shared);
}
}