magi-cli 0.275.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
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
//! CLI surface for owner-selected immediate execution:
//! - `magi task add --immediate` (and coexistence with `--urgent`)
//! - `magi task immediate <id> [--clear]`
//! - `magi task list` / `magi task show [--json]` labels and admission status
//! - owner-only enforcement refusing agent seats and chats.

mod common;

use magi::daemon::{Status, write_status_to};
use magi::queue::{Queue, Source, Task};

#[test]
fn immediate_cli_add_toggle_show_list_and_owner_only_guards() {
    let home = tempfile::tempdir().unwrap();
    let repo = home.path().join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    let init = std::process::Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert!(
        init.status.success(),
        "git init failed: {}",
        String::from_utf8_lossy(&init.stderr)
    );
    let queue = Queue::at(home.path().join("queue"));

    let run = |args: &[&str], envs: &[(&str, &str)]| {
        let mut cmd = common::magi_cli(home.path());
        cmd.args(args)
            .env("NO_COLOR", "1")
            .env_remove("MAGI_RUN")
            .env_remove("MAGI_NODE")
            .env_remove("MAGI_CHAT_CONTROL_CHANNEL")
            .env_remove("MAGI_CHAT_CONTROL_SOCKET");
        for (k, v) in envs {
            cmd.env(k, v);
        }
        cmd.output().unwrap()
    };

    // Owner can file with both --immediate and --urgent.
    let added = run(
        &[
            "task",
            "add",
            "--repo",
            repo.to_str().unwrap(),
            "--immediate",
            "--urgent",
            "--json",
            "owner immediate task",
        ],
        &[],
    );
    assert!(
        added.status.success(),
        "{}",
        String::from_utf8_lossy(&added.stderr)
    );
    let filed: Task = serde_json::from_slice(&added.stdout).unwrap();
    assert!(filed.immediate);
    assert!(filed.urgent);

    // Without a live scheduler, show & list report waiting on scheduler, never "next poll".
    let show = run(&["task", "show", filed.short()], &[]);
    assert!(show.status.success());
    let show_text = String::from_utf8(show.stdout).unwrap();
    assert!(show_text.contains("immediate enabled"), "{show_text}");
    assert!(show_text.contains("urgent    enabled"), "{show_text}");
    assert!(
        show_text.contains("admission Immediate: waiting — scheduler not running"),
        "{show_text}"
    );

    let list = run(&["task", "list"], &[]);
    assert!(list.status.success());
    let list_text = String::from_utf8(list.stdout).unwrap();
    assert!(list_text.contains("[immediate]"), "{list_text}");
    assert!(
        list_text.contains("Immediate: waiting — scheduler not running"),
        "{list_text}"
    );

    // With a live scheduler heartbeat, show --json & show report "Immediate: next poll".
    let status = Status::new();
    write_status_to(&home.path().join("daemon.json"), &status).unwrap();
    let show_json = run(&["task", "show", filed.short(), "--json"], &[]);
    assert!(show_json.status.success());
    let parsed: serde_json::Value = serde_json::from_slice(&show_json.stdout).unwrap();
    assert_eq!(parsed["immediate"], true);
    assert_eq!(parsed["urgent"], true);
    assert_eq!(parsed["admission"]["mode"], "immediate");
    assert_eq!(parsed["admission"]["state"], "next_poll");
    assert_eq!(parsed["admission"]["label"], "Immediate: next poll");

    // Clearing immediate preserves urgent.
    let cleared = run(&["task", "immediate", filed.short(), "--clear"], &[]);
    assert!(
        cleared.status.success(),
        "{}",
        String::from_utf8_lossy(&cleared.stderr)
    );
    assert!(
        String::from_utf8(cleared.stdout)
            .unwrap()
            .contains("immediate now disabled")
    );
    let after_clear = queue.get(&filed.id).unwrap();
    assert!(!after_clear.immediate);
    assert!(after_clear.urgent);

    // Re-enabling immediate works on unclaimed queued task.
    let enabled = run(&["task", "immediate", filed.short()], &[]);
    assert!(enabled.status.success());
    assert!(queue.get(&filed.id).unwrap().immediate);

    // Claimed task refuses immediate change.
    let _claim = queue.claim(&filed.id).unwrap();
    let conflict = run(&["task", "immediate", filed.short(), "--clear"], &[]);
    assert!(!conflict.status.success());
    assert!(
        String::from_utf8_lossy(&conflict.stderr).contains("claimed"),
        "{}",
        String::from_utf8_lossy(&conflict.stderr)
    );
    drop(_claim);

    // Owner-only enforcement: agent seats, unbridged chats, spoofed bridge env
    // vars (including MAGI_ALLOW_WRITE=1), standing markers, and worker envs
    // cannot add --immediate or toggle immediate.
    let mut existing = Task::new(
        "plain task".into(),
        "plain body".into(),
        repo.clone(),
        Source::Human,
    );
    queue.put(&mut existing).unwrap();
    for env_set in [
        &[("MAGI_RUN", "run-1"), ("MAGI_NODE", "implement")][..],
        &[("MAGI_RUN", "chat-1"), ("MAGI_NODE", "chat")][..],
        &[("MAGI_NODE", "external-chat")][..],
        &[("MAGI_SEAT", "impl-A")][..],
        &[("MAGI_WORKER_ID", "worker-1")][..],
        &[("MAGI_CHAT_STANDING_TURN", "1")][..],
    ] {
        let refused_add = run(
            &[
                "task",
                "add",
                "--repo",
                repo.to_str().unwrap(),
                "--immediate",
                "agent immediate attempt",
            ],
            env_set,
        );
        assert!(
            !refused_add.status.success(),
            "agent/chat env {env_set:?} must not file --immediate"
        );
        let refused_toggle = run(&["task", "immediate", existing.short()], env_set);
        assert!(
            !refused_toggle.status.success(),
            "agent/chat env {env_set:?} must not enable immediate"
        );
        assert!(!queue.get(&existing.id).unwrap().immediate);
    }

    // Spoofing chat control env vars + MAGI_ALLOW_WRITE=1 with --request must
    // still fail closed (no local fallback for Operation::AddImmediate).
    let spoofed = run(
        &[
            "task",
            "add",
            "--repo",
            repo.to_str().unwrap(),
            "--immediate",
            "--request",
            "req-spoof",
            "spoofed bridge attempt",
        ],
        &[
            ("MAGI_RUN", "chat-spoof"),
            ("MAGI_NODE", "chat"),
            ("MAGI_ALLOW_WRITE", "1"),
            ("MAGI_CHAT_CONTROL_PIPE", r"\\.\pipe\magi-chat-nonexistent"),
            ("MAGI_CHAT_CONTROL_SOCKET", "/nonexistent/magi-socket"),
            ("MAGI_CHAT_CONTROL_CAP", &"0".repeat(64)),
        ],
    );
    assert!(
        !spoofed.status.success(),
        "spoofed control channel with MAGI_ALLOW_WRITE=1 must fail closed"
    );

    // Terminal owner passing --request is refused cleanly (chat-only flag).
    let terminal_with_req = run(
        &[
            "task",
            "add",
            "--repo",
            repo.to_str().unwrap(),
            "--immediate",
            "--request",
            "req-term",
            "terminal with request",
        ],
        &[],
    );
    assert!(
        !terminal_with_req.status.success(),
        "terminal --immediate must not silently ignore --request"
    );
    assert_eq!(queue.list().len(), 2);
}

#[test]
fn owner_chat_authenticated_immediate_admission_binding_replay_and_non_owner_denials() {
    common::isolated(
        "owner_chat_authenticated_immediate_admission_binding_replay_and_non_owner_denials",
        || async {
            use magi::config::{AgentKind, AgentSpec, Config};
            use magi::talk::{self, Talks};
            use std::collections::BTreeMap;

            let tmp = tempfile::tempdir().unwrap();
            let home = tmp.path();
            magi::run::set_home(home.to_owned());

            let repo_chat = home.join("magi-repo");
            let repo_target = home.join("shun-repo");
            // Keep `repo_chat` a plain directory (matching `tests/talk_external.rs`)
            // so `Config::discover` reads `repo_chat/magi.toml` directly in detached
            // `send` / `send-owner` workers without requiring a bare `origin` remote.
            std::fs::create_dir_all(&repo_chat).unwrap();
            std::fs::create_dir_all(&repo_target).unwrap();
            let init = std::process::Command::new("git")
                .args(["init", "-b", "main"])
                .current_dir(&repo_target)
                .output()
                .unwrap();
            assert!(init.status.success());

            let cli = common::magi_cli(home);
            let binary = cli.get_program().to_string_lossy().replace('\\', "/");
            let script = repo_chat.join("chat-backend.sh");
            // Deterministic chat backend driven by TEST_MODE.
            std::fs::write(
                &script,
                r#"set -eu
if [ "${MAGI_NODE:-}" = "talk-title" ]; then
  if "$TEST_MAGI" task add --immediate --request req-title --solo --repo "$TARGET_REPO" --json "Title seat immediate" > "$OUT_DIR/title-seat.out" 2>&1; then exit 31; fi
  printf 'Test title\n'
  exit 0
fi
case "${TEST_MODE:-}" in
  owner)
    # 1. Authorized cross-repo immediate filing succeeds.
    "$TEST_MAGI" task add --immediate --request req-shun --solo --repo "$TARGET_REPO" --json "Fix shun issue 339" > "$OUT_DIR/first.json" 2> "$OUT_DIR/first.err"
    # 2. Exact replay returns the exact same task ID.
    "$TEST_MAGI" task add --immediate --request req-shun --solo --repo "$TARGET_REPO" --json "Fix shun issue 339" > "$OUT_DIR/replay.json" 2> "$OUT_DIR/replay.err"
    # 3. Reusing the same request ID with a different repo fails closed.
    if "$TEST_MAGI" task add --immediate --request req-shun --solo --repo "$CHAT_REPO" --json "Fix shun issue 339" > "$OUT_DIR/bad-repo.out" 2>&1; then exit 11; fi
    # 4. Reusing the same request ID with different text fails closed.
    if "$TEST_MAGI" task add --immediate --request req-shun --solo --repo "$TARGET_REPO" --json "Different work" > "$OUT_DIR/bad-text.out" 2>&1; then exit 12; fi
    # 5. Missing --request in chat fails closed.
    if "$TEST_MAGI" task add --immediate --solo --repo "$TARGET_REPO" --json "Missing request" > "$OUT_DIR/no-req.out" 2>&1; then exit 13; fi
    # 6. Ordinary and urgent task filings stay intact.
    "$TEST_MAGI" task add --solo --repo "$TARGET_REPO" --json "Ordinary chat task" > "$OUT_DIR/ordinary.json"
    "$TEST_MAGI" task add --urgent --solo --repo "$TARGET_REPO" --json "Urgent chat task" > "$OUT_DIR/urgent.json"
    # 7. Toggling immediate on an existing task from chat stays refused.
    if "$TEST_MAGI" task immediate "$EXISTING_TASK" > "$OUT_DIR/toggle.out" 2>&1; then exit 14; fi
    printf 'owner turn done\n'
    ;;
  deny)
    if "$TEST_MAGI" task add --immediate --request "$REQ_ID" --solo --repo "$TARGET_REPO" --json "Unauthorized immediate" > "$OUT_DIR/denied.out" 2>&1; then exit 21; fi
    printf 'denied as expected\n'
    ;;
  cli-owner)
    "$TEST_MAGI" task add --immediate --request req-cli-owner --solo --repo "$TARGET_REPO" --json "CLI owner immediate" > "$OUT_DIR/cli-owner.json"
    printf 'cli owner ok\n'
    ;;
  *)
    printf 'unexpected TEST_MODE\n' >&2
    exit 99
    ;;
esac
"#,
            )
            .unwrap();

            let out_dir = home.join("out");
            std::fs::create_dir_all(&out_dir).unwrap();
            let queue = Queue::at(home.join("queue"));
            let mut existing = Task::new(
                "existing".into(),
                "existing work".into(),
                repo_target.clone(),
                Source::Human,
            );
            queue.put(&mut existing).unwrap();

            let make_cfg = |mode: &str, req_id: &str, standing_auth: bool| {
                let mut env = common::magi_cli_env(home, "TEST_MAGI");
                env.extend(BTreeMap::from([
                    ("TEST_MODE".into(), mode.into()),
                    ("REQ_ID".into(), req_id.into()),
                    ("TEST_MAGI".into(), binary.clone()),
                    (
                        "CHAT_REPO".into(),
                        repo_chat.to_string_lossy().replace('\\', "/"),
                    ),
                    (
                        "TARGET_REPO".into(),
                        repo_target.to_string_lossy().replace('\\', "/"),
                    ),
                    (
                        "OUT_DIR".into(),
                        out_dir.to_string_lossy().replace('\\', "/"),
                    ),
                    ("EXISTING_TASK".into(), existing.id.clone()),
                ]));
                Config {
                    agents: vec![AgentSpec {
                        id: "mock".into(),
                        kind: AgentKind::Command,
                        model: None,
                        command: vec!["sh".into(), script.to_string_lossy().replace('\\', "/")],
                        extra_args: vec![],
                        env,
                        prompt_delivery: None,
                        max_turn_secs: Some(30),
                    }],
                    talk: magi::config::Talk {
                        standing_authorization: standing_auth,
                        ..Default::default()
                    },
                    ..Config::default()
                }
            };

            let talks = Talks::at(home.join("talks"));
            let cfg_owner = make_cfg("owner", "req-shun", false);
            let mut talk =
                talk::begin(&talks, &cfg_owner, repo_chat.clone(), Some("mock")).unwrap();
            let lease = talks.claim_turn(&talk.id).unwrap().unwrap();

            // 1. Authenticated Web/Chat owner turn via real bridge.
            talk::say(
                &lease,
                &mut talk,
                &talks,
                &cfg_owner,
                "Please file shun issue #339 as immediate",
                vec![],
            )
            .await
            .unwrap();
            let last_reply = &talk.turns.last().unwrap().body;
            assert_eq!(last_reply, "owner turn done", "turns: {:#?}", talk.turns);

            let parse_task = |name: &str| -> Task {
                let raw = std::fs::read_to_string(out_dir.join(name)).unwrap_or_else(|e| {
                    panic!(
                        "read {name}: {e}; stderr={}",
                        std::fs::read_to_string(talks.artifacts_of(&talk.id).join("turn-1.err"))
                            .unwrap_or_default()
                    )
                });
                serde_json::from_str(&raw).unwrap_or_else(|e| {
                    panic!(
                        "parse {name}: {e}; raw={raw:?}; first.err={:?}; replay={:?}; ordinary={:?}; queue_len={}; stderr={:?}",
                        std::fs::read_to_string(out_dir.join("first.err")).ok(),
                        std::fs::read_to_string(out_dir.join("replay.json")).ok(),
                        std::fs::read_to_string(out_dir.join("ordinary.json")).ok(),
                        queue.list().len(),
                        std::fs::read_to_string(talks.artifacts_of(&talk.id).join("turn-1.err")).ok(),
                    )
                })
            };
            let first = parse_task("first.json");
            let replay = parse_task("replay.json");
            let ordinary = parse_task("ordinary.json");
            let urgent = parse_task("urgent.json");
            assert_eq!(first.id, replay.id);
            assert!(first.immediate);
            assert!(!first.urgent);
            assert!(first.solo);
            assert_eq!(
                std::fs::canonicalize(&first.repo).unwrap(),
                std::fs::canonicalize(&repo_target).unwrap()
            );
            assert!(!ordinary.immediate);
            assert!(!ordinary.urgent);
            assert!(!urgent.immediate);
            assert!(urgent.urgent);
            assert!(!queue.get(&existing.id).unwrap().immediate);
            // Only existing + first + ordinary + urgent exist (no duplicates or leaked tasks).
            assert_eq!(queue.list().len(), 4);

            // 2. Automatic notice turn (with standing_authorization = false) fails closed.
            talk::queue_magi(&mut talk, &talks, "Automatic notice: CI failed").unwrap();
            let drained = talk::drain(&mut talk, &talks).unwrap().unwrap();
            let cfg_deny = make_cfg("deny", "req-auto-off", false);
            magi::chat_goal::with_source(
                magi::chat_goal::Source::Automatic,
                talk::respond(&lease, &mut talk, &talks, &cfg_deny, &drained),
            )
            .await
            .unwrap();
            assert_eq!(talk.turns.last().unwrap().body, "denied as expected");
            assert_eq!(queue.list().len(), 4);

            // 3. Automatic notice turn (with standing_authorization = true) fails closed.
            talk::queue_magi(&mut talk, &talks, "Automatic notice: held task").unwrap();
            let drained = talk::drain(&mut talk, &talks).unwrap().unwrap();
            let cfg_deny_standing = make_cfg("deny", "req-auto-standing", true);
            magi::chat_goal::with_source(
                magi::chat_goal::Source::Automatic,
                talk::respond(&lease, &mut talk, &talks, &cfg_deny_standing, &drained),
            )
            .await
            .unwrap();
            assert_eq!(talk.turns.last().unwrap().body, "denied as expected");
            assert_eq!(queue.list().len(), 4);

            // 4. Goal wake turn fails closed.
            talk = talks.get(&talk.id).unwrap();
            talk.goals.push(
                serde_json::from_value(serde_json::json!({
                    "id": "goal-1",
                    "rev": 1,
                    "purpose": "follow",
                    "scope": "repo",
                    "condition": { "description": "done", "kind": "tasks_done" },
                    "state": "runnable",
                    "step": "continue",
                    "source_turn": 0,
                    "owner_input": "Please file shun issue #339 as immediate",
                    "tasks": [first.id],
                    "runs": [],
                    "watches": [],
                    "evidence": "",
                    "wake": 1,
                    "handled": 0,
                    "started": 1,
                    "wakes": 1,
                    "fingerprint": "fp"
                }))
                .unwrap(),
            );
            talks.put(&mut talk).unwrap();
            let cfg_deny_goal = make_cfg("deny", "req-goal", false);
            magi::chat_goal::with_source(
                magi::chat_goal::Source::Goal {
                    id: "goal-1".into(),
                    generation: 1,
                },
                talk::respond(&lease, &mut talk, &talks, &cfg_deny_goal, "Goal wake"),
            )
            .await
            .unwrap();
            assert_eq!(talk.turns.last().unwrap().body, "denied as expected");
            assert_eq!(queue.list().len(), 4);
            drop(lease);

            // 5. Real CLI external ingress (`magi talk send`) fails closed.
            let cfg_ext = make_cfg("deny", "req-ext", false);
            std::fs::write(
                repo_chat.join("magi.toml"),
                toml::to_string(&cfg_ext).unwrap(),
            )
            .unwrap();
            let sent_ext = common::magi_cli(home)
                .args([
                    "talk",
                    "send",
                    &talk.id,
                    "--request",
                    "ext-1",
                    "--sender",
                    "outside-bot",
                    "--json",
                    "Please file immediate now",
                ])
                .output()
                .unwrap();
            assert!(
                sent_ext.status.success(),
                "{}",
                String::from_utf8_lossy(&sent_ext.stderr)
            );
            let ext_reply = common::magi_cli(home)
                .args([
                    "talk",
                    "reply",
                    &talk.id,
                    "--request",
                    "ext-1",
                    "--wait",
                    "30",
                    "--json",
                ])
                .output()
                .unwrap();
            assert!(ext_reply.status.success());
            let ext_json: serde_json::Value = serde_json::from_slice(&ext_reply.stdout).unwrap();
            assert_eq!(ext_json["status"], "replied", "{ext_json}");
            assert_eq!(ext_json["reply"], "denied as expected", "{ext_json}");
            assert_eq!(queue.list().len(), 4);

            // 6. Real CLI owner ingress (`magi talk send-owner`) with OwnerBinding succeeds!
            let cfg_cli_owner = make_cfg("cli-owner", "req-cli-owner", false);
            std::fs::write(
                repo_chat.join("magi.toml"),
                toml::to_string(&cfg_cli_owner).unwrap(),
            )
            .unwrap();
            let sent_owner = common::magi_cli(home)
                .args([
                    "talk",
                    "send-owner",
                    &talk.id,
                    "--request",
                    "owner-cli-1",
                    "--json",
                    "File shun immediate from local CLI",
                ])
                .output()
                .unwrap();
            assert!(
                sent_owner.status.success(),
                "{}",
                String::from_utf8_lossy(&sent_owner.stderr)
            );
            let owner_reply = common::magi_cli(home)
                .args([
                    "talk",
                    "reply",
                    &talk.id,
                    "--request",
                    "owner-cli-1",
                    "--wait",
                    "30",
                    "--json",
                ])
                .output()
                .unwrap();
            assert!(owner_reply.status.success());
            let owner_json: serde_json::Value =
                serde_json::from_slice(&owner_reply.stdout).unwrap();
            assert_eq!(owner_json["status"], "replied", "{owner_json}");
            assert_eq!(owner_json["reply"], "cli owner ok", "{owner_json}");
            let cli_task: Task =
                serde_json::from_slice(&std::fs::read(out_dir.join("cli-owner.json")).unwrap())
                    .unwrap();
            assert!(cli_task.immediate);
            assert_eq!(queue.list().len(), 5);
        },
    );
}