magi-cli 0.5.2

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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
//! `magi plan`: the interview that turns an idea into a task file worth
//! competing.
//!
//! A competition is only as good as its task statement. A vague task buys
//! three vague candidates and a coin-toss tally, and the operator finds that
//! out forty minutes and several dollars later. So this module sits in front of
//! [`crate::queue`]: an agent interviews the operator about the idea, writes a
//! full task file, and magi files that file rather than the one-liner the
//! operator would otherwise have typed.
//!
//! # magi does not host the conversation
//!
//! There is no chat loop in here and there must not be one. The operator
//! already has `claude`, `opencode` and `agy`, each with years of work in its
//! own terminal UI - streaming, editing, file pickers, permission prompts. A
//! conversation reimplemented over captured pipes would be worse than all
//! three, and it is not what magi is for.
//!
//! What magi does instead is narrow and mechanical:
//!
//! 1. Write a *briefing* - the idea, the repository, and [`TASK_FILE_SPEC`] -
//!    to a file, telling the agent to interview the operator and write its task
//!    file to a named output path.
//! 2. Spawn the agent with stdin, stdout and stderr **inherited**, so the
//!    operator is talking to that CLI directly, in its own UI, with no magi in
//!    the middle. Nothing is captured and there is no timeout: a human deciding
//!    what to build takes as long as it takes.
//! 3. When the agent exits, read the output path, check it with
//!    [`review_draft`], and file it.
//!
//! # The draft is never thrown away
//!
//! The output path is under [`crate::run::home`]`/drafts` from the start, not a
//! temporary file, and nothing in this module deletes it. A twenty-minute
//! interview that ends in a validation failure must leave the operator holding
//! the draft, named in the error message, so the fix is an edit and
//! `magi task add --file` rather than a second interview. That is the single
//! most important behaviour here, and [`vet`] is the only place that can break
//! it.

use std::io::{IsTerminal as _, Write as _};
use std::path::{Path, PathBuf};
use std::process::Stdio;

use anyhow::{Context as _, Result, bail};

use crate::chat;
use crate::config::{AgentKind, AgentSpec, Config, which};
use crate::proc::Quiet as _;
use crate::queue::{self, Queue, Source, Task};
use crate::repos;
use crate::run;

/// The task-file shape the leader is asked to produce.
///
/// This is handed to the leader verbatim as part of its briefing, and it is
/// also the document [`review_draft`] enforces. The two are checked against
/// each other by a test, because a spec that asks for something the validator
/// does not require - or worse, the reverse - turns a good interview into a
/// rejected draft for no reason the operator can see.
pub const TASK_FILE_SPEC: &str = "\
The task file is markdown. magi hands it to every candidate verbatim and to
every judge as the statement of what was asked, so it is the only thing any of
them knows about the change. Use this shape:

# <one line, imperative: what the change is>

## Context

Why this change, and what a competent stranger to this repository needs to know
that the code does not say. Name the files, the modules and the symbols
involved, with paths.

## Change

What to do, in enough mechanical detail that two candidates could not
reasonably disagree about the target: the interfaces, the names, the shape of
the data. Leave the *design* open - how it is built, in what order, with what
internal structure. That gap is where blind judging does its work; closing it
turns the competition into three transcriptions of the same answer.

## Constraints

Anything that must hold: files that must not be touched, dependencies that must
not be added, conventions to follow, commands that must not be run.

## Completion criteria

- [ ] One observable, checkable statement per line.
- [ ] Written so that a judge holding only the diff and this list can decide
      whether each line holds. \"Works well\" cannot be judged; \"`magi plan`
      exits non-zero and names the draft path when the draft has no completion
      criteria\" can.

## Out of scope

What this competition must not touch, so that no candidate can win on breadth
instead of on the change that was asked for.

Rules for the task itself:

- One change per competition. Bundling unrelated fixes makes the diff
  unjudgeable and the statistics meaningless.
- Nothing destructive or irreversible. Several candidates run unattended and in
  parallel, and no node stops to ask.
- Visual and UX judgement stays with the operator: no judge sees a rendered
  screen, so do not ask for one to be evaluated.
";

/// Shortest draft magi will treat as a finished task without comment.
///
/// Nothing magic about the number: it is roughly a title plus one criterion,
/// and an interview that produced less than that almost always ended early.
const MIN_DRAFT_BYTES: usize = 200;

/// The problem [`review_draft`] reports for a draft that is merely suspiciously
/// short.
///
/// It is a public constant because it is the *only* problem a caller may
/// override - length alone is a smell, not a defect, and a genuinely small
/// change deserves a small task file. Callers compare against this exact string
/// to separate the warning from the refusals; [`plan`] does, and `magi task
/// add` will when it starts vetting the files it is given.
pub const SHORT_DRAFT: &str = "the draft is under 200 bytes, which is about a \
     title and one criterion: check the interview actually finished";

/// The problem reported for a draft with nothing in it at all.
const EMPTY_DRAFT: &str = "the draft is empty";

/// The problem reported for a draft with no line that could serve as a title.
const NO_TITLE: &str = "no line in the draft can be used as a title: the first \
     non-blank line must say what the change is";

/// The problem reported for a draft with no completion criteria.
const NO_CRITERIA: &str = "no completion criteria: add a `## Completion \
     criteria` heading (or `## 完了条件`) with one checkable statement per line, \
     or the candidates cannot be compared and the judges have nothing to \
     measure against";

/// Headings that mark a completion-criteria section, in the two languages this
/// repository's operator writes tasks in.
const CRITERIA_HEADINGS: [&str; 4] = [
    "completion criteria",
    "acceptance",
    "完了条件",
    "受け入れ基準",
];

/// What `magi plan` was asked to do.
#[derive(Debug, Clone)]
pub struct Opts {
    /// The rough starting idea, if the operator gave one on the command line.
    /// Absent is normal: the interview can start from nothing.
    pub idea: Option<String>,
    /// Repository the task will be competed in.
    pub repo: PathBuf,
    /// Explicit config file, as `--config`.
    pub config: Option<PathBuf>,
    /// Roster agent id to interview with. `None` picks one per the policy in
    /// [`pick`].
    pub agent: Option<String>,
    /// Priority for the filed task.
    pub priority: i32,
    /// File the draft without the confirmation prompt.
    pub yes: bool,
    /// A browser-interview chat id (or unambiguous prefix/suffix) to
    /// continue here. Its whole transcript and repository are folded into
    /// this interview's opening briefing as background - see
    /// [`chat::derived_background`]. `magi chat`, the CLI-side counterpart
    /// that could name a terminal interview as `from`, does not exist yet
    /// (issue #21), so only a browser chat can be named.
    pub from: Option<String>,
}

impl Default for Opts {
    fn default() -> Self {
        Self {
            idea: None,
            repo: PathBuf::from("."),
            config: None,
            agent: None,
            priority: 0,
            yes: false,
            from: None,
        }
    }
}

/// Interview the operator, then file the resulting task.
///
/// Blocks for as long as the conversation lasts, holding the terminal. Returns
/// the task that was filed; the draft it was filed from stays on disk either
/// way.
pub async fn plan(opts: Opts) -> Result<Task> {
    // The whole command is a handover of the terminal to another program's UI.
    // Without one there is nothing to hand over, and the operator would be left
    // watching an agent wait for input that can never arrive.
    if !std::io::stdin().is_terminal() {
        bail!(
            "`magi plan` is an interview and needs a terminal. To file a task \
             without one, pipe it to `magi task add`."
        );
    }

    // `--repo` accepts a path or a short `owner/repo` name; see
    // `resolve_repo`. Absolute either way, because the daemon that eventually
    // runs this task has its own working directory and a relative path -
    // `.`, or a short name once resolved to one - would mean the wrong
    // repository.
    let repo = resolve_repo(&opts.repo, opts.config.as_deref())?;
    let repo = repo.canonicalize().unwrap_or(repo);
    let (config, _sources) = Config::discover(&repo, opts.config.as_deref())?;
    // `--agent` beats the config, the config beats the built-in order.
    let want = opts.agent.as_deref().or(config.roles.planner.as_deref());
    let leader = pick(&config.agents, want, &installed)?;

    let background = from_background(&chat::Chats::open(), opts.from.as_deref())?;

    let dir = drafts_dir();
    std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
    let id = new_id();
    let draft = dir.join(format!("{id}.md"));
    let brief_path = dir.join(format!("{id}.briefing.md"));
    let mut brief = briefing(opts.idea.as_deref(), &repo, &draft, &config.graph.language);
    if let Some(background) = &background {
        // Prepended, so the leader reads what it is inheriting before its own
        // instructions - the order a human handing off a conversation would
        // use.
        brief = format!("{background}\n\n{brief}");
    }
    std::fs::write(&brief_path, &brief)
        .with_context(|| format!("write {}", brief_path.display()))?;

    let argv = interactive_argv(&leader, &brief_path, &dir, &repo)?;

    // Say this before handing over the terminal. `opencode` and `agy` are
    // entered plain (see `interactive_argv`), so for those two this line is the
    // operator's only way to know where the briefing is if the agent comes up
    // without having read it.
    println!("leader: {}", leader.display());
    println!("briefing: {}", brief_path.display());
    println!("task file goes to: {}", draft.display());
    println!("talk it through, then let the leader write the task file and exit.\n");

    let mut cmd = tokio::process::Command::new(&argv[0]);
    cmd.quiet();
    cmd.args(&argv[1..])
        .current_dir(&repo)
        .envs(&leader.env)
        // Inherited, not piped: the operator is talking to this CLI's own UI.
        // Capturing any of the three would replace that UI with magi's, which
        // is the mistake this module exists to avoid.
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit());
    // No timeout, and no `kill_on_drop`. Every other agent invocation in magi
    // is bounded because nothing is watching it; this one is bounded by a human
    // who is sitting right there, and killing their conversation on a clock
    // would lose the interview.
    let status = cmd
        .status()
        .await
        .with_context(|| format!("spawn {} (is it installed?)", argv[0]))?;
    if !status.success() {
        // Not fatal on its own: an agent that wrote the task file and then
        // exited badly - or that the operator quit with Ctrl-C after it had
        // written - still leaves something worth filing. Whether there is a
        // draft is the question that matters, and `vet` answers it next.
        eprintln!("note: {} exited with {status}", argv[0]);
    }

    let (body, warnings) = vet(&draft)?;
    for w in &warnings {
        eprintln!("warning: {w}");
    }

    let title = queue::title_from(&body, 72);
    if !opts.yes {
        println!("\n{title}");
        println!("draft: {} ({} bytes)", draft.display(), body.len());
        print!("file this task? [y/N] ");
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin()
            .read_line(&mut answer)
            .context("read the confirmation")?;
        if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
            bail!(
                "not filed. The draft is kept at {0} - file it later with \
                 `magi task add --file {0}`.",
                draft.display()
            );
        }
    }

    let q = Queue::open();
    let mut task = Task::new(title, body, repo, Source::Human);
    task.priority = opts.priority;
    q.put(&mut task)?;
    println!("filed {} {}", task.short(), task.title);
    Ok(task)
}

/// Is this draft usable as a magi task?
///
/// Separated from [`plan`] so that the rules are assertable without an
/// interview, and so `magi task add` can reuse them for the files it is handed.
///
/// Every problem found is returned, not just the first: an operator about to
/// edit a draft wants the whole list, and a validator that reveals one defect
/// per run turns one fix into three.
pub fn review_draft(body: &str) -> Result<(), Vec<String>> {
    // An empty draft is reported as exactly one problem. It has no title and no
    // criteria either, but saying so would be three ways of describing the same
    // nothing, and the operator's next action is the same in all three cases.
    if body.trim().is_empty() {
        return Err(vec![EMPTY_DRAFT.to_owned()]);
    }

    let mut problems = Vec::new();

    // Delegated rather than reimplemented: whatever `title_from` would accept
    // is by definition a usable title, since it is what ends up on the task.
    // Its placeholder is the queue's way of saying "there was nothing here".
    if queue::title_from(body, 72) == "(empty task)" {
        problems.push(NO_TITLE.to_owned());
    }

    if !has_completion_criteria(body) {
        problems.push(NO_CRITERIA.to_owned());
    }

    if body.len() < MIN_DRAFT_BYTES {
        problems.push(SHORT_DRAFT.to_owned());
    }

    if problems.is_empty() {
        Ok(())
    } else {
        Err(problems)
    }
}

/// Read the draft, check it, and split the refusals from the warnings.
///
/// The draft file is read and never written, moved or removed, whatever the
/// outcome - that is what makes a rejected interview recoverable, and the error
/// names the path so the operator does not have to guess it.
fn vet(draft: &Path) -> Result<(String, Vec<String>)> {
    let body = std::fs::read_to_string(draft).with_context(|| {
        format!(
            "no task file at {} - the leader was asked to write one there",
            draft.display()
        )
    })?;
    match review_draft(&body) {
        Ok(()) => Ok((body, Vec::new())),
        Err(problems) => {
            let (soft, hard): (Vec<String>, Vec<String>) =
                problems.into_iter().partition(|p| p == SHORT_DRAFT);
            if hard.is_empty() {
                return Ok((body, soft));
            }
            let list = hard
                .iter()
                .map(|p| format!("  - {p}"))
                .collect::<Vec<_>>()
                .join("\n");
            bail!(
                "the draft is not usable as a magi task:\n{list}\n\n\
                 It is kept at {0} - nothing was thrown away. Edit it and file \
                 it with `magi task add --file {0}`.",
                draft.display()
            );
        }
    }
}

/// Does this draft state how anyone would know the task was done?
///
/// Two forms count: a heading naming the section, or a checkbox list anywhere.
/// The heading match is deliberately lenient about decoration, because the same
/// section arrives as `## Acceptance`, `**Acceptance criteria**` or `完了条件:`
/// depending on which CLI wrote it, and rejecting a real criteria section over
/// asterisks would teach the operator to distrust the check. An undecorated
/// line has to *be* the phrase, though: prose that happens to contain the word
/// "acceptance" is not a section.
fn has_completion_criteria(body: &str) -> bool {
    body.lines().any(|line| {
        let line = line.trim();
        is_checkbox(line) || is_criteria_heading(line)
    })
}

fn is_criteria_heading(line: &str) -> bool {
    let decorated = line.starts_with(['#', '*', '_']);
    let bare = line
        .trim_start_matches(['#', '*', '_', '>', ' '])
        .trim_end_matches(['#', '*', '_', ':', '', ' '])
        .trim()
        .to_lowercase();
    CRITERIA_HEADINGS.iter().any(|h| {
        if decorated {
            bare.starts_with(h)
        } else {
            bare == *h
        }
    })
}

fn is_checkbox(line: &str) -> bool {
    let Some(rest) = line.strip_prefix(['-', '*', '+']) else {
        return false;
    };
    let rest = rest.trim_start();
    rest.starts_with("[ ]") || rest.starts_with("[x]") || rest.starts_with("[X]")
}

/// Where drafts live: under the run home, never in a temporary directory the OS
/// may reap and never inside the repository, where it would show up as an
/// untracked file in every candidate's worktree.
fn drafts_dir() -> PathBuf {
    run::home().join("drafts")
}

fn new_id() -> String {
    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
    let seed = crate::rng::entropy();
    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
}

/// Resolve `--repo` to a directory.
///
/// An existing directory is used as-is. Anything else is tried as a short
/// name (`owner/repo`) against `[repos] roots` - which needs a config lookup
/// of its own, since the roots have to be known before a name can be resolved
/// against them. That lookup uses `raw` exactly as [`Config::discover`]
/// itself would, so a short name that happens to also be a config layer's
/// directory is not treated specially - it already failed the `is_dir` check
/// above, so this is purely about finding `[repos] roots`, most often from
/// the machine layer.
fn resolve_repo(raw: &Path, explicit_config: Option<&Path>) -> Result<PathBuf> {
    if raw.is_dir() {
        return Ok(raw.to_owned());
    }
    let (cfg, _) = Config::discover(raw, explicit_config)?;
    repos::resolve(&cfg.repos.roots, &raw.to_string_lossy())
}

/// The background block for `--from`, if given.
///
/// Split out of [`plan`] so the one mistake an operator can make with this
/// flag - naming a chat that does not exist - is testable without a
/// terminal. Reuses [`chat::derived_background`] rather than rendering the
/// transcript a second way, so the terminal interview and the browser
/// interview describe a derived conversation identically.
fn from_background(chats: &chat::Chats, from: Option<&str>) -> Result<Option<String>> {
    match from {
        None => Ok(None),
        Some(id) => Ok(Some(chat::derived_background(&chats.get(id)?))),
    }
}

/// Can this agent's CLI actually be run on this machine?
pub fn installed(spec: &AgentSpec) -> bool {
    // A `command` agent has no program of its own to look for - its argv is the
    // operator's, and they are the authority on whether it runs.
    spec.kind.program().is_none_or(which)
}

/// Choose the agent that will conduct the interview.
///
/// `available` is a parameter rather than a call to [`which`] so the order
/// below is assertable on a machine with none of these CLIs installed, which is
/// every CI runner.
///
/// The order, and why:
///
/// 1. An explicit `--agent` always wins, and is an error rather than a fallback
///    when it is unusable. The operator naming a leader has a reason, and
///    silently interviewing them with a different model would waste the
///    conversation.
/// 2. Otherwise a [`AgentKind::Claude`] seat, ahead of the roster order. It is
///    the only one of the three CLIs magi can address before the first turn
///    (see [`crate::agent`]'s session table), so it is the only one that can be
///    handed the briefing as an argument and come up already knowing what the
///    interview is for - with the others the operator has to point them at the
///    briefing themselves. For the one command whose whole value is a smooth
///    conversation, that difference decides it.
/// 3. Otherwise the first runnable agent in roster order, because the roster
///    order is the operator's own stated preference and magi has nothing better
///    to go on.
pub fn pick(
    agents: &[AgentSpec],
    want: Option<&str>,
    available: &dyn Fn(&AgentSpec) -> bool,
) -> Result<AgentSpec> {
    if let Some(id) = want {
        let spec = agents
            .iter()
            .find(|a| a.id == id)
            .with_context(|| format!("no agent `{id}` in the roster; it has {}", ids(agents)))?;
        if !available(spec) {
            bail!(
                "agent `{}` needs `{}` on PATH; install it or pass a different \
                 --agent",
                spec.id,
                spec.kind.program().unwrap_or("its command")
            );
        }
        return Ok(spec.clone());
    }

    if agents.is_empty() {
        bail!(
            "the agent roster is empty, so there is nobody to plan with: \
             install one of claude, opencode or agy - magi derives a roster \
             from what is on PATH - or add an [[agents]] entry to magi.toml."
        );
    }

    if let Some(spec) = agents
        .iter()
        .find(|a| a.kind == AgentKind::Claude && available(a))
    {
        return Ok(spec.clone());
    }

    agents
        .iter()
        .find(|a| available(a))
        .cloned()
        .with_context(|| {
            let missing = agents
                .iter()
                .filter_map(|a| a.kind.program())
                .collect::<Vec<_>>()
                .join(", ");
            format!(
                "no agent in the roster can be run here: install one of \
                 {missing}, or add an [[agents]] entry to magi.toml for a CLI \
                 you do have"
            )
        })
}

fn ids(agents: &[AgentSpec]) -> String {
    if agents.is_empty() {
        return "no agents at all".to_owned();
    }
    agents
        .iter()
        .map(|a| a.id.clone())
        .collect::<Vec<_>>()
        .join(", ")
}

/// The argv that puts the operator in a conversation with `spec`.
///
/// Deliberately *not* [`crate::agent`]'s `build_command`: that one builds the
/// headless invocation the graph needs - `claude -p`, `opencode run`,
/// `agy --output-format json` - which prints one answer and exits, and would
/// turn this interview into a single non-interactive turn. Every flag there
/// exists to make a CLI machine-readable and unattended; every flag here exists
/// to leave it exactly as interactive as the operator is used to.
///
/// Two other differences from the headless path are on purpose:
///
/// - No permission bypass. `bypassPermissions` / `--dangerously-skip-permissions`
///   are how an unattended node gets work done with nobody to ask. Here there
///   is somebody to ask, sitting at the terminal, and deciding on their behalf
///   would be magi overstepping.
/// - `spec.extra_args` is passed only for `kind = "command"`. For the three
///   known CLIs those arguments were written for the headless invocation - an
///   `--output-format json` or a `--print-timeout` among them ends the
///   interview before it starts. For a `command` agent the whole argv is the
///   operator's, so their arguments *are* the invocation.
fn interactive_argv(
    spec: &AgentSpec,
    brief_path: &Path,
    widen: &Path,
    repo: &Path,
) -> Result<Vec<String>> {
    let mut argv: Vec<String> = Vec::new();
    match spec.kind {
        AgentKind::Claude => {
            argv.push("claude".to_owned());
            if let Some(m) = &spec.model {
                argv.push("--model".to_owned());
                argv.push(m.clone());
            }
            // The briefing and the task file both live under the run home,
            // outside the repository, so the workspace has to be widened to
            // reach them - the same reason `agent::build_command` adds
            // `--add-dir` for a file-delivered prompt.
            argv.push("--add-dir".to_owned());
            argv.push(widen.to_string_lossy().into_owned());
            // The positional argument is claude's opening prompt, and the
            // session stays interactive because `-p` is absent. This is the
            // whole advantage that puts claude first in `pick`.
            argv.push(format!(
                "Read the file at {} and follow it. Interview me about the \
                 change first; write the task file only once I say the plan is \
                 right.",
                brief_path.display()
            ));
        }
        // Entered plain, in the repository. Neither CLI's interactive form has
        // a documented way to be handed an opening prompt that magi can rely
        // on, and guessing a flag would break the one command an operator
        // cannot work around by editing a config file. They read the briefing
        // because magi printed its path before handing over the terminal.
        AgentKind::Opencode => argv.push("opencode".to_owned()),
        AgentKind::Antigravity => {
            argv.push("agy".to_owned());
            argv.push("--add-dir".to_owned());
            argv.push(widen.to_string_lossy().into_owned());
        }
        AgentKind::Command => {
            if spec.command.is_empty() {
                bail!("agent `{}` has kind = \"command\" but no command", spec.id);
            }
            // Same placeholders as the headless path, so an operator's existing
            // `command` agent works here without a second spelling to learn.
            for raw in &spec.command {
                argv.push(
                    raw.replace("{prompt_file}", &brief_path.to_string_lossy())
                        .replace("{cwd}", &repo.to_string_lossy()),
                );
            }
            argv.extend(spec.extra_args.iter().cloned());
        }
    }
    Ok(argv)
}

/// What the leader is told before it starts talking.
fn briefing(idea: Option<&str>, repo: &Path, out: &Path, language: &str) -> String {
    let idea = match idea.map(str::trim).filter(|s| !s.is_empty()) {
        Some(i) => i.to_owned(),
        None => "The operator has not written the idea down yet. Ask them what \
                 they want to change, starting from the repository itself."
            .to_owned(),
    };
    // The interview is the operator talking, so their language matters more
    // here than it does in any prompt the graph sends: an agent that answers a
    // Japanese question in English makes the conversation slower for exactly
    // the person magi is trying to help.
    let lang = if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
        String::new()
    } else {
        format!("\n\nConduct the interview in {language}, and write the task file in {language}.")
    };
    format!(
        "You are the planning leader for magi, which runs a blind \
         multi-agent implementation competition: several agents will implement \
         the task file you write, in isolated worktrees, unaware of each other, \
         and judges will rank the results without knowing who wrote what.\n\n\
         Your job is not to implement anything. It is to interview the operator \
         until the change is pinned down, and then write one task file.\n\n\
         # Repository\n\n{repo}\n\n\
         Read it before you start asking. Questions that the code already \
         answers spend the operator's patience for nothing.\n\n\
         # The idea\n\n{idea}\n\n\
         # How to run the interview\n\n\
         - Ask about what you cannot determine yourself: intent, scope, which \
         of several defensible designs the operator wants, what must not \
         change.\n\
         - Ask a few questions at a time and wait for the answers. Do not \
         produce the task file after one exchange.\n\
         - Disagree when you have grounds. A leader that agrees with everything \
         adds nothing to what the operator already typed.\n\
         - Confirm the plan in your own words and get an explicit yes before \
         writing.\n\n\
         # What to write, and where\n\n\
         When the operator agrees the plan is right, write the task file to \
         exactly this path:\n\n{out}\n\n\
         Write that file and nothing else. Do not modify the repository: the \
         competing agents do the implementation, and a repository you have \
         already edited makes their diffs unjudgeable.\n\n\
         magi will refuse a task file with no completion criteria, so those are \
         not optional.\n\n\
         # Task file specification\n\n{spec}\n\n\
         When the file is written, tell the operator it is done and exit.{lang}",
        repo = repo.display(),
        out = out.display(),
        spec = TASK_FILE_SPEC,
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A task file of the shape `AGENTS.md` and [`TASK_FILE_SPEC`] describe.
    fn good_draft() -> String {
        "# Report per-node durations in `magi show`\n\
         \n\
         ## Context\n\
         \n\
         `report::run` prints a run's nodes but not how long each took, so the \
         numbers behind a slow competition have to be recovered from \
         `run.json`'s `events` with `jq`.\n\
         \n\
         ## Change\n\
         \n\
         Add a duration column to the node table in `src/report.rs`, computed \
         from the existing `events` timestamps in `RunState`.\n\
         \n\
         ## Constraints\n\
         \n\
         No new dependencies. Do not change `run.json`'s schema.\n\
         \n\
         ## Completion criteria\n\
         \n\
         - [ ] `magi show <id>` prints a duration for every finished node.\n\
         - [ ] A node still running prints its elapsed time, not a blank.\n\
         - [ ] `cargo test` passes.\n\
         \n\
         ## Out of scope\n\
         \n\
         The TUI's detail pane.\n"
            .to_owned()
    }

    fn spec(id: &str, kind: AgentKind) -> AgentSpec {
        AgentSpec {
            id: id.to_owned(),
            kind,
            model: None,
            command: Vec::new(),
            extra_args: Vec::new(),
            env: Default::default(),
            prompt_delivery: None,
        }
    }

    /// Availability stub: an agent is runnable unless its id was listed as
    /// missing. Keeps the selection tests off `PATH` entirely.
    fn without<'a>(missing: &'a [&'a str]) -> impl Fn(&AgentSpec) -> bool + 'a {
        move |a: &AgentSpec| !missing.contains(&a.id.as_str())
    }

    #[test]
    fn a_realistic_task_file_is_accepted() {
        let draft = good_draft();
        assert!(
            draft.len() >= MIN_DRAFT_BYTES,
            "the fixture must be a real task file, not a stub"
        );
        assert_eq!(review_draft(&draft), Ok(()));
    }

    #[test]
    fn a_bad_draft_reports_every_problem_at_once_rather_than_one_per_run() {
        // Markdown decoration and nothing else: no usable title, no criteria,
        // and far too short.
        let problems = review_draft("###\n\n- - -\n").expect_err("must be rejected");
        assert_eq!(problems.len(), 3, "{problems:?}");
        assert_eq!(problems[0], NO_TITLE);
        assert_eq!(problems[1], NO_CRITERIA);
        assert_eq!(problems[2], SHORT_DRAFT);
    }

    #[test]
    fn an_empty_draft_is_reported_as_empty_and_not_as_three_other_things() {
        for body in ["", "   \n\t\n  "] {
            let problems = review_draft(body).expect_err("must be rejected");
            assert_eq!(problems, vec![EMPTY_DRAFT.to_owned()], "body {body:?}");
        }
    }

    #[test]
    fn a_draft_without_a_usable_title_is_rejected() {
        // Long enough, and it has criteria - the title is the only defect.
        let body = format!(
            "#\n\n## Completion criteria\n\n- it works\n\n{}",
            "x".repeat(300)
        );
        assert_eq!(
            review_draft(&body).expect_err("must be rejected"),
            vec![NO_TITLE.to_owned()]
        );
    }

    #[test]
    fn a_draft_without_completion_criteria_is_rejected_on_that_alone() {
        let body = format!(
            "# Rework the config loader\n\n## Change\n\nMake it layered.\n\n{}",
            "prose. ".repeat(60)
        );
        assert!(body.len() >= MIN_DRAFT_BYTES);
        assert_eq!(
            review_draft(&body).expect_err("must be rejected"),
            vec![NO_CRITERIA.to_owned()]
        );
    }

    #[test]
    fn completion_criteria_are_recognised_in_english_and_japanese_and_as_checkboxes() {
        let filler = "x".repeat(300);
        for section in [
            "## Completion criteria\n\n- everything holds",
            "## Acceptance\n\n- everything holds",
            "### Acceptance criteria (all of them)\n\n- everything holds",
            "**Completion criteria**\n\n- everything holds",
            "## 完了条件\n\n- 全部そろっている",
            "## 受け入れ基準\n\n- 全部そろっている",
            "完了条件:\n\n- 全部そろっている",
            "- [ ] no heading at all, just a checkbox",
        ] {
            let body = format!("# A real change\n\n{section}\n\n{filler}");
            assert_eq!(
                review_draft(&body),
                Ok(()),
                "must accept criteria written as {section:?}"
            );
        }
    }

    #[test]
    fn prose_that_merely_mentions_acceptance_is_not_a_criteria_section() {
        let body = format!(
            "# A real change\n\nAcceptance of the design is up to you.\n\n{}",
            "x".repeat(300)
        );
        assert_eq!(
            review_draft(&body).expect_err("prose is not a section"),
            vec![NO_CRITERIA.to_owned()]
        );
    }

    #[test]
    fn a_complete_but_tiny_draft_is_warned_about_and_not_refused() {
        let body = "# Bump the poll interval to 5s\n\n## Completion criteria\n\n- [ ] it is 5s\n";
        assert!(body.len() < MIN_DRAFT_BYTES);
        let problems = review_draft(body).expect_err("must warn");
        assert_eq!(problems, vec![SHORT_DRAFT.to_owned()]);

        // And `vet` must let it through as a warning rather than a refusal,
        // which is what makes `--yes` able to override length alone.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tiny.md");
        std::fs::write(&path, body).unwrap();
        let (read_back, warnings) = vet(&path).expect("length alone must not refuse");
        assert_eq!(read_back, body);
        assert_eq!(warnings, vec![SHORT_DRAFT.to_owned()]);
    }

    /// The behaviour a twenty-minute interview depends on: a draft magi refuses
    /// is still there, byte for byte, at the path the refusal prints.
    #[test]
    fn a_refused_draft_is_still_on_disk_at_the_path_the_error_names() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("20260902-231501-ab12.md");
        let body = "# Something the operator spent twenty minutes on\n\nBut with no criteria.\n";
        std::fs::write(&path, body).unwrap();

        let err = vet(&path).expect_err("no criteria must be refused");
        let msg = err.to_string();
        assert!(
            msg.contains(&path.display().to_string()),
            "the error must name the draft path: {msg}"
        );
        assert!(msg.contains("magi task add --file"), "{msg}");
        assert_eq!(
            std::fs::read_to_string(&path).expect("the draft must survive its refusal"),
            body
        );
    }

    #[test]
    fn a_draft_lives_under_the_run_home_so_it_outlives_the_command_that_wrote_it() {
        assert_eq!(drafts_dir(), run::home().join("drafts"));
    }

    #[test]
    fn a_missing_draft_is_reported_against_the_path_the_leader_was_given() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("never-written.md");
        let msg = vet(&path).expect_err("nothing to file").to_string();
        assert!(msg.contains(&path.display().to_string()), "{msg}");
    }

    #[test]
    fn the_leader_is_the_claude_seat_even_when_it_is_not_first_in_the_roster() {
        let agents = [
            spec("oc", AgentKind::Opencode),
            spec("opus", AgentKind::Claude),
            spec("agy", AgentKind::Antigravity),
        ];
        let got = pick(&agents, None, &without(&[])).expect("a leader");
        assert_eq!(got.id, "opus");
    }

    #[test]
    fn the_leader_falls_back_to_the_first_installed_agent_in_roster_order() {
        let agents = [
            spec("opus", AgentKind::Claude),
            spec("oc", AgentKind::Opencode),
            spec("agy", AgentKind::Antigravity),
        ];
        let got = pick(&agents, None, &without(&["opus", "oc"])).expect("a leader");
        assert_eq!(got.id, "agy");
    }

    #[test]
    fn an_empty_roster_says_what_to_install() {
        let msg = pick(&[], None, &without(&[]))
            .expect_err("nobody to plan with")
            .to_string();
        assert!(msg.contains("roster is empty"), "{msg}");
        assert!(msg.contains("claude"), "{msg}");
        assert!(msg.contains("magi.toml"), "{msg}");
    }

    #[test]
    fn a_roster_with_nothing_installed_names_the_programs_that_are_missing() {
        let agents = [
            spec("opus", AgentKind::Claude),
            spec("oc", AgentKind::Opencode),
        ];
        let err = pick(&agents, None, &without(&["opus", "oc"])).expect_err("nothing runnable");
        let msg = format!("{err:#}");
        assert!(msg.contains("claude"), "{msg}");
        assert!(msg.contains("opencode"), "{msg}");
    }

    #[test]
    fn an_explicitly_named_agent_wins_over_the_claude_preference() {
        let agents = [
            spec("opus", AgentKind::Claude),
            spec("oc", AgentKind::Opencode),
        ];
        let got = pick(&agents, Some("oc"), &without(&[])).expect("a leader");
        assert_eq!(got.id, "oc");
    }

    #[test]
    fn an_unknown_agent_id_lists_the_ids_that_do_exist() {
        let agents = [
            spec("opus", AgentKind::Claude),
            spec("oc", AgentKind::Opencode),
        ];
        let msg = pick(&agents, Some("gemini"), &without(&[]))
            .expect_err("no such agent")
            .to_string();
        assert!(msg.contains("gemini"), "{msg}");
        assert!(msg.contains("opus, oc"), "{msg}");
    }

    #[test]
    fn an_explicitly_named_agent_that_is_not_installed_is_an_error_not_a_fallback() {
        let agents = [
            spec("opus", AgentKind::Claude),
            spec("oc", AgentKind::Opencode),
        ];
        let msg = pick(&agents, Some("oc"), &without(&["oc"]))
            .expect_err("must not silently interview with another model")
            .to_string();
        assert!(msg.contains("opencode"), "{msg}");
        assert!(msg.contains("--agent"), "{msg}");
    }

    /// The spec and the validator are one contract in two places, and only this
    /// test keeps them from drifting: a spec that stopped asking for completion
    /// criteria would produce drafts magi refuses, with the operator following
    /// magi's own instructions.
    #[test]
    fn the_task_file_spec_asks_for_the_completion_criteria_the_validator_requires() {
        assert!(TASK_FILE_SPEC.contains("## Completion criteria"));
        assert!(has_completion_criteria(TASK_FILE_SPEC));
        assert_eq!(
            review_draft(TASK_FILE_SPEC),
            Ok(()),
            "the spec must pass the validator it is paired with"
        );
    }

    #[test]
    fn the_briefing_carries_the_idea_the_repository_the_output_path_and_the_spec() {
        let b = briefing(
            Some("make the queue drain faster"),
            Path::new("/src/magi"),
            Path::new("/home/magi/drafts/x.md"),
            "en",
        );
        assert!(b.contains("make the queue drain faster"));
        assert!(b.contains("/src/magi"));
        assert!(b.contains("/home/magi/drafts/x.md"));
        assert!(b.contains("## Completion criteria"));
        assert!(
            !b.contains("Conduct the interview in"),
            "en adds no language line"
        );
    }

    #[test]
    fn a_briefing_without_an_idea_tells_the_leader_to_start_the_conversation() {
        let b = briefing(
            Some("   "),
            Path::new("/src/magi"),
            Path::new("/o.md"),
            "ja",
        );
        assert!(b.contains("has not written the idea down yet"));
        assert!(b.contains("Conduct the interview in ja"));
    }

    #[test]
    fn the_interactive_invocation_is_never_the_headless_one() {
        let brief = Path::new("/home/magi/drafts/x.briefing.md");
        let widen = Path::new("/home/magi/drafts");
        let repo = Path::new("/src/magi");

        let mut claude = spec("opus", AgentKind::Claude);
        claude.model = Some("opus".to_owned());
        // Flags that would end the conversation, and the ones that carry it.
        let argv = interactive_argv(&claude, brief, widen, repo).unwrap();
        assert_eq!(argv[0], "claude");
        assert!(!argv.iter().any(|a| a == "-p" || a == "--output-format"));
        assert!(!argv.iter().any(|a| a == "--permission-mode"));
        assert!(argv.windows(2).any(|w| w == ["--model", "opus"]));
        assert!(
            argv.windows(2)
                .any(|w| w == ["--add-dir", "/home/magi/drafts"])
        );
        assert!(
            argv.last().unwrap().contains(&brief.display().to_string()),
            "claude gets the briefing as its opening prompt: {argv:?}"
        );

        assert_eq!(
            interactive_argv(&spec("oc", AgentKind::Opencode), brief, widen, repo).unwrap(),
            vec!["opencode".to_owned()],
            "opencode is entered plain, in the repository"
        );
        assert_eq!(
            interactive_argv(&spec("agy", AgentKind::Antigravity), brief, widen, repo).unwrap(),
            vec![
                "agy".to_owned(),
                "--add-dir".to_owned(),
                "/home/magi/drafts".to_owned()
            ]
        );
    }

    #[test]
    fn a_command_agent_gets_its_own_argv_with_the_briefing_substituted_in() {
        let mut cmd = spec("local", AgentKind::Command);
        cmd.command = vec![
            "my-agent".to_owned(),
            "--brief".to_owned(),
            "{prompt_file}".to_owned(),
            "--in".to_owned(),
            "{cwd}".to_owned(),
        ];
        cmd.extra_args = vec!["--interactive".to_owned()];
        let argv = interactive_argv(
            &cmd,
            Path::new("/b.md"),
            Path::new("/drafts"),
            Path::new("/src/magi"),
        )
        .unwrap();
        assert_eq!(
            argv,
            vec![
                "my-agent",
                "--brief",
                "/b.md",
                "--in",
                "/src/magi",
                "--interactive"
            ]
        );

        let empty = spec("broken", AgentKind::Command);
        let msg = interactive_argv(&empty, Path::new("/b.md"), Path::new("/d"), Path::new("/r"))
            .expect_err("a command agent with no command cannot be spawned")
            .to_string();
        assert!(msg.contains("broken"), "{msg}");
    }
    #[test]
    fn the_configured_planner_is_used_and_an_explicit_agent_still_beats_it() {
        // The interview is the one node a human sits through, and on a phone
        // there is no `--agent` to type - so it has to be settable in config.
        let agents = [
            spec("opus", AgentKind::Claude),
            spec("oc", AgentKind::Opencode),
            spec("agy", AgentKind::Antigravity),
        ];

        // Config names the seat: roster order does not get a say.
        let by_config = pick(&agents, Some("oc"), &without(&[])).expect("configured");
        assert_eq!(by_config.id, "oc");

        // Nothing named anywhere falls back to the built-in order, which
        // prefers a claude seat.
        let by_default = pick(&agents, None, &without(&[])).expect("default");
        assert_eq!(by_default.kind, AgentKind::Claude);

        // A configured seat that is not installed is an error rather than a
        // silent substitution: an operator who named an interviewer had a
        // reason, and quietly using a different model wastes the conversation.
        let err = pick(&agents, Some("oc"), &without(&["oc"])).expect_err("not runnable");
        assert!(err.to_string().contains("oc"), "{err}");
    }

    #[test]
    fn resolve_repo_uses_an_existing_directory_as_is() {
        let dir = tempfile::tempdir().unwrap();
        let resolved = resolve_repo(dir.path(), None).expect("an existing directory resolves");
        assert_eq!(resolved, dir.path());
    }

    #[test]
    fn resolve_repo_resolves_a_short_name_against_configured_roots() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("root");
        let checkout = root.join("github.com").join("yukimemi").join("magi");
        std::fs::create_dir_all(checkout.join(".git")).unwrap();

        let config_path = tmp.path().join("machine.toml");
        std::fs::write(
            &config_path,
            format!(
                "[repos]\nroots = [{:?}]\n",
                root.to_string_lossy().into_owned()
            ),
        )
        .unwrap();

        let resolved =
            resolve_repo(Path::new("yukimemi/magi"), Some(&config_path)).expect("must resolve");
        assert_eq!(resolved, checkout.canonicalize().unwrap());
    }

    #[test]
    fn resolve_repo_reports_an_unresolvable_short_name() {
        let tmp = tempfile::tempdir().unwrap();
        let config_path = tmp.path().join("machine.toml");
        std::fs::write(&config_path, "[repos]\nroots = []\n").unwrap();

        let err = resolve_repo(Path::new("nope/nope"), Some(&config_path))
            .expect_err("nothing configured to match")
            .to_string();
        assert!(err.contains("nope/nope"), "{err}");
    }

    #[test]
    fn from_background_is_none_when_no_chat_is_named() {
        let tmp = tempfile::tempdir().unwrap();
        let chats = chat::Chats::at(tmp.path().join("chats"));
        assert_eq!(from_background(&chats, None).unwrap(), None);
    }

    #[test]
    fn from_background_names_the_missing_chat_id() {
        let tmp = tempfile::tempdir().unwrap();
        let chats = chat::Chats::at(tmp.path().join("chats"));
        let err = from_background(&chats, Some("nope"))
            .expect_err("no such chat")
            .to_string();
        assert!(err.contains("nope"), "{err}");
    }
}