magi/config.rs
1//! Run configuration: the agent roster, the shape of the graph, and the
2//! blindness / verification policy.
3//!
4//! Discovery order (first hit wins):
5//!
6//! 1. `--config <path>`
7//! 2. `<repo>/magi.toml`
8//! 3. `<repo>/.magi/config.toml`
9//! 4. `<config_dir>/magi/config.toml`
10//! 5. built-in defaults, with the agent roster derived from the agent CLIs
11//! actually installed on this machine
12use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14
15use anyhow::{Context as _, Result, bail};
16use serde::{Deserialize, Serialize};
17
18/// Which CLI drives an agent.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
20#[serde(rename_all = "lowercase")]
21pub enum AgentKind {
22 /// Anthropic Claude Code (`claude -p`).
23 Claude,
24 /// opencode (`opencode run`).
25 Opencode,
26 /// Antigravity CLI (`agy -p`). Gemini CLI is deliberately absent: Google
27 /// retired the standalone client for individual accounts in favour of this
28 /// one, so an adapter for it would be dead code on a live machine.
29 Antigravity,
30 /// OpenAI Codex CLI (`codex exec`). The one roster member with a real
31 /// read-only mode: `--sandbox read-only` is enforced by the CLI, not by
32 /// the prompt.
33 Codex,
34 /// oh-my-pi (`omp -p --mode=json`). Another CLI with no read-only mode of
35 /// its own - `--auto-approve` gates reads and writes together - so a
36 /// read-only seat rests on the prompt and on the worktree discipline the
37 /// other non-codex seats already rely on. It is also the roster member that
38 /// reaches DeepSeek, whose models ship in `omp`'s own catalog.
39 Omp,
40 /// Arbitrary command. The escape hatch, and what the test suite drives.
41 Command,
42}
43
44impl AgentKind {
45 /// Executable that must be on `PATH` for this kind, if any.
46 pub fn program(self) -> Option<&'static str> {
47 match self {
48 Self::Claude => Some("claude"),
49 Self::Opencode => Some("opencode"),
50 Self::Antigravity => Some("agy"),
51 Self::Codex => Some("codex"),
52 Self::Omp => Some("omp"),
53 Self::Command => None,
54 }
55 }
56
57 /// Lowercase name as written in the config file.
58 pub fn as_str(self) -> &'static str {
59 match self {
60 Self::Claude => "claude",
61 Self::Opencode => "opencode",
62 Self::Antigravity => "antigravity",
63 Self::Codex => "codex",
64 Self::Omp => "omp",
65 Self::Command => "command",
66 }
67 }
68
69 /// Every kind the roster can name, in display order.
70 ///
71 /// This is what `magi doctor` lists, and it has to be one list rather than
72 /// the same set typed out again wherever a kind is enumerated. The last
73 /// time it was typed out twice, `omp` was added as a roster member and the
74 /// doctor output went on saying the machine had four CLIs - which reads as
75 /// "that agent is not installed" to the person the command exists for.
76 pub const ALL: [Self; 6] = [
77 Self::Claude,
78 Self::Opencode,
79 Self::Antigravity,
80 Self::Codex,
81 Self::Omp,
82 Self::Command,
83 ];
84}
85
86/// How the prompt reaches the agent process.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
88#[serde(rename_all = "lowercase")]
89pub enum Delivery {
90 /// Piped on stdin.
91 Stdin,
92 /// Passed as a positional argument. Beware OS command-line limits.
93 Argv,
94 /// Written to a file; the agent is told to read it. No length limit.
95 File,
96}
97
98/// One addressable agent in the roster.
99#[derive(Debug, Clone, Deserialize, Serialize)]
100#[serde(deny_unknown_fields)]
101pub struct AgentSpec {
102 /// Stable identifier used by `[roles]` and by the stats tables.
103 pub id: String,
104 /// Which CLI to drive.
105 pub kind: AgentKind,
106 /// Model passed through to the CLI (`--model` / `-m`). CLI default if unset.
107 #[serde(default)]
108 pub model: Option<String>,
109 /// `kind = "command"` only: argv. Supports `{prompt_file}`, `{cwd}`,
110 /// `{label}`, `{session}` placeholders.
111 #[serde(default)]
112 pub command: Vec<String>,
113 /// Extra arguments appended to the built command line.
114 #[serde(default)]
115 pub extra_args: Vec<String>,
116 /// Extra environment variables for the child process.
117 #[serde(default)]
118 pub env: BTreeMap<String, String>,
119 /// Override the per-kind prompt delivery default.
120 #[serde(default)]
121 pub prompt_delivery: Option<Delivery>,
122}
123
124impl AgentSpec {
125 /// Default prompt delivery for this agent.
126 ///
127 /// `opencode` and `agy` take the prompt as an argument, which on Windows
128 /// caps out around 32 KiB — well under a judging prompt carrying three
129 /// patches — so both get a file instead.
130 pub fn delivery(&self) -> Delivery {
131 self.prompt_delivery.unwrap_or(match self.kind {
132 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
133 // `codex exec -` reads the prompt from stdin, so the whole
134 // instruction arrives without an argv length limit and without a
135 // tool round-trip to open a file.
136 AgentKind::Codex => Delivery::Stdin,
137 // `omp -p` reads the prompt from stdin too, and a judging prompt
138 // carrying three patches is well past the Windows argv cap, so this
139 // is the only delivery that works for every node.
140 AgentKind::Omp => Delivery::Stdin,
141 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
142 })
143 }
144
145 /// Human-facing label, e.g. `opus (claude:opus)`.
146 pub fn display(&self) -> String {
147 match &self.model {
148 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
149 None => format!("{} ({})", self.id, self.kind.as_str()),
150 }
151 }
152}
153
154/// A standalone seat's agent: one roster id, or an ordered fallback chain.
155///
156/// The string form is what every existing config uses and serializes back as
157/// a string; the array form tries each id at most once, in order, moving on
158/// when a call ends in quota or fails (see [`crate::agent::pick_chain`]).
159/// An empty string or array is the same as unset.
160#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
161#[serde(untagged)]
162pub enum AgentChoice {
163 /// One agent id.
164 One(String),
165 /// Ordered fallback chain of agent ids.
166 Chain(Vec<String>),
167}
168
169impl AgentChoice {
170 /// The ids named, in order, with blanks dropped. Empty means unset.
171 pub fn ids(&self) -> Vec<&str> {
172 let all: Vec<&str> = match self {
173 Self::One(id) => vec![id.as_str()],
174 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
175 };
176 all.into_iter()
177 .map(str::trim)
178 .filter(|id| !id.is_empty())
179 .collect()
180 }
181
182 /// The first id named, if any.
183 pub fn primary(&self) -> Option<&str> {
184 self.ids().into_iter().next()
185 }
186}
187
188impl From<&str> for AgentChoice {
189 fn from(id: &str) -> Self {
190 Self::One(id.to_owned())
191 }
192}
193
194/// The first id of an optional choice: what a single-seat caller resolves.
195pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
196 choice.and_then(AgentChoice::primary)
197}
198
199/// Explicit role assignment. Empty lists are filled in by
200/// [`Config::resolve_roles`] by rotating the roster.
201#[derive(Debug, Clone, Default, Deserialize, Serialize)]
202#[serde(deny_unknown_fields, default)]
203pub struct Roles {
204 /// Agents that implement the task, one worktree each.
205 pub implementers: Vec<String>,
206 /// Agents that rank the candidates blind.
207 pub judges: Vec<String>,
208 /// Agents that review the winning patch.
209 pub reviewers: Vec<String>,
210 /// Agent that applies review findings. Defaults to the winner's author.
211 pub fixer: Option<String>,
212 /// Agent that answers the standing chat's turns (`src/talk.rs`).
213 ///
214 /// Unset picks a `claude` seat, else the first runnable agent in roster
215 /// order (see [`crate::agent::pick`]) - which is roster *order*, not a
216 /// judgement about who converses well. Naming one here matters once an
217 /// agent is also sitting as a judge: the chat is opened far more often
218 /// than any single competition, and every open competes with that judge
219 /// seat for the same account's concurrency. A timeout on an ordinary chat
220 /// turn traced to exactly this - `opus` triple-booked as chatter and judge
221 /// - is what this field exists to let an operator break apart.
222 ///
223 /// Accepts one id or an ordered array of ids: a fallback chain, see
224 /// [`AgentChoice`].
225 pub chatter: Option<AgentChoice>,
226 /// Agent that arranges the queue between polls: `crate::conduct`'s single
227 /// seat, called once per cycle to decide a runnable task's `blocked_by`
228 /// and how a stalled or finished task recovers.
229 ///
230 /// The same precedent as [`Self::chatter`] for a seat that stands alone
231 /// rather than rotating through the roster - resolved through
232 /// [`crate::agent::pick`], so unset falls back to its own default order
233 /// (a claude seat, else the first runnable agent) rather than reusing a
234 /// judge or reviewer seat that the conductor's own poll-cycle cadence
235 /// would otherwise compete with for the same account's concurrency.
236 ///
237 /// Accepts a string or a fallback chain, like [`Self::chatter`].
238 pub conductor: Option<AgentChoice>,
239 /// Seats for the design-deliberation stage `graph::Runner::advise` runs
240 /// before `implement`: independent, read-only design proposals gathered
241 /// once a run has a settled task instruction and before any implementer
242 /// touches the repository.
243 ///
244 /// Empty falls back to `judges` rather than to the whole roster: a panel
245 /// trusted to rank patches independently is exactly the panel worth
246 /// asking to sketch a design independently, and an operator who has
247 /// already thought about judge diversity gets advisor diversity for free
248 /// instead of a fourth roster to maintain.
249 pub advisors: Vec<String>,
250 /// Agent that blends [`Self::advisors`]' proposals into the one design
251 /// brief `graph::Runner::synthesize_brief` carries into every
252 /// implementer's prompt.
253 ///
254 /// The same precedent as [`Self::chatter`] and [`Self::conductor`] for a
255 /// seat that stands alone rather than rotating through the roster -
256 /// resolved through [`crate::agent::pick`], so unset falls back to its
257 /// own default order (a claude seat, else the first runnable agent in
258 /// roster order) - exactly today's behavior, unchanged by leaving this
259 /// field out.
260 ///
261 /// Accepts a string or a fallback chain, like [`Self::chatter`].
262 pub synthesizer: Option<AgentChoice>,
263}
264
265/// Graph shape and limits.
266#[derive(Debug, Clone, Deserialize, Serialize)]
267#[serde(deny_unknown_fields, default)]
268pub struct Graph {
269 /// Parallel implementations of the same task. **One by default.**
270 ///
271 /// Competition is the thing magi is for, and it is still here - it is just
272 /// no longer what every task buys without being asked. Three days and 13
273 /// runs on this repository, which is the workload these numbers are drawn
274 /// from:
275 ///
276 /// - **0 of 13** competed runs reached a merge. Everything that landed in
277 /// that window went through `magi review` - the cheap half, no
278 /// competition - and passed on the first try.
279 /// - The judges' first choices **split 73% of the time** (8 of 11
280 /// tallies). Candidates that close together make the ranking a weak
281 /// signal for what it costs to produce.
282 /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
283 /// review 28min, **verify 5min** - and verify is the node that caught a
284 /// defect every reviewer had passed as clean. The cheapest step is the
285 /// one that earns its place every time.
286 ///
287 /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
288 /// single-seat default would have shipped the worse implementation in
289 /// roughly a quarter of them. That is exactly why this is a *default* and
290 /// not a removal - `magi run --candidates N` and a per-task seat count are
291 /// how a task that deserves a competition gets one.
292 ///
293 /// A single-candidate run needs no special case: `Runner::review`'s doc
294 /// records that `execute` already degrades to implement -> review -> gate
295 /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
296 /// no two first choices to reconcile and `vote` returns early.
297 pub candidates: usize,
298 /// Independent judges.
299 pub judges: usize,
300 /// Deliberation rounds when the judges' first choices disagree.
301 pub deliberate_rounds: usize,
302 /// Reviewers per review round. **Three by default** - the smallest panel
303 /// a lens cycle (see [`crate::prompt::Lens`]) covers exactly once, so the
304 /// default panel reads the patch for spec compliance, regressions, and
305 /// simplicity without repeating an angle. Review is also the one stage
306 /// [`Self::candidates`]'s doc describes as running on every task
307 /// regardless of competition, which is what makes a panel worth its cost
308 /// here even though `candidates` itself defaults to one.
309 pub reviewers: usize,
310 /// Maximum review+fix rounds before the run is declared blocked.
311 pub review_rounds: usize,
312 /// Fix rounds a failing `verify.gate` gets before the run is blocked. The
313 /// fixer is handed the gate's own output; `0` keeps the old behaviour of
314 /// blocking on the first red gate. Independent of [`Self::review_rounds`]
315 /// so a run that spent its review budget can still repair a one-line gate
316 /// failure.
317 pub gate_fix_rounds: usize,
318 /// Maximum agent processes running at once.
319 pub max_parallel: usize,
320 /// Language for the prose the agents write (`en` / `ja` / any language name).
321 pub language: String,
322 /// Keep one CLI conversation per seat, so a judge remembers its own
323 /// argument across deliberation rounds and the fixer remembers its own
324 /// implementation across review rounds.
325 ///
326 /// Sessions are scoped to a *seat*, never to an agent id: the same model
327 /// sitting as implementer and as judge gets two unrelated conversations,
328 /// which is what keeps blind judging blind.
329 pub sessions: bool,
330 /// Per-node timeouts, seconds.
331 pub timeout_implement: u64,
332 /// Per-node timeouts, seconds.
333 pub timeout_judge: u64,
334 /// Per-node timeouts, seconds.
335 pub timeout_review: u64,
336 /// Timeout for `verify.e2e` and `verify.gate`, seconds. Separate from
337 /// [`Self::timeout_review`] so shrinking a reviewer's budget cannot
338 /// silently shrink a real-machine command's budget too — the two used to
339 /// share `timeout_review`, and turning a slow reviewer down cut the
340 /// timeout `cargo test --all-targets` runs under along with it. When
341 /// omitted, preserves legacy configurations by using
342 /// [`Self::timeout_review`]. Set an explicit value to make verification
343 /// independent of later review-seat budget changes.
344 pub timeout_verify: Option<u64>,
345 /// Per-node timeouts, seconds.
346 pub timeout_fix: u64,
347 /// Wall-clock limit for one turn of [`crate::talk`]'s standing
348 /// conversation, seconds.
349 ///
350 /// An hour: the operator is not watching this turn resolve in real time,
351 /// so the budget can match what the work - reading files, running
352 /// commands, checking their output - actually needs rather than what a
353 /// person waiting on a phone can tolerate.
354 pub timeout_talk: u64,
355 /// Retries for an agent invocation that fails or returns nothing usable.
356 pub retries: usize,
357 /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
358 pub worktree_root: Option<PathBuf>,
359 /// After the pull request is open, keep going: watch its checks and
360 /// reviews, run a fix round when they are unhappy, and ask to merge.
361 ///
362 /// On, because stopping at an open pull request left the operator doing
363 /// the watching by hand - six times in the session this was built in - and
364 /// that is the work the loop exists to take. It only engages for
365 /// `merge = "pr"`; every other merge mode ends the run as before.
366 ///
367 /// Turning this on does **not** hand magi the merge button:
368 /// [`Graph::land_approval`] is on too, and nothing merges without an
369 /// explicit answer. Setting both to their non-defaults is the only way to
370 /// get an unattended merge, and it has to be chosen twice.
371 pub land: bool,
372 /// Land rounds - watch, fix, push - before the run is left for a human.
373 pub land_rounds: usize,
374 /// Ask the owner before merging, showing what is about to land.
375 ///
376 /// On, and it is what makes `land` safe to have on: the question carries a
377 /// rendered panel - the diffstat, the patch, the checks, the review
378 /// comments that were addressed, and the subject the squash will use - so
379 /// the decision is made on evidence rather than on trust, from wherever
380 /// the operator happens to be.
381 ///
382 /// Silence is a hold. An unanswered approval never merges, and neither
383 /// does any answer other than the word `merge`.
384 pub land_approval: bool,
385 /// Ask the owner before merging a run whose review loop handed off over a
386 /// contested finding: the last round ended with a Major-or-above finding
387 /// still open *and* at least one reviewer's final vote (after
388 /// reconsideration) was reject. Findings raised in the last round are
389 /// never fixed or re-reviewed, so this is the one case an unattended
390 /// merge would land over a reviewer's explicit objection.
391 ///
392 /// On. Interaction with [`Self::land_approval`]: when that is on, every
393 /// merge is asked about and this key changes nothing. When it is off,
394 /// this key alone decides whether a contested hand-off is asked about
395 /// (the question says why); every other run still merges unattended.
396 /// Read at land time, so turning it off restores the unattended merge at
397 /// once. The pull request is opened either way; only the merge waits.
398 pub hold_contested_merge: bool,
399 /// After a run's pull request merges, file the findings its last review
400 /// round left open as follow-up tasks (`crate::followup`) instead of
401 /// letting them vanish with the merge: every Major-or-above finding, and
402 /// every finding of a seat whose final vote was reject. Other Minor/Nit
403 /// findings are only listed in the pull-request comment. Does not affect
404 /// whether the merge happens. On; best-effort, a failure is a run event.
405 pub file_followups: bool,
406 /// How long to wait for an owner to answer a question before the run is
407 /// abandoned, seconds. A parked run costs nothing, so this is generous;
408 /// it exists so a forgotten question cannot pin a worktree forever.
409 pub answer_timeout: u64,
410 /// What a round does when one or more reviewer seats never answered
411 /// (timeout, crash, unparsable output).
412 pub incomplete_review: IncompleteReviewPolicy,
413 /// Run `verify.e2e` on every round, even one that already has blocking
414 /// findings and another round left to try.
415 ///
416 /// Off by default: a round with a blocking finding and rounds still left
417 /// is going back to the fixer regardless of what `verify.e2e` says, so
418 /// running it first only spends the round's slowest step (minutes, on a
419 /// Rust repo's `cargo test --all-targets`) on a head about to be
420 /// rewritten anyway. `verify.e2e` still runs once a round has no
421 /// blocking findings left (a round cannot go `clean` without it) and the
422 /// final `verify.gate` always runs on the actual tree that would land —
423 /// deferring is about *when* e2e runs mid-loop, never about skipping it.
424 ///
425 /// Set this to restore the old every-round diagnostic behaviour: e2e
426 /// output from a round that still has blocking findings is occasionally
427 /// useful on its own (a runtime failure a reviewer's panel would not
428 /// have caught by reading), and this is the way back to seeing it every
429 /// round instead of only once the panel has nothing left to flag.
430 pub e2e_every_round: bool,
431 /// Run the design-deliberation stage before `implement`: independent
432 /// advisor seats each sketch a design, and (when at least one produced a
433 /// usable proposal) a synthesis blends them into a brief carried in the
434 /// implementer's prompt. See `graph::Runner::advise`.
435 ///
436 /// On by default. A design sketch is a few paragraphs an agent can write
437 /// without touching the repository, where a full implementation is a
438 /// tool loop that re-reads the codebase on every turn - so three
439 /// sketches, gathered once before `implement` starts, cost a fraction of
440 /// a fourth candidate and buy back a form of the same disagreement
441 /// [`Self::candidates`]'s doc describes moving away from being the
442 /// default, on every run rather than only the ones an operator remembers
443 /// to ask for with `--candidates`.
444 pub advise: bool,
445 /// How many independent design proposals the deliberation stage gathers.
446 /// **Three by default** - the same number [`Self::candidates`]'s doc
447 /// names as the point where a fourth judge's first choice stopped
448 /// changing the tally.
449 pub advisors: usize,
450}
451
452impl Default for Graph {
453 fn default() -> Self {
454 Self {
455 candidates: 1,
456 judges: 3,
457 deliberate_rounds: 1,
458 reviewers: 3,
459 review_rounds: 6,
460 gate_fix_rounds: 1,
461 max_parallel: 4,
462 language: "en".to_owned(),
463 sessions: true,
464 timeout_implement: 3600,
465 timeout_judge: 1200,
466 timeout_review: 1200,
467 timeout_verify: None,
468 timeout_fix: 1800,
469 timeout_talk: 3600,
470 retries: 1,
471 worktree_root: None,
472 land: true,
473 land_rounds: 4,
474 land_approval: true,
475 hold_contested_merge: true,
476 file_followups: true,
477 answer_timeout: 86_400,
478 incomplete_review: IncompleteReviewPolicy::Block,
479 e2e_every_round: false,
480 advise: true,
481 advisors: 3,
482 }
483 }
484}
485
486impl Graph {
487 /// Effective machine-command budget. Older configuration files had only
488 /// `timeout_review`, which also governed verification, so absence is a
489 /// compatibility fallback rather than a new 1200-second default.
490 pub fn verify_timeout(&self) -> u64 {
491 self.timeout_verify.unwrap_or(self.timeout_review)
492 }
493}
494
495/// What a review round does when a reviewer seat never answered.
496///
497/// A round where half the panel timed out is not evidence of a clean patch —
498/// it is evidence of nothing. The default refuses to call that clean; `warn`
499/// exists for an operator who would rather keep a flaky seat from stalling
500/// every run, and accepts that the gap is on them to read in the report.
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
502#[serde(rename_all = "lowercase")]
503pub enum IncompleteReviewPolicy {
504 /// A round with a missing seat is never `clean`: with nothing raised to
505 /// fix, the round is re-reviewed instead of gating; with the max rounds
506 /// exhausted, the run is left `Blocked` rather than declared ready.
507 Block,
508 /// A round with a missing seat can still gate as clean, once every seat
509 /// that *did* answer raised nothing blocking and verification is green.
510 /// The record keeps the gap visible (`magi show`, `magi stats`) even
511 /// though the run does not wait on it.
512 Warn,
513}
514
515/// What to do when vendor-identifying text is found in material shown to judges.
516#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
517#[serde(rename_all = "lowercase")]
518pub enum LeakPolicy {
519 /// Record the leak, show the patch unmodified.
520 Warn,
521 /// Replace the token with `[REDACTED]` in the presented patch.
522 Redact,
523 /// Abort the run.
524 Fail,
525}
526
527/// Blindness policy.
528///
529/// Commit messages and candidate summaries are *always* stripped of
530/// attribution trailers and redacted — that is where signatures actually
531/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
532/// redaction would corrupt the artifact under judgement.
533#[derive(Debug, Clone, Deserialize, Serialize)]
534#[serde(deny_unknown_fields, default)]
535pub struct Blind {
536 /// Install a per-worktree `commit-msg` hook that deletes attribution
537 /// trailers before they can land in a candidate's history.
538 pub commit_msg_hook: bool,
539 /// Literal, case-insensitive substrings. A line containing any of them is
540 /// dropped from commit messages and summaries; the `commit-msg` hook is
541 /// generated from the same list.
542 pub strip_lines: Vec<String>,
543 /// Case-insensitive substrings that identify a vendor or model.
544 pub vendor_tokens: Vec<String>,
545 /// Policy for vendor tokens found in the patch body.
546 pub on_leak: LeakPolicy,
547 /// Seed for label assignment and per-judge presentation order. Derived from
548 /// the run id when unset; set it to make a run reproducible.
549 pub seed: Option<u64>,
550}
551
552impl Default for Blind {
553 fn default() -> Self {
554 Self {
555 commit_msg_hook: true,
556 strip_lines: [
557 "Co-Authored-By:",
558 "Signed-off-by:",
559 "Assisted-by:",
560 "Generated-by:",
561 "Generated with",
562 "\u{1f916}",
563 ]
564 .iter()
565 .map(|s| (*s).to_owned())
566 .collect(),
567 vendor_tokens: [
568 "claude",
569 "anthropic",
570 "codex",
571 "openai",
572 "chatgpt",
573 "gemini",
574 "grok",
575 "xai",
576 "copilot",
577 "opencode",
578 "qoder",
579 "cursor",
580 "\u{1f916}",
581 ]
582 .iter()
583 .map(|s| (*s).to_owned())
584 .collect(),
585 on_leak: LeakPolicy::Warn,
586 seed: None,
587 }
588 }
589}
590
591/// Shell commands that gate the winner.
592#[derive(Debug, Clone, Default, Deserialize, Serialize)]
593#[serde(deny_unknown_fields, default)]
594pub struct Verify {
595 /// Run in the winner's worktree once per review round. Its output is fed
596 /// back to the fixer. This is the "real machine" leg of the review.
597 pub e2e: Vec<String>,
598 /// Final gate. Must all exit 0 before a merge is attempted.
599 pub gate: Vec<String>,
600 /// Mechanical fixers (formatters) run in the winner's worktree just before
601 /// `gate`, after review is clean. Anything they change is committed as one
602 /// neutral-identity commit so the gate and the PR see it. A command that
603 /// fails or times out is a warning, never a failed run: the gate stays the
604 /// single arbiter. Empty (the default) turns the feature off. Runs under
605 /// `graph.verify_timeout()` per command, like the gate. Meant for light
606 /// tools: it is not scanned for `CARGO_TARGET_DIR`, and it should be
607 /// idempotent since a resumed run may repeat it.
608 #[serde(default)]
609 pub pre_gate: Vec<String>,
610 /// Shell used to run the commands above. Defaults to `sh -c`, or
611 /// `cmd /C` when `sh` is not on `PATH`.
612 pub shell: Option<Vec<String>>,
613}
614
615impl Verify {
616 /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
617 /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
618 /// this reads back. One rendering is enough - they all set the same
619 /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
620 /// command is checked before the gate because the e2e rebuilds the crate.
621 pub fn cache_dir(&self) -> Option<PathBuf> {
622 self.e2e
623 .iter()
624 .chain(self.gate.iter())
625 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
626 }
627}
628
629/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
630///
631/// The numbers below come from one incident, not from theory: a machine with
632/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
633/// Three multi-gigabyte classes of junk accumulated side by side - per-run
634/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
635/// each verify round and each implementation wave recompiles the derived
636/// section of the project into, and the outputs of runs that were removed but
637/// whose folders nobody deleted.
638#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
639#[serde(deny_unknown_fields, default)]
640pub struct Disk {
641 /// Free space, in bytes, below which no new run may start: the daemon and
642 /// the `magi run` gate answer with "the disk is full" instead of letting
643 /// the graph fill it the rest of the way. `0` turns the gate off.
644 ///
645 /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
646 /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
647 /// competition triggers and small enough that a 1 TB disk with 100 GB free
648 /// is nowhere near the threshold.
649 pub min_free_bytes: u64,
650 /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
651 /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
652 /// worktrees removed. `0` turns the janitor off.
653 ///
654 /// Default true.
655 pub auto_fold: bool,
656 /// How old a finished run must be before the janitor folds it, seconds.
657 ///
658 /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
659 /// run that `Ready` a week ago is worktrees holding a compile each. Six
660 /// hours is long enough that nobody loses an answer in the gap between
661 /// reading the report and starting from it, and short enough that a backlog
662 /// cannot pile up across two nights.
663 pub fold_grace_secs: u64,
664 /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
665 /// verify commands), in bytes. When the janitor runs and the cache is over
666 /// it, files are dropped oldest-first until it is not. `0` turns pruning
667 /// off - the cache then only ever grows, which is the operator's call.
668 ///
669 /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
670 /// shared cache on top of ~16 GB in the primary target directory and 6.7-
671 /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
672 /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
673 /// pruning only costs the rebuild of the dropped files, not of the world)
674 /// without letting one addled cache swallow the machine.
675 pub cache_limit_bytes: u64,
676}
677
678impl Default for Disk {
679 fn default() -> Self {
680 Self {
681 min_free_bytes: 8 * 1024 * 1024 * 1024,
682 auto_fold: true,
683 fold_grace_secs: 6 * 60 * 60,
684 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
685 }
686 }
687}
688
689/// What to do with the winning branch.
690#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
691#[serde(rename_all = "lowercase")]
692pub enum MergeMode {
693 /// Leave the branch alone and print the merge command matching
694 /// [`Merge::style`].
695 None,
696 /// Merge into the base branch in the primary worktree, using
697 /// [`Merge::style`].
698 Local,
699 /// Push the branch and open a PR with `gh pr create`. Landing this PR
700 /// (`[graph] land`) always squashes — see `land`'s module doc — so
701 /// [`Merge::style`] does not apply here.
702 Pr,
703}
704
705/// How the winning branch is attached to the base branch: what
706/// `mode = "local"` runs, and what `mode = "none"`'s printed guidance tells
707/// the operator to run by hand.
708///
709/// Read from configuration rather than asked of the repository at run time
710/// (e.g. `gh api repos/{owner}/{repo}/rulesets`) for two reasons: it keeps
711/// `mode = "none"`'s guidance a pure function of `RunState`, assertable in a
712/// unit test the same way `land::decide` is kept pure (see that module's
713/// doc), and it works for a base branch that is not hosted on GitHub, or not
714/// reachable at all, at the moment the report is rendered. An operator whose
715/// base branch enforces a ruleset already knows what it allows; declaring it
716/// once here is cheaper than magi re-discovering it, with a network call, on
717/// every render.
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
719#[serde(rename_all = "lowercase")]
720pub enum MergeStyle {
721 /// `git merge --no-ff`: every candidate commit lands, plus a merge
722 /// commit that records the merge as its own event in history. Rejected
723 /// by a base branch whose ruleset requires linear history or forbids
724 /// merge commits outright.
725 #[default]
726 Merge,
727 /// `git merge --squash` followed by a commit under an explicit message:
728 /// every candidate commit folds into one, and none of the candidate's
729 /// own placeholder subjects (`magi: candidate A (uncommitted work)`)
730 /// reach the base branch. No merge commit, so this satisfies a linear-
731 /// history ruleset.
732 Squash,
733 /// A fast-forward-only merge: every candidate commit lands verbatim, in
734 /// order, with no merge commit. Only succeeds because the winner was
735 /// already rebased onto the tracked base tip before this runs (see
736 /// `Runner::sync_to_base`) — equivalent to GitHub's "rebase and merge"
737 /// once that has happened.
738 Rebase,
739}
740
741/// Merge policy.
742#[derive(Debug, Clone, Deserialize, Serialize)]
743#[serde(deny_unknown_fields, default)]
744pub struct Merge {
745 /// Default is [`MergeMode::None`]: magi never touches your base branch
746 /// unless you ask it to.
747 pub mode: MergeMode,
748 /// Base branch. Defaults to the branch checked out when the run started.
749 pub base: Option<String>,
750 /// How the winner is attached to `base`; see [`MergeStyle`]. Ignored by
751 /// `mode = "pr"`.
752 pub style: MergeStyle,
753 /// Remote for `mode = "pr"`.
754 pub remote: String,
755 /// After a `mode = "pr"` run lands, open a `chore/release-vX.Y.Z` pull
756 /// request sized to the change by an agent's own judgement, so a version
757 /// bump does not depend on a human remembering to cut one.
758 ///
759 /// Only acts on Rust repositories (a `Cargo.toml` at the root of the base
760 /// branch); on any other repository it is a no-op that records one event.
761 ///
762 /// On by default. **Turning this off means a merge landed from the phone
763 /// never becomes a release**, so `POST /api/upgrade` keeps reporting
764 /// "already on the newest release" against a `main` that has moved past
765 /// it - the same gap this feature exists to close. Only for a repository
766 /// that wants to keep cutting releases by hand.
767 pub release_bump: bool,
768}
769
770impl Default for Merge {
771 fn default() -> Self {
772 Self {
773 mode: MergeMode::None,
774 base: None,
775 style: MergeStyle::default(),
776 remote: "origin".to_owned(),
777 release_bump: true,
778 }
779 }
780}
781
782/// How magi keeps itself current.
783#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
784#[serde(rename_all = "lowercase")]
785pub enum UpdateMode {
786 /// Never check.
787 Off,
788 /// Check in the background and print a one-line banner when a newer
789 /// release exists.
790 Notify,
791 /// Check and install silently.
792 Install,
793}
794
795/// Self-update policy.
796#[derive(Debug, Clone, Deserialize, Serialize)]
797#[serde(deny_unknown_fields, default)]
798pub struct Update {
799 /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
800 pub mode: UpdateMode,
801 /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
802 pub interval: Option<String>,
803}
804
805impl Default for Update {
806 fn default() -> Self {
807 Self {
808 mode: UpdateMode::Notify,
809 interval: None,
810 }
811 }
812}
813
814/// Who performs the release after a `chore/release-vX.Y.Z` pull request merges.
815#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
816#[serde(rename_all = "lowercase")]
817pub enum ReleaseMode {
818 /// The repository's own workflows do (`auto-tag.yml` then `release.yml`),
819 /// and the release pull request merges on its checks.
820 #[default]
821 Actions,
822 /// magi does, from this machine: no CI is awaited, the owner approves the
823 /// merge, and magi then tags and runs [`Release::commands`]. See
824 /// [`crate::release_local`].
825 Local,
826}
827
828/// `[release]`: releasing without GitHub Actions. Opt-in per repository.
829#[derive(Debug, Clone, Deserialize, Serialize)]
830#[serde(deny_unknown_fields, default)]
831pub struct Release {
832 /// [`ReleaseMode::Actions`] (default: nothing changes) or
833 /// [`ReleaseMode::Local`].
834 pub mode: ReleaseMode,
835 /// Shell commands run in order, from a clean checkout of the merge commit,
836 /// once the tag is pushed. The first failure stops the list. They see
837 /// `MAGI_RELEASE_VERSION`, `MAGI_RELEASE_TAG`, `MAGI_RELEASE_COMMIT` and
838 /// `MAGI_RELEASE_PR` in the environment; `{{ ... }}` cannot carry the
839 /// version because teravars renders the whole file before any release
840 /// exists. Only read when `mode = "local"`.
841 pub commands: Vec<String>,
842 /// Minutes each command may run before it is killed and counted as failed.
843 pub timeout_minutes: u64,
844}
845
846impl Default for Release {
847 fn default() -> Self {
848 Self {
849 mode: ReleaseMode::Actions,
850 commands: Vec::new(),
851 timeout_minutes: 30,
852 }
853 }
854}
855
856impl Release {
857 /// Is this repository released by magi rather than by its workflows?
858 pub fn is_local(&self) -> bool {
859 self.mode == ReleaseMode::Local
860 }
861}
862
863/// Top-level configuration.
864#[derive(Debug, Clone, Default, Deserialize, Serialize)]
865#[serde(deny_unknown_fields, default)]
866pub struct Config {
867 /// Agent roster.
868 pub agents: Vec<AgentSpec>,
869 /// Role assignment.
870 pub roles: Roles,
871 /// Graph shape.
872 pub graph: Graph,
873 /// Blindness policy.
874 pub blind: Blind,
875 /// Verification commands.
876 pub verify: Verify,
877 /// Disk hygiene.
878 pub disk: Disk,
879 /// Merge policy.
880 pub merge: Merge,
881 /// Self-update policy.
882 pub update: Update,
883 /// Project-specific text appended to the node prompts.
884 pub prompts: Prompts,
885 /// How the operator is told a run is waiting on them.
886 pub notify: Notify,
887 /// Local repositories the plan surface can start or derive a conversation
888 /// against.
889 pub repos: Repos,
890 /// Policy for the standing conversation ([`crate::talk`]).
891 pub talk: Talk,
892 /// How many runs `magi serve`'s own loop drives at once.
893 pub daemon: Daemon,
894 /// Who tags and publishes after a release pull request merges.
895 pub release: Release,
896 /// Context-window sizes in tokens, keyed by model name, merged over
897 /// [`BUILTIN_CONTEXT_WINDOWS`]. See [`Config::context_window`].
898 pub context_windows: BTreeMap<String, u64>,
899}
900
901/// Context windows of models magi commonly drives, in tokens.
902///
903/// A convenience, not a source of truth: vendors resize windows and ship new
904/// models faster than this table is edited, so an entry that is stale or
905/// missing is fixed by `[context_windows]` in `magi.toml`, which wins. Matched
906/// by [`Config::context_window`]: exact name first, then the longest key that
907/// prefixes the model name (so a dated or suffixed id such as
908/// `claude-sonnet-4-5-20250929` finds `claude-sonnet-4-5`). A model matching
909/// nothing has no percentage - the UI shows the raw count.
910const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
911 ("claude-opus-4", 200_000),
912 ("claude-sonnet-4", 200_000),
913 ("claude-haiku-4", 200_000),
914 ("claude-3", 200_000),
915 ("opus", 200_000),
916 ("sonnet", 200_000),
917 ("haiku", 200_000),
918 ("gpt-5", 400_000),
919 ("gpt-4.1", 1_000_000),
920 ("gpt-4o", 128_000),
921 ("o3", 200_000),
922 ("o4-mini", 200_000),
923 ("gemini-2.5", 1_000_000),
924 ("deepseek", 128_000),
925];
926
927impl Config {
928 /// Context window in tokens for `model`: `[context_windows]` first, then
929 /// the built-in table; within each, an exact name beats the longest
930 /// prefix. `None` for an unknown model, which is a deliberate answer -
931 /// guessing a denominator would print a confident wrong percentage.
932 pub fn context_window(&self, model: &str) -> Option<u64> {
933 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
934 let mut best: Option<(usize, u64)> = None;
935 for (key, window) in entries {
936 if key == model {
937 return Some(window);
938 }
939 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
940 best = Some((key.len(), window));
941 }
942 }
943 best.map(|(_, w)| w)
944 }
945 lookup(
946 model,
947 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
948 )
949 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
950 }
951}
952
953/// How the daemon loop itself behaves, as opposed to what one run does.
954///
955/// Machine-layer material in the same sense [`Repos::roots`] is: how many
956/// competitions this machine's own loop is willing to babysit at once is a
957/// fact about the machine running `magi serve`, not about any one
958/// repository's task, so it belongs in `<config_dir>/magi/config.toml`
959/// rather than a repository's own `magi.toml` - though, like `Repos::roots`,
960/// nothing stops a repository from setting it too, since a scalar field
961/// takes whichever layer has the highest precedence.
962#[derive(Debug, Clone, Deserialize, Serialize)]
963#[serde(deny_unknown_fields, default)]
964pub struct Daemon {
965 /// How many runs `magi serve` may have actively in flight at once.
966 /// **One by default** - today's behaviour, one run at a time.
967 ///
968 /// This is a different knob from [`Graph::max_parallel`], and the two
969 /// must not be confused: `max_parallel` bounds how many agent *processes*
970 /// one run starts inside itself (implementers, judges, reviewers -
971 /// candidates competing on a single task); this field bounds how many
972 /// *runs* - whole competitions, each with its own `max_parallel` budget -
973 /// the loop drives side by side, possibly across different tasks and
974 /// different repositories. Raising `max_parallel` buys a bigger panel for
975 /// one task; raising this buys more tasks worked at once. A config file
976 /// that meant one and wrote the other would either starve a competition
977 /// of judges or leave the rest of the backlog waiting for no reason.
978 ///
979 /// A run parked waiting on the operator's land-merge approval - see
980 /// [`crate::land`] - does not hold one of these slots while it waits: the
981 /// whole point of parking there is to let the loop spend the slot on
982 /// something runnable instead of sitting on a decision only a human can
983 /// make. So even at the default of `1`, an approval that comes back does
984 /// not queue behind whatever else the loop happens to be running.
985 pub max_concurrent_runs: usize,
986 /// Let a task marked [`crate::queue::Task::interrupt`] (`magi task
987 /// interrupt`) cut ahead of whatever `magi serve` already has in flight,
988 /// instead of waiting for it to finish.
989 ///
990 /// **Off by default.** When enabled, a run that is in flight and is not
991 /// itself the interrupt candidate may be paused at its next safe node
992 /// boundary - see [`crate::graph::Runner::park_here`] - so the marked
993 /// task can run alone; the paused run resumes automatically, through the
994 /// same path any other parked run does, the moment the interrupting
995 /// task's own run reaches a terminal status. This is opt-in because it
996 /// bends the loop's own "one run at a time" principle (see this repository's
997 /// `magi serve` help) for a specific, explicit operator request, and a
998 /// repository that never files an interrupt task pays nothing for having
999 /// it on - but an operator who does not want any run of theirs preempted,
1000 /// ever, should leave this `false`.
1001 pub pause_for_interrupts: bool,
1002 /// How many deputies `magi serve` runs at once. A deputy is the short-lived
1003 /// seat that waits on one open conductor question (see [`crate::deputy`]);
1004 /// each is a live agent conversation, so this is bounded - **two by
1005 /// default**, because the agent CLIs' quota is the scarce resource. A
1006 /// question over the limit keeps its place and starts when a deputy
1007 /// finishes; `0` runs none.
1008 pub max_deputies: usize,
1009 /// Minutes a release-bump pull request may make no progress before
1010 /// `magi serve` raises a notice and asks the owner (see
1011 /// [`crate::release_watch`]). Progress is a change of head commit or of any
1012 /// check's verdict. A required check that stays red after the one rerun the
1013 /// watcher is allowed escalates at once, whatever this says. **Sixty by
1014 /// default**; `0` turns the watcher off.
1015 pub release_stall_minutes: u64,
1016}
1017
1018impl Default for Daemon {
1019 fn default() -> Self {
1020 Self {
1021 max_concurrent_runs: 1,
1022 pause_for_interrupts: false,
1023 max_deputies: 2,
1024 release_stall_minutes: 60,
1025 }
1026 }
1027}
1028
1029/// Where `magi repos` and `GET /api/repos` look for local checkouts.
1030///
1031/// `roots` is one of the array keys [`array_merge_policy`] marks as
1032/// append-across-layers: which checkouts exist in general is a *machine*
1033/// fact in the same way the agent roster is - a repository's own `magi.toml`
1034/// cannot state where its siblings live before magi has resolved which
1035/// repository to read that file from in the first place - but a repository
1036/// that genuinely has an extra root worth scanning is not forced to choose
1037/// between an error and losing the machine's roots outright. Both layers'
1038/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
1039/// are still refused.
1040#[derive(Debug, Clone, Deserialize, Serialize)]
1041#[serde(deny_unknown_fields, default)]
1042pub struct Repos {
1043 /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
1044 /// with a `.git` directory. Empty by default - nothing is scanned unless
1045 /// asked to be.
1046 pub roots: Vec<PathBuf>,
1047 /// How long a scan is trusted before the next request re-scans it,
1048 /// seconds. `0` means never trust it: scan on every request. Defaults to
1049 /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
1050 /// the same reason - a checkout does not usually appear or vanish inside
1051 /// a session, so there is little to gain from scanning more often than
1052 /// that, and an explicit refresh exists for the moment one does.
1053 pub scan_ttl: u64,
1054 /// How often `magi serve` runs `git fetch origin` in every checkout under
1055 /// `roots`, seconds, so `origin/main` stays fresh whatever state the
1056 /// working tree is in. Fetch only: no branch, HEAD or working tree is
1057 /// touched. `0` disables it.
1058 pub fetch_interval: u64,
1059}
1060
1061impl Default for Repos {
1062 fn default() -> Self {
1063 Self {
1064 roots: Vec::new(),
1065 scan_ttl: 86_400,
1066 fetch_interval: 600,
1067 }
1068 }
1069}
1070
1071/// Project-specific text appended to each node's prompt.
1072///
1073/// **Additive by construction.** These fields cannot replace magi's prompts,
1074/// only extend them, and that restriction is the whole design. The built-in
1075/// prompts carry the invariants the competition rests on: a judging prompt
1076/// names no authors, every structured answer must arrive as one fenced `json`
1077/// block, and a judge is told not to speculate about who wrote what. A config
1078/// that could overwrite them would let a typo silently un-blind the panel or
1079/// break the parser, and the symptom would be "the judges got worse" rather
1080/// than an error.
1081///
1082/// Repository-wide context belongs in `AGENTS.md`, which every agent already
1083/// reads from the checkout. Use these fields for the things a *magi node*
1084/// needs to know and a repository file cannot say - for instance that
1085/// reviewers here should ignore formatting because a hook owns it.
1086#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1087#[serde(deny_unknown_fields, default)]
1088pub struct Prompts {
1089 /// Appended to every node's prompt.
1090 pub all: String,
1091 /// Appended for implementers.
1092 pub implement: String,
1093 /// Appended for judges, both ranking and voting.
1094 pub judge: String,
1095 /// Appended for reviewers.
1096 pub review: String,
1097 /// Appended for the fixer.
1098 pub fix: String,
1099}
1100
1101impl Prompts {
1102 /// The overlay for one node, or `None` when nothing is configured.
1103 ///
1104 /// `node` is the graph's own node name, so a new node gets no overlay
1105 /// rather than the wrong one.
1106 pub fn overlay(&self, node: &str) -> Option<String> {
1107 let specific = match node {
1108 "implement" => &self.implement,
1109 "judge" | "vote" | "deliberate" => &self.judge,
1110 "review" => &self.review,
1111 "fix" => &self.fix,
1112 _ => "",
1113 };
1114 let mut parts: Vec<&str> = Vec::new();
1115 for p in [self.all.trim(), specific.trim()] {
1116 if !p.is_empty() {
1117 parts.push(p);
1118 }
1119 }
1120 if parts.is_empty() {
1121 return None;
1122 }
1123 Some(parts.join("\n\n"))
1124 }
1125}
1126
1127/// How the operator is told that a run is waiting on them.
1128///
1129/// A command rather than a built-in integration: magi is one binary with no
1130/// network dependencies, and every operator's notification path is different -
1131/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
1132/// Shelling out keeps all of them possible and none of them magi's problem.
1133#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1134#[serde(deny_unknown_fields, default)]
1135pub struct Notify {
1136 /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
1137 /// Empty means no notification - the web UI is then the only surface.
1138 pub command: Vec<String>,
1139}
1140
1141/// Policy for [`crate::talk`], the standing conversation.
1142#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1143#[serde(deny_unknown_fields, default)]
1144pub struct Talk {
1145 /// Let the conversation's agent edit files in the repository instead of
1146 /// filing a task for one. **Off by default** - see
1147 /// [`crate::talk`]'s module doc for why an edit made mid-conversation is
1148 /// an edit no run and no review can be attributed to, which is exactly
1149 /// the property a repository entered in a competition depends on. A
1150 /// repository that is never judged - dotfiles, a personal config
1151 /// checkout - has nothing to lose by turning this on in its own
1152 /// `magi.toml`, and a one-line fix stops costing a queued task to get.
1153 pub allow_write: bool,
1154}
1155
1156/// Roles resolved to concrete agent specs for one run.
1157#[derive(Debug, Clone)]
1158pub struct ResolvedRoles {
1159 /// One per candidate.
1160 pub implementers: Vec<AgentSpec>,
1161 /// One per judge.
1162 pub judges: Vec<AgentSpec>,
1163 /// One per reviewer slot.
1164 pub reviewers: Vec<AgentSpec>,
1165 /// Explicit fixer, if configured.
1166 pub fixer: Option<AgentSpec>,
1167 /// Queue conductor, explicitly selected or resolved by the standalone-seat fallback.
1168 pub conductor: AgentSpec,
1169 /// The full ordered implementer roster, in [`Roles::implementers`]'s own
1170 /// order — or `[[agents]]` in file order, when that list is empty. Unlike
1171 /// [`Self::implementers`], never truncated to `graph.candidates` and
1172 /// never `rotate`d/wrapped: a solo run (`candidates = 1`) resolves
1173 /// `implementers` down to a single slot, but `graph::Runner`'s per-seat
1174 /// quota fallback needs the *whole* list to walk forward through when
1175 /// that one slot's agent runs out of quota mid-run.
1176 pub implementer_roster: Vec<AgentSpec>,
1177 /// [`Self::implementer_roster`]'s counterpart for judge seats: the whole
1178 /// `[roles] judges` list (or every agent), untruncated and unrotated, for
1179 /// the per-seat handover when a judge's agent fails.
1180 pub judge_roster: Vec<AgentSpec>,
1181 /// Likewise for reviewer seats.
1182 pub reviewer_roster: Vec<AgentSpec>,
1183}
1184
1185/// Every array-valued key in a config table, as a dotted path.
1186///
1187/// Dotted so the error names `roles.implementers` rather than `implementers`:
1188/// an operator with three config files needs to know which key, not just that
1189/// there was one. `vars` is skipped because it is teravars' own input, merged
1190/// on purpose and never deserialised into `Config`.
1191fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1192 let mut out = Vec::new();
1193 for (k, v) in table {
1194 if prefix.is_empty() && k == "vars" {
1195 continue;
1196 }
1197 let path = if prefix.is_empty() {
1198 k.clone()
1199 } else {
1200 format!("{prefix}.{k}")
1201 };
1202 match v {
1203 toml::Value::Array(_) => out.push(path),
1204 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1205 _ => {}
1206 }
1207 }
1208 out
1209}
1210
1211/// How an array key behaves when two config layers both declare it.
1212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1213enum ArrayMerge {
1214 /// Two layers may both declare it; the composed value is the
1215 /// low-to-high-priority concatenation teravars already produces (see
1216 /// [`Config::load_layers`]'s doc for why that order and no dedup).
1217 Append,
1218 /// Two layers declaring it is refused; see
1219 /// [`Config::refuse_split_arrays`].
1220 Replace,
1221}
1222
1223/// The single place that decides, for a dotted array key (as returned by
1224/// [`array_keys`]), whether declaring it in two config layers is a
1225/// concatenation the operator asked for or a silent accident.
1226///
1227/// Kept as one match so the whole policy is visible in one place - the same
1228/// reason `claude_quota` and `dropped_stream` close their own classification
1229/// in one spot elsewhere in this codebase. Anything not listed defaults to
1230/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
1231/// reasoned about yet, and a new array key added later has to be added here
1232/// deliberately to become appendable.
1233///
1234/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
1235/// gate. Concatenating two of them is exactly the checks both layers
1236/// wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
1237/// live in a shared layer while a repository's own layer adds its own
1238/// command, instead of every repository copying the shared command into
1239/// its own file.
1240/// - `repos.roots` — a set of directories to scan for checkouts. A
1241/// repository adding its own root on top of the machine's is additive by
1242/// nature, not a replacement of where the machine looks; see
1243/// [`Repos::roots`].
1244///
1245/// Left on the refuse side, and why:
1246/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
1247/// list of *seats*, not a set. A machine's two implementers plus a
1248/// repository's one is three seats nobody asked for and nobody is paying
1249/// for on purpose.
1250/// - `notify.command` — an argv. Concatenating two argvs does not produce a
1251/// program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
1252/// - `blind.strip_lines` — technically safe to concatenate (each entry is
1253/// matched as an independent substring, so a longer list only strips
1254/// *more*), but left on the refuse side anyway: the same list also drives
1255/// `commit_msg_hook`'s generated `sed` addresses, where position matters,
1256/// and a silent three-layer merge is exactly the kind of surprise
1257/// `refuse_split_arrays` exists to catch rather than to reason about
1258/// case-by-case. A repository that wants one more stripped phrase restates
1259/// the whole list; that restatement is visible in review, an accidental
1260/// concatenation would not be.
1261fn array_merge_policy(key: &str) -> ArrayMerge {
1262 match key {
1263 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1264 _ => ArrayMerge::Replace,
1265 }
1266}
1267
1268impl Config {
1269 /// Load one file through teravars: Tera rendering, `[vars]` resolution,
1270 /// and the `include = [...]` directive.
1271 pub fn load(path: &Path) -> Result<Self> {
1272 Self::load_layers(&[path.to_path_buf()])
1273 }
1274
1275 /// The Tera render context shared by every layer: `system.*` (from
1276 /// teravars), `env` (magi's own addition - a config that names a shared
1277 /// build-cache directory or a machine-specific path needs
1278 /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
1279 /// derived from the last (highest-priority) path's parent directory.
1280 ///
1281 /// Factored out so [`Config::array_provenance`] can re-render a single
1282 /// layer under the exact same context [`Config::load_layers`] uses for
1283 /// the joint render, rather than drifting from it by accident.
1284 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1285 let mut ctx = teravars::system_context();
1286 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1287 ctx.insert("env", &env);
1288 if let Some(last) = paths.last()
1289 && let Some(dir) = last.parent()
1290 {
1291 ctx.insert("repo", &dir.to_string_lossy());
1292 ctx.insert(
1293 "repo_name",
1294 &dir.file_name().unwrap_or_default().to_string_lossy(),
1295 );
1296 }
1297 ctx
1298 }
1299
1300 /// Load and deep-merge a stack of config files, later files winning.
1301 ///
1302 /// This is why the config is TOML-through-teravars rather than plain serde:
1303 /// the roster is a *machine* fact (which CLIs and plans you pay for) while
1304 /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
1305 /// there). Picking one file and ignoring the other would force every repo
1306 /// to restate the roster.
1307 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1308 let mut engine = teravars::Engine::default();
1309 let ctx = Self::render_ctx(paths);
1310 if paths.len() > 1 {
1311 Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
1312 }
1313 let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
1314 format!(
1315 "rendering config via teravars: {}",
1316 paths
1317 .iter()
1318 .map(|p| p.display().to_string())
1319 .collect::<Vec<_>>()
1320 .join(", ")
1321 )
1322 })?;
1323 let mut table = merged.config;
1324 // `[vars]` is teravars' own input, already resolved into the render
1325 // context; `deny_unknown_fields` must not trip over it.
1326 table.remove("vars");
1327 // No layer says anything about `agents`: the roster is whatever is on
1328 // `PATH` now, exactly as when no layer exists at all. An explicit
1329 // `agents = []` is a statement and is kept.
1330 let detect_agents = !table.contains_key("agents");
1331 let mut cfg: Self = toml::Value::Table(table)
1332 .try_into()
1333 .context("deserializing magi config")?;
1334 if detect_agents {
1335 cfg.agents = Self::autodetected().agents;
1336 }
1337 Ok(cfg)
1338 }
1339
1340 /// Refuse an array that two layers both declare, unless
1341 /// [`array_merge_policy`] says that key is meant to accumulate.
1342 ///
1343 /// teravars **appends** arrays when it merges layers, and that is wrong for
1344 /// most arrays magi has: `implementers` is an ordered list of seats,
1345 /// `notify.command` is an argv. Concatenating two of them yields something
1346 /// nobody wrote - three implementers out of a machine's two and a
1347 /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
1348 ///
1349 /// Replacing instead would be the right merge rule for those keys, but the
1350 /// rule lives in teravars, which several other projects depend on;
1351 /// changing it there is a decision for that crate, not something to fake
1352 /// here by re-reading the files with different semantics and hoping the
1353 /// two paths agree.
1354 ///
1355 /// So magi refuses the ambiguity rather than resolving it silently, for
1356 /// every array key except the short, deliberate list
1357 /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
1358 /// concatenation teravars already produces *is* what both files say, so
1359 /// there is nothing to refuse. The cost of guessing wrong on the refused
1360 /// keys is a roster the operator did not ask for and is paying for by the
1361 /// token; the append keys carry no such risk because every element runs
1362 /// (or every directory is scanned) regardless of order.
1363 fn refuse_split_arrays(
1364 paths: &[PathBuf],
1365 engine: &mut teravars::Engine,
1366 ctx: &teravars::Context,
1367 ) -> Result<()> {
1368 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1369 for path in paths {
1370 let one = teravars::load_merged([path], engine, ctx)
1371 .with_context(|| format!("rendering {}", path.display()))?;
1372 for key in array_keys(&one.config, "") {
1373 if array_merge_policy(&key) == ArrayMerge::Append {
1374 continue;
1375 }
1376 if let Some(first) = seen.get(&key) {
1377 bail!(
1378 "`{key}` is an array declared in two config layers:\n \
1379 {}\n {}\nteravars appends arrays when it merges, so \
1380 magi would run the concatenation of both - which is \
1381 not what either file says. Declare `{key}` in exactly \
1382 one of them.",
1383 first.display(),
1384 path.display()
1385 );
1386 }
1387 seen.insert(key, path.clone());
1388 }
1389 }
1390 Ok(())
1391 }
1392
1393 /// Which layers contributed to a composed, appendable array key (e.g.
1394 /// `"verify.gate"`), in the same low-to-high-priority order
1395 /// [`Config::load_layers`] concatenates them in. Layers that do not
1396 /// declare `key` at all are omitted.
1397 ///
1398 /// This is a **display aid for `magi doctor` only.** The command list
1399 /// that actually runs always comes from the one joint
1400 /// [`teravars::load_merged`] call in `load_layers`, never from this
1401 /// function - the exact hazard [`Config::refuse_split_arrays`] warns
1402 /// about is two merge paths that might disagree, so this function must
1403 /// never become a second source of the *composed* value, only of which
1404 /// file wrote which line in it.
1405 ///
1406 /// Re-rendering each layer alone can, in principle, resolve a
1407 /// `{{ vars.x }}` differently than the joint render would, if `x` is
1408 /// defined in one layer and referenced in another - the same caveat
1409 /// `refuse_split_arrays`'s structural, key-only check already lives with.
1410 /// None of magi's own gate commands cross that line, and a doctor listing
1411 /// is read by a human who can compare it against the joint one printed
1412 /// alongside it, so this is judged worth the simplicity of not
1413 /// threading provenance through the real load path.
1414 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1415 let mut engine = teravars::Engine::default();
1416 let ctx = Self::render_ctx(paths);
1417 let mut out = Vec::new();
1418 for path in paths {
1419 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1420 continue;
1421 };
1422 let mut cur = &one.config;
1423 let mut found = None;
1424 let parts: Vec<&str> = key.split('.').collect();
1425 for (i, part) in parts.iter().enumerate() {
1426 match cur.get(*part) {
1427 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1428 found = Some(a);
1429 break;
1430 }
1431 Some(toml::Value::Table(t)) => cur = t,
1432 _ => break,
1433 }
1434 }
1435 let Some(values) = found else { continue };
1436 let strings: Vec<String> = values
1437 .iter()
1438 .filter_map(|v| v.as_str().map(str::to_owned))
1439 .collect();
1440 if !strings.is_empty() {
1441 out.push((path.clone(), strings));
1442 }
1443 }
1444 out
1445 }
1446
1447 /// Each layer rendered on its own, with the outcome per file: the
1448 /// settings screen's way of saying which layer a value came from and which
1449 /// layer is the one that does not parse. A **display aid only**, for the
1450 /// same reason as [`Config::array_provenance`]: the effective config
1451 /// always comes from the one joint [`Config::load_layers`].
1452 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1453 let mut engine = teravars::Engine::default();
1454 let ctx = Self::render_ctx(paths);
1455 paths
1456 .iter()
1457 .map(|path| {
1458 let one = teravars::load_merged([path], &mut engine, &ctx)
1459 .map(|m| m.config)
1460 .with_context(|| format!("rendering {}", path.display()));
1461 (path.clone(), one)
1462 })
1463 .collect()
1464 }
1465
1466 /// Render a composed command list for `magi doctor`: the joined command
1467 /// line the run actually uses, plus - only when more than one layer
1468 /// contributed - which layer wrote which line.
1469 ///
1470 /// A single contributing layer (the common case today) stays the plain
1471 /// one-line summary magi has always printed, `empty` included: that
1472 /// honest "(none — ...)" is what caught a real gate-composition gap
1473 /// before this array could compose at all, and composition should not
1474 /// make the common case noisier.
1475 pub fn describe_composed(
1476 paths: &[PathBuf],
1477 commands: &[String],
1478 key: &str,
1479 empty: &str,
1480 ) -> String {
1481 if commands.is_empty() {
1482 return empty.to_owned();
1483 }
1484 let joined = commands.join(" && ");
1485 let provenance = Self::array_provenance(paths, key);
1486 if provenance.len() <= 1 {
1487 return joined;
1488 }
1489 let mut out = joined;
1490 for (path, cmds) in &provenance {
1491 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1492 }
1493 out
1494 }
1495
1496 /// Resolve the config for `repo`, honouring an explicit `--config` path.
1497 ///
1498 /// Returns the config and the layers it came from, empty for built-in
1499 /// defaults.
1500 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1501 if let Some(p) = explicit {
1502 let paths = vec![p.to_path_buf()];
1503 return Ok((Self::load_layers(&paths)?, paths));
1504 }
1505 let paths = Self::layers(repo);
1506 if paths.is_empty() {
1507 return Ok((Self::autodetected(), paths));
1508 }
1509 Ok((Self::load_layers(&paths)?, paths))
1510 }
1511 /// Environment variable that relocates the machine-wide config layer.
1512 ///
1513 /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
1514 /// of the one under [`dirs::config_dir`]; set it to the empty string and
1515 /// magi reads no machine layer at all.
1516 ///
1517 /// This exists because the machine layer is otherwise unavoidable, and a
1518 /// test that builds a config fixture is not asking for the operator's
1519 /// preferences to be merged into it. Adding `[repos] roots` to the real
1520 /// machine config on a development box turned two passing tests red -
1521 /// `repos_list_returns_name_and_path_for_every_configured_root` and
1522 /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
1523 /// declare `[repos] roots` of their own, which [`Config::layers`] then
1524 /// found in two layers and [`Config::refuse_split_arrays`] correctly
1525 /// refused. CI never saw it: a runner has no machine config, so the suite
1526 /// was green there and red only where somebody actually uses magi.
1527 ///
1528 /// An operator gets the same escape hatch for free: a second machine
1529 /// config, or none, without moving files about.
1530 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
1531
1532 /// Every config layer that applies to `repo`, in increasing precedence.
1533 ///
1534 /// The machine layer is whatever [`Config::machine_layer`] resolves to,
1535 /// which is nothing at all in a test build.
1536 pub fn layers(repo: &Path) -> Vec<PathBuf> {
1537 let mut paths = Vec::new();
1538 paths.extend(Self::machine_layer());
1539 paths.push(repo.join(".magi").join("config.toml"));
1540 paths.push(repo.join("magi.toml"));
1541 paths.retain(|p| p.is_file());
1542 paths
1543 }
1544
1545 /// The machine-wide layer's path, when there is one.
1546 ///
1547 /// **A test build has none unless it names one.** A fixture is a complete
1548 /// statement of the config under test, and the operator's own preferences
1549 /// have no business being merged into it - least of all silently, on one
1550 /// machine, in a suite that is green everywhere else.
1551 #[cfg(test)]
1552 pub(crate) fn machine_layer() -> Option<PathBuf> {
1553 std::env::var(Self::CONFIG_DIR_ENV)
1554 .ok()
1555 .filter(|dir| !dir.trim().is_empty())
1556 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
1557 }
1558
1559 /// The machine-wide layer's path, when there is one.
1560 #[cfg(not(test))]
1561 pub(crate) fn machine_layer() -> Option<PathBuf> {
1562 match std::env::var(Self::CONFIG_DIR_ENV) {
1563 // Named, and empty on purpose: no machine layer.
1564 Ok(dir) if dir.trim().is_empty() => None,
1565 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1566 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1567 }
1568 }
1569
1570 /// Built-in config whose roster is the agent CLIs found on `PATH`.
1571 pub fn autodetected() -> Self {
1572 let mut cfg = Self::default();
1573 for (kind, id, model) in [
1574 (AgentKind::Claude, "opus", Some("opus")),
1575 (AgentKind::Claude, "sonnet", Some("sonnet")),
1576 (AgentKind::Antigravity, "antigravity", None),
1577 (AgentKind::Opencode, "opencode", None),
1578 (AgentKind::Codex, "codex", None),
1579 (AgentKind::Omp, "omp", None),
1580 ] {
1581 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1582 cfg.agents.push(AgentSpec {
1583 id: id.to_owned(),
1584 kind,
1585 model: model.map(str::to_owned),
1586 command: Vec::new(),
1587 extra_args: Vec::new(),
1588 env: BTreeMap::new(),
1589 prompt_delivery: None,
1590 });
1591 }
1592 }
1593 cfg
1594 }
1595
1596 /// The shared build cache the verify commands and the agents both build
1597 /// into, when the config declares one. See [`Verify::cache_dir`].
1598 pub fn cache_dir(&self) -> Option<PathBuf> {
1599 self.verify.cache_dir()
1600 }
1601
1602 /// Look an agent up by id.
1603 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1604 self.agents
1605 .iter()
1606 .find(|a| a.id == id)
1607 .with_context(|| format!("no agent with id `{id}` in the roster"))
1608 }
1609
1610 /// Rotate `count` seats out of `ids`, or out of the whole roster at
1611 /// `offset` when `ids` is empty.
1612 ///
1613 /// The one rotation rule - explicit ids cycle, an empty list rotates the
1614 /// roster - shared by every seat count [`Config::resolve_roles`] fills in,
1615 /// rather than each seat reimplementing it and drifting apart.
1616 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
1617 let mut out = Vec::with_capacity(count);
1618 for i in 0..count {
1619 let spec = if ids.is_empty() {
1620 self.agents[(i + offset) % self.agents.len()].clone()
1621 } else {
1622 self.agent(&ids[i % ids.len()])?.clone()
1623 };
1624 out.push(spec);
1625 }
1626 Ok(out)
1627 }
1628
1629 /// `ids`, resolved to specs in the order named, or the whole `[[agents]]`
1630 /// roster in file order when `ids` is empty — the same "explicit ids
1631 /// stand alone, an empty list means the whole roster" rule [`Self::rotate`]
1632 /// applies, but with no `count` to truncate to and no `offset` to wrap by.
1633 /// See [`ResolvedRoles::implementer_roster`] for why a truncated, rotated
1634 /// list cannot answer the question this exists for.
1635 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
1636 if ids.is_empty() {
1637 Ok(self.agents.clone())
1638 } else {
1639 ids.iter().map(|id| self.agent(id).cloned()).collect()
1640 }
1641 }
1642
1643 /// Fill the roles out to the configured widths.
1644 ///
1645 /// An empty role list rotates through the whole roster, so a three-agent
1646 /// roster with `candidates = 3` gives one implementation per agent, and
1647 /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1648 /// author of candidate *i* whenever the roster has more than one agent.
1649 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1650 if self.agents.is_empty() {
1651 bail!(
1652 "agent roster is empty: no agent CLI found on PATH and no \
1653 [[agents]] in the config. Run `magi init` to write a starter \
1654 magi.toml."
1655 );
1656 }
1657 Ok(ResolvedRoles {
1658 implementers: self.rotate(&self.roles.implementers, self.graph.candidates, 0)?,
1659 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
1660 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
1661 fixer: self
1662 .roles
1663 .fixer
1664 .as_deref()
1665 .map(|f| self.agent(f).cloned())
1666 .transpose()?,
1667 // Role resolution validates roster shape, but deliberately does
1668 // not preflight a CLI. The other graph seats have always deferred
1669 // that failure to invocation; doing it only for the conductor
1670 // made otherwise usable graph commands and `doctor` fail as one.
1671 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
1672 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
1673 // A fallback chain: the first id the roster knows. The rest
1674 // are `agent::pick_chain`'s business at invocation.
1675 Some(ids) if !ids.is_empty() => ids
1676 .iter()
1677 .find_map(|id| self.agent(id).ok())
1678 .cloned()
1679 .with_context(|| {
1680 format!("[roles] conductor names no agent in the roster: {ids:?}")
1681 })?,
1682 // Keep the normal standalone-seat preference when something
1683 // is installed, but retain a roster fallback when it is not.
1684 // Invocation then reports the unavailable CLI in the same
1685 // place it does for every other graph role.
1686 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
1687 .unwrap_or_else(|_| self.agents[0].clone()),
1688 },
1689 implementer_roster: self.full_roster(&self.roles.implementers)?,
1690 judge_roster: self.full_roster(&self.roles.judges)?,
1691 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
1692 })
1693 }
1694
1695 /// Advisor seats for the design-deliberation stage (see
1696 /// `graph::Runner::advise`): `[roles] advisors` when set, otherwise the
1697 /// judge roster - see [`Roles::advisors`] for why that fallback and not
1698 /// the whole roster.
1699 ///
1700 /// The fallback rotates with `offset = 1`, matching the judges line in
1701 /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
1702 /// `roles.judges`, which is empty whenever judges themselves are
1703 /// unconfigured and rotating the whole roster. Falling back with
1704 /// `offset = 0` there would silently hand the advisors a *different*
1705 /// agent set than the judges an unconfigured run would actually get,
1706 /// which is the one thing [`Roles::advisors`]'s doc promises will not
1707 /// happen.
1708 ///
1709 /// Called lazily from the graph node itself rather than folded into
1710 /// [`Config::resolve_roles`]: unlike the other roles, a failure here must
1711 /// not stop a run from starting at all - the deliberation stage is an
1712 /// enrichment `[graph] advise` can turn off, not a seat later nodes
1713 /// cannot proceed without - and at the point `resolve_roles` runs (before
1714 /// [`crate::run::RunState`] exists, on `Runner::start`) there would be no
1715 /// run yet for a resolution failure to be reported against.
1716 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
1717 if self.agents.is_empty() {
1718 bail!(
1719 "agent roster is empty: no agent CLI found on PATH and no \
1720 [[agents]] in the config. Run `magi init` to write a starter \
1721 magi.toml."
1722 );
1723 }
1724 if !self.roles.advisors.is_empty() {
1725 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
1726 }
1727 self.rotate(&self.roles.judges, self.graph.advisors, 1)
1728 }
1729
1730 /// The untruncated roster advisor seats hand over along: `[roles]
1731 /// advisors` when set, otherwise the judges' roster, exactly as
1732 /// [`Self::advisors`] chooses its own list.
1733 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
1734 if self.roles.advisors.is_empty() {
1735 self.full_roster(&self.roles.judges)
1736 } else {
1737 self.full_roster(&self.roles.advisors)
1738 }
1739 }
1740
1741 /// Shell prefix for [`Verify`] commands.
1742 pub fn shell(&self) -> Vec<String> {
1743 if let Some(s) = &self.verify.shell {
1744 return s.clone();
1745 }
1746 if which("sh") {
1747 vec!["sh".to_owned(), "-c".to_owned()]
1748 } else {
1749 vec!["cmd".to_owned(), "/C".to_owned()]
1750 }
1751 }
1752
1753 /// Starter config, as written by `magi init`.
1754 pub fn starter_toml() -> String {
1755 let detected = Self::autodetected();
1756 let mut s = String::from(
1757 "# magi — blind multi-agent implementation competition.\n\
1758 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
1759 # -> blind judging -> deliberation -> private final vote\n\
1760 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
1761 #\n\
1762 # Rendered by teravars: a `[vars]` table, env\n\
1763 # and system lookups, and `include = [...]` all work. Tera\n\
1764 # braces are live everywhere in this file, but comments are\n\
1765 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
1766 # may quote `{{ ... }}` freely.\n\
1767 #\n\
1768 # Layers deep-merge in increasing\n\
1769 # precedence, so the roster can live once per machine in\n\
1770 # <config_dir>/magi/config.toml and each repo only states its own\n\
1771 # gate:\n\
1772 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
1773 [vars]\n\
1774 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
1775 # Single quotes inside the braces: teravars renders the raw file\n\
1776 # text, so TOML's own \\\" escaping never reaches Tera.\n\
1777 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
1778 );
1779 if detected.agents.is_empty() {
1780 s.push_str(
1781 "# No agent CLI was found on PATH. Fill this in by hand.\n\
1782 # kind = claude | opencode | antigravity | codex | command\n\
1783 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
1784 );
1785 } else {
1786 for a in &detected.agents {
1787 s.push_str("[[agents]]\n");
1788 s.push_str(&format!("id = {:?}\n", a.id));
1789 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
1790 if let Some(m) = &a.model {
1791 s.push_str(&format!("model = {m:?}\n"));
1792 }
1793 s.push('\n');
1794 }
1795 }
1796 s.push_str(
1797 "# Leave a role list empty to rotate through the roster.\n\
1798 [roles]\n\
1799 implementers = []\n\
1800 judges = []\n\
1801 reviewers = []\n\
1802 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
1803 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
1804 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
1805 [graph]\n\
1806 candidates = 3\n\
1807 judges = 3\n\
1808 deliberate_rounds = 1\n\
1809 reviewers = 3\n\
1810 review_rounds = 6\n\
1811 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
1812 gate_fix_rounds = 1\n\
1813 max_parallel = 4\n\
1814 language = \"en\"\n\
1815 # One CLI conversation per seat: judges keep their own argument\n\
1816 # across deliberation, the fixer keeps its implementation context.\n\
1817 sessions = true\n\
1818 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
1819 # the final gate inherit this value for compatibility.\n\
1820 timeout_review = 1200\n\
1821 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
1822 # verification independent if timeout_review changes later.\n\
1823 # timeout_verify = 1200\n\n\
1824 [verify]\n\
1825 # Run once per review round in the winner's worktree; failures are\n\
1826 # fed back to the fixer.\n\
1827 e2e = []\n\
1828 # Final gate. Every command must exit 0 before a merge.\n\
1829 gate = []\n\
1830 # Mechanical fixers (formatters) run in the winner's worktree just\n\
1831 # before the gate; whatever they change becomes one commit. A failing\n\
1832 # command only warns - the gate stays the arbiter. Same timeout as the\n\
1833 # gate (timeout_verify). Keep it light and idempotent.\n\
1834 # pre_gate = []\n\n\
1835 [merge]\n\
1836 # none | local | pr\n\
1837 mode = \"none\"\n\
1838 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
1839 [update]\n\
1840 # off | notify | install — checked in the background, throttled.\n\
1841 mode = \"notify\"\n\
1842 # interval = \"24h\"\n\n\
1843 [daemon]\n\
1844 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
1845 # no new commit and no check changing state before `magi serve`\n\
1846 # notices and asks you. A failed check is rerun once on its own;\n\
1847 # still red after that escalates at once. 0 turns the watcher off.\n\
1848 # release_stall_minutes = 60\n\n\
1849 [release]\n\
1850 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
1851 # Actions never run (private, no minutes): the release pull request\n\
1852 # does not wait for CI, you approve the merge in magi, and then\n\
1853 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
1854 # runs `commands` from a clean checkout of the merge commit. A\n\
1855 # failure holds the release with a notice; it is never retried blind.\n\
1856 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
1857 # mode = \"actions\"\n\
1858 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
1859 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
1860 # safe to repeat: a crash mid-command is treated as unfinished.\n\
1861 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
1862 # timeout_minutes = 30\n",
1863 );
1864 s
1865 }
1866}
1867
1868/// Is `program` on `PATH`?
1869pub fn which(program: &str) -> bool {
1870 find_program(program).is_some()
1871}
1872
1873/// The file a bare `program` name resolves to on `PATH`, the way the OS shell
1874/// would find it.
1875///
1876/// Spawn agents through this, not by bare name: on Windows Rust's std
1877/// only tries `name.exe`, so a CLI installed as an npm `.cmd` shim (codex
1878/// since its 2026-09-23 reinstall) is "not found" even though a shell runs it.
1879/// On Windows an extensionless file is never a match: npm writes an `sh`
1880/// script beside every `.cmd` shim, and spawning that fails with os error 193.
1881pub fn find_program(program: &str) -> Option<PathBuf> {
1882 find_program_on(program, &std::env::var_os("PATH")?)
1883}
1884
1885/// [`find_program`] against an explicit `PATH`, for a child whose environment
1886/// overrides it.
1887pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
1888 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
1889 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
1890}
1891
1892fn find_program_in(
1893 program: &str,
1894 paths: &std::ffi::OsStr,
1895 pathext: Option<&str>,
1896) -> Option<PathBuf> {
1897 let p = Path::new(program);
1898 if p.components().count() > 1 {
1899 return p.is_file().then(|| p.to_path_buf());
1900 }
1901 std::env::split_paths(paths).find_map(|dir| match pathext {
1902 Some(exts) => {
1903 let bare = dir.join(program);
1904 if p.extension().is_some() && bare.is_file() {
1905 return Some(bare);
1906 }
1907 exts.split(';')
1908 .filter(|e| !e.is_empty())
1909 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
1910 .find(|c| c.is_file())
1911 }
1912 None => Some(dir.join(program)).filter(|c| c.is_file()),
1913 })
1914}
1915
1916#[cfg(test)]
1917mod tests {
1918 #[test]
1919 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
1920 let mut cfg = Config::default();
1921 assert_eq!(
1922 cfg.context_window("claude-sonnet-4-5-20250929"),
1923 Some(200_000)
1924 );
1925 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
1926 assert_eq!(cfg.context_window("mystery-model"), None);
1927 cfg.context_windows
1928 .insert("claude-sonnet-4-5".into(), 1_000_000);
1929 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
1930 cfg.context_windows.insert("mystery".into(), 32_768);
1931 // Longest user prefix beats a shorter one and the built-in table.
1932 assert_eq!(
1933 cfg.context_window("claude-sonnet-4-5-20250929"),
1934 Some(1_000_000)
1935 );
1936 // An exact name beats any prefix.
1937 cfg.context_windows
1938 .insert("claude-sonnet-4-5-20250929".into(), 7);
1939 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
1940 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
1941 }
1942
1943 use super::*;
1944
1945 /// npm writes an extensionless `sh` script beside `codex.cmd`; on Windows
1946 /// the `.cmd` is the spawnable one (os error 193 otherwise, 2026-09-23).
1947 #[test]
1948 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
1949 let dir = tempfile::tempdir().unwrap();
1950 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
1951 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
1952 let paths = dir.path().as_os_str();
1953 assert_eq!(
1954 find_program_in("codex", paths, Some(".EXE;.CMD")),
1955 Some(dir.path().join("codex.cmd"))
1956 );
1957 assert_eq!(
1958 find_program_in("codex", paths, None),
1959 Some(dir.path().join("codex"))
1960 );
1961 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
1962 }
1963
1964 fn spec(id: &str) -> AgentSpec {
1965 AgentSpec {
1966 id: id.to_owned(),
1967 kind: AgentKind::Command,
1968 model: None,
1969 command: vec!["true".to_owned()],
1970 extra_args: Vec::new(),
1971 env: BTreeMap::new(),
1972 prompt_delivery: None,
1973 }
1974 }
1975
1976 #[test]
1977 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
1978 // `timeout_verify` used to not exist: `verify.e2e`/`verify.gate` ran
1979 // under `timeout_review`. A config written before this field existed
1980 // must run exactly as before, which means its default has to be the
1981 // same 1200s `timeout_review` has always defaulted to.
1982 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
1983 assert_eq!(g.timeout_verify, None);
1984 assert_eq!(g.verify_timeout(), 3600);
1985 }
1986
1987 #[test]
1988 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
1989 // The bug this field exists to close: `[graph] timeout_review = 45`
1990 // used to shrink the real-machine `verify.e2e`/`verify.gate` budget
1991 // along with the reviewer seats' own timeout, because both read the
1992 // same field.
1993 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
1994 assert_eq!(g.timeout_review, 45);
1995 assert_eq!(
1996 g.verify_timeout(),
1997 45,
1998 "an omitted legacy value follows review"
1999 );
2000 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
2001 .expect("parse explicit override");
2002 assert_eq!(explicit.verify_timeout(), 1200);
2003 }
2004
2005 #[test]
2006 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
2007 // `deny_unknown_fields` cuts both ways: a config from before
2008 // `timeout_verify`/`e2e_every_round` existed must still parse, with
2009 // both defaulted rather than refused as unknown-in-reverse.
2010 let g: Graph =
2011 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
2012 .expect("an old-shaped [graph] table must still parse");
2013 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
2014 assert!(
2015 !g.e2e_every_round,
2016 "off by default, same as before this field existed"
2017 );
2018 }
2019
2020 #[test]
2021 fn empty_roles_rotate_judges_off_their_own_candidate() {
2022 // Three seats, said out loud: this is a test about *rotation*, and it
2023 // has nothing to say about how many candidates a task buys by default.
2024 let cfg = Config {
2025 agents: vec![spec("a"), spec("b"), spec("c")],
2026 graph: Graph {
2027 candidates: 3,
2028 ..Graph::default()
2029 },
2030 ..Config::default()
2031 };
2032 let roles = cfg.resolve_roles().unwrap();
2033 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
2034 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
2035 assert_eq!(impls, ["a", "b", "c"]);
2036 assert_eq!(judges, ["b", "c", "a"]);
2037 for (i, j) in judges.iter().enumerate() {
2038 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
2039 }
2040 }
2041
2042 #[test]
2043 fn single_agent_roster_fills_every_seat() {
2044 let cfg = Config {
2045 agents: vec![spec("solo")],
2046 graph: Graph {
2047 candidates: 3,
2048 ..Graph::default()
2049 },
2050 ..Config::default()
2051 };
2052 let roles = cfg.resolve_roles().unwrap();
2053 assert_eq!(roles.implementers.len(), 3);
2054 assert!(roles.judges.iter().all(|a| a.id == "solo"));
2055 }
2056
2057 #[test]
2058 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
2059 // `candidates = 1` (a solo run) still resolves `implementers` down to
2060 // one slot, but `implementer_roster` must carry every agent in the
2061 // roster, in file order, for `graph::Runner`'s quota fallback to walk
2062 // forward through once that one slot's agent runs out of quota.
2063 let cfg = Config {
2064 agents: vec![spec("a"), spec("b"), spec("c")],
2065 graph: Graph {
2066 candidates: 1,
2067 ..Graph::default()
2068 },
2069 ..Config::default()
2070 };
2071 let roles = cfg.resolve_roles().unwrap();
2072 assert_eq!(roles.implementers.len(), 1);
2073 let roster: Vec<&str> = roles
2074 .implementer_roster
2075 .iter()
2076 .map(|a| a.id.as_str())
2077 .collect();
2078 assert_eq!(roster, ["a", "b", "c"]);
2079 }
2080
2081 #[test]
2082 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
2083 let cfg = Config {
2084 agents: vec![spec("a"), spec("b"), spec("c")],
2085 roles: Roles {
2086 implementers: vec!["c".to_owned(), "a".to_owned()],
2087 ..Roles::default()
2088 },
2089 graph: Graph {
2090 candidates: 1,
2091 ..Graph::default()
2092 },
2093 ..Config::default()
2094 };
2095 let roles = cfg.resolve_roles().unwrap();
2096 // Unaffected by the new field: still just the first named id.
2097 assert_eq!(roles.implementers.len(), 1);
2098 assert_eq!(roles.implementers[0].id, "c");
2099 let roster: Vec<&str> = roles
2100 .implementer_roster
2101 .iter()
2102 .map(|a| a.id.as_str())
2103 .collect();
2104 assert_eq!(roster, ["c", "a"]);
2105 }
2106
2107 #[test]
2108 fn explicit_roles_win() {
2109 let cfg = Config {
2110 agents: vec![spec("a"), spec("b")],
2111 roles: Roles {
2112 implementers: vec!["b".to_owned()],
2113 judges: vec!["a".to_owned()],
2114 reviewers: Vec::new(),
2115 fixer: Some("a".to_owned()),
2116 ..Roles::default()
2117 },
2118 ..Config::default()
2119 };
2120 let roles = cfg.resolve_roles().unwrap();
2121 assert!(roles.implementers.iter().all(|a| a.id == "b"));
2122 assert!(roles.judges.iter().all(|a| a.id == "a"));
2123 assert_eq!(roles.fixer.unwrap().id, "a");
2124 assert_eq!(roles.conductor.id, "a");
2125 }
2126
2127 #[test]
2128 fn unknown_agent_id_is_an_error() {
2129 let cfg = Config {
2130 agents: vec![spec("a")],
2131 roles: Roles {
2132 judges: vec!["nope".to_owned()],
2133 ..Roles::default()
2134 },
2135 ..Config::default()
2136 };
2137 assert!(cfg.resolve_roles().is_err());
2138 }
2139
2140 #[test]
2141 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
2142 let mut cfg = Config {
2143 agents: vec![spec("a"), spec("b")],
2144 ..Config::default()
2145 };
2146 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
2147
2148 cfg.roles.conductor = Some("b".into());
2149 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
2150
2151 cfg.roles.conductor = Some("missing".into());
2152 assert!(cfg.resolve_roles().is_err());
2153 }
2154
2155 #[test]
2156 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
2157 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
2158 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
2159 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
2160
2161 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
2162 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
2163 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
2164
2165 for roles in [one, chain] {
2166 let text = toml::to_string(&roles).unwrap();
2167 let back: Roles = toml::from_str(&text).unwrap();
2168 assert_eq!(back.synthesizer, roles.synthesizer);
2169 assert_eq!(back.chatter, roles.chatter);
2170 }
2171 let text = toml::to_string(&Roles {
2172 conductor: Some("x".into()),
2173 ..Roles::default()
2174 })
2175 .unwrap();
2176 assert!(
2177 text.contains("conductor = \"x\""),
2178 "string stays a string: {text}"
2179 );
2180 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
2181 }
2182
2183 #[test]
2184 fn an_empty_choice_counts_as_unset() {
2185 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
2186 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
2187 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
2188 }
2189
2190 #[test]
2191 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
2192 // Unlike `conductor`, `synthesizer` is never validated by
2193 // `resolve_roles` — it is looked up lazily by
2194 // `graph::Runner::synthesize_brief` the same way `[roles] chatter`
2195 // is looked up by `talk::begin`, so this exercises `agent::pick`
2196 // directly instead of going through `resolve_roles`.
2197 let mut cfg = Config {
2198 agents: vec![spec("a"), spec("b")],
2199 ..Config::default()
2200 };
2201 let want = primary(cfg.roles.synthesizer.as_ref());
2202 assert_eq!(
2203 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
2204 .unwrap()
2205 .id,
2206 "a",
2207 "unset falls back to agent::pick's own default order"
2208 );
2209
2210 cfg.roles.synthesizer = Some("b".into());
2211 let want = primary(cfg.roles.synthesizer.as_ref());
2212 assert_eq!(
2213 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
2214 .unwrap()
2215 .id,
2216 "b",
2217 "the named agent wins over the default order"
2218 );
2219 }
2220
2221 #[test]
2222 fn empty_roster_is_an_error() {
2223 assert!(Config::default().resolve_roles().is_err());
2224 }
2225
2226 #[test]
2227 fn advise_defaults_to_on_with_three_proposals() {
2228 let g = Graph::default();
2229 assert!(g.advise);
2230 assert_eq!(g.advisors, 3);
2231 }
2232
2233 #[test]
2234 fn unset_advisors_falls_back_to_the_judge_roster() {
2235 let cfg = Config {
2236 agents: vec![spec("a"), spec("b")],
2237 roles: Roles {
2238 judges: vec!["b".to_owned()],
2239 ..Roles::default()
2240 },
2241 graph: Graph {
2242 advisors: 2,
2243 ..Graph::default()
2244 },
2245 ..Config::default()
2246 };
2247 let advisors = cfg.advisors().expect("advisors resolve");
2248 assert_eq!(advisors.len(), 2);
2249 assert!(
2250 advisors.iter().all(|a| a.id == "b"),
2251 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
2252 );
2253 }
2254
2255 #[test]
2256 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
2257 let cfg = Config {
2258 agents: vec![spec("a"), spec("b")],
2259 roles: Roles {
2260 judges: vec!["b".to_owned()],
2261 advisors: vec!["a".to_owned()],
2262 ..Roles::default()
2263 },
2264 graph: Graph {
2265 advisors: 2,
2266 ..Graph::default()
2267 },
2268 ..Config::default()
2269 };
2270 let advisors = cfg.advisors().expect("advisors resolve");
2271 assert!(advisors.iter().all(|a| a.id == "a"));
2272 }
2273
2274 /// Neither `[roles] advisors` nor `[roles] judges` set: an unconfigured
2275 /// advisor roster must resolve to the exact same agents an unconfigured
2276 /// judge panel would get - same ids, same rotation offset - or the
2277 /// promise in [`Roles::advisors`]'s doc ("advisor diversity for free")
2278 /// does not actually hold.
2279 #[test]
2280 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
2281 let cfg = Config {
2282 agents: vec![spec("a"), spec("b"), spec("c")],
2283 graph: Graph {
2284 advisors: 3,
2285 judges: 3,
2286 ..Graph::default()
2287 },
2288 ..Config::default()
2289 };
2290 let advisors = cfg.advisors().expect("advisors resolve");
2291 let judges = cfg.resolve_roles().expect("roles resolve").judges;
2292 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
2293 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
2294 assert_eq!(
2295 advisor_ids, judge_ids,
2296 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
2297 );
2298 }
2299
2300 #[test]
2301 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
2302 let cfg = Config {
2303 agents: vec![spec("a")],
2304 roles: Roles {
2305 advisors: vec!["nope".to_owned()],
2306 ..Roles::default()
2307 },
2308 graph: Graph {
2309 advisors: 1,
2310 ..Graph::default()
2311 },
2312 ..Config::default()
2313 };
2314 let err = cfg.advisors().expect_err("`nope` is not in the roster");
2315 assert!(format!("{err:#}").contains("nope"));
2316 }
2317
2318 #[test]
2319 fn repos_default_to_no_roots_and_a_day_of_trust() {
2320 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
2321 assert_eq!(Config::default().repos.scan_ttl, 86_400);
2322 assert_eq!(Config::default().repos.fetch_interval, 600);
2323 }
2324
2325 #[test]
2326 fn a_config_file_with_no_repos_table_still_loads() {
2327 let dir = tempfile::tempdir().unwrap();
2328 let path = dir.path().join("magi.toml");
2329 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
2330 let cfg = Config::load(&path).expect("must load without [repos]");
2331 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
2332 assert_eq!(cfg.repos.scan_ttl, 86_400);
2333 }
2334
2335 /// A fixture is the whole config under test.
2336 ///
2337 /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
2338 /// a machine where somebody had written `<config_dir>/magi/config.toml`
2339 /// the suite silently loaded it as the lowest layer. Adding `[repos]
2340 /// roots` there turned two web tests red - their fixtures declare
2341 /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
2342 /// array key spread across two layers. CI stayed green throughout,
2343 /// because a runner has no such file: the suite failed only where magi is
2344 /// actually used.
2345 ///
2346 /// So a test build has no machine layer unless it asks for one, and this
2347 /// is that promise. Written against a real file at the real location so
2348 /// it fails if `machine_layer` starts reading it again.
2349 #[test]
2350 fn a_test_build_does_not_read_the_operators_machine_config() {
2351 let repo = tempfile::tempdir().unwrap();
2352 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
2353
2354 let layers = Config::layers(repo.path());
2355 assert_eq!(
2356 layers,
2357 vec![repo.path().join("magi.toml")],
2358 "only the fixture's own file may be a layer"
2359 );
2360 if let Some(real) = dirs::config_dir() {
2361 let machine = real.join("magi").join("config.toml");
2362 assert!(
2363 !layers.contains(&machine),
2364 "the operator's {} must not be a layer in a test build",
2365 machine.display()
2366 );
2367 }
2368 }
2369
2370 #[test]
2371 fn starter_toml_loads_through_teravars() {
2372 let dir = tempfile::tempdir().unwrap();
2373 let path = dir.path().join("magi.toml");
2374 std::fs::write(&path, Config::starter_toml()).unwrap();
2375 let parsed = Config::load(&path).expect("starter config must load");
2376 assert_eq!(parsed.graph.candidates, 3);
2377 assert_eq!(parsed.merge.mode, MergeMode::None);
2378 assert_eq!(parsed.merge.style, MergeStyle::Merge);
2379 assert!(parsed.graph.sessions);
2380 assert_eq!(parsed.graph.timeout_review, 1200);
2381 assert_eq!(parsed.graph.verify_timeout(), 1200);
2382 assert_eq!(parsed.update.mode, UpdateMode::Notify);
2383 }
2384
2385 #[test]
2386 fn release_defaults_to_actions_and_the_starter_documents_it() {
2387 let dir = tempfile::tempdir().unwrap();
2388 let path = dir.path().join("magi.toml");
2389 std::fs::write(&path, Config::starter_toml()).unwrap();
2390 let r = Config::load(&path).unwrap().release;
2391 assert_eq!(r.mode, ReleaseMode::Actions);
2392 assert!(!r.is_local());
2393 assert!(r.commands.is_empty());
2394 assert_eq!(r.timeout_minutes, 30);
2395 assert!(Config::starter_toml().contains("# mode = \"actions\""));
2396 }
2397
2398 #[test]
2399 fn release_local_parses_and_unknown_keys_are_refused() {
2400 let dir = tempfile::tempdir().unwrap();
2401 let path = dir.path().join("magi.toml");
2402 std::fs::write(
2403 &path,
2404 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
2405 )
2406 .unwrap();
2407 let r = Config::load(&path).unwrap().release;
2408 assert!(r.is_local());
2409 assert_eq!(r.commands.len(), 2);
2410 assert_eq!(r.timeout_minutes, 5);
2411 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
2412 assert!(Config::load(&path).is_err());
2413 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
2414 assert!(Config::load(&path).is_err());
2415 }
2416
2417 #[test]
2418 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
2419 let dir = tempfile::tempdir().unwrap();
2420 let path = dir.path().join("magi.toml");
2421 std::fs::write(&path, Config::starter_toml()).unwrap();
2422 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
2423 assert!(Config::starter_toml().contains("# pre_gate = []"));
2424 }
2425
2426 #[test]
2427 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
2428 let starter = Config::starter_toml();
2429 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
2430 assert!(starter.contains("verification independent if timeout_review changes later"));
2431 assert!(starter.contains("# timeout_verify = 1200"));
2432 }
2433
2434 /// A repository whose ruleset forbids merge commits declares that once,
2435 /// here, rather than magi asking GitHub about it on every render (see
2436 /// [`MergeStyle`]'s own doc for why).
2437 #[test]
2438 fn a_repository_can_declare_a_linear_history_merge_style() {
2439 let dir = tempfile::tempdir().unwrap();
2440 let path = dir.path().join("magi.toml");
2441 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
2442 let parsed = Config::load(&path).expect("config must load");
2443 assert_eq!(parsed.merge.style, MergeStyle::Squash);
2444 }
2445
2446 #[test]
2447 fn later_layers_win_and_vars_render() {
2448 let dir = tempfile::tempdir().unwrap();
2449 let machine = dir.path().join("machine.toml");
2450 let project = dir.path().join("magi.toml");
2451 // The machine layer owns the roster...
2452 std::fs::write(
2453 &machine,
2454 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
2455 [graph]\ncandidates = 3\nmax_parallel = 8\n",
2456 )
2457 .unwrap();
2458 // ...and the project layer only states what is repo-specific, plus a
2459 // `[vars]` value interpolated into a command.
2460 std::fs::write(
2461 &project,
2462 "[vars]\ncache = \"/shared\"\n\n\
2463 [graph]\ncandidates = 2\n\n\
2464 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
2465 )
2466 .unwrap();
2467
2468 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
2469 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
2470 assert_eq!(cfg.graph.candidates, 2, "project layer wins");
2471 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
2472 assert_eq!(
2473 cfg.verify.gate,
2474 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
2475 );
2476 // The rendered command is where the cache path is read back from.
2477 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
2478 }
2479
2480 #[test]
2481 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
2482 // An operator who writes no `[graph]` timeout keys at all must still
2483 // land on the hour, not on the five/fifteen minutes this turn used
2484 // to hardcode before it read from config.
2485 let g = Graph::default();
2486 assert_eq!(g.timeout_talk, 3600);
2487
2488 let dir = tempfile::tempdir().unwrap();
2489 let path = dir.path().join("magi.toml");
2490 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
2491 let cfg = Config::load(&path).expect("must load without timeout_talk set");
2492 assert_eq!(cfg.graph.timeout_talk, 3600);
2493 }
2494
2495 #[test]
2496 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
2497 let dir = tempfile::tempdir().unwrap();
2498 let path = dir.path().join("magi.toml");
2499 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
2500 let cfg = Config::load(&path).expect("must load");
2501 assert_eq!(cfg.graph.timeout_talk, 120);
2502 }
2503
2504 #[test]
2505 fn the_disk_defaults_are_the_measurements_made_up_front() {
2506 let cfg = Config::default();
2507 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
2508 assert!(cfg.disk.auto_fold);
2509 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
2510 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
2511 }
2512
2513 #[test]
2514 fn an_unset_disk_section_is_the_safe_default() {
2515 let dir = tempfile::tempdir().unwrap();
2516 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
2517 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
2518 assert_eq!(cfg.disk, Disk::default());
2519 }
2520
2521 #[test]
2522 fn env_is_available_to_templates_with_a_default() {
2523 let dir = tempfile::tempdir().unwrap();
2524 let path = dir.path().join("magi.toml");
2525 // teravars ships no `env`; magi adds it, and the `default` filter has
2526 // to cover the unset case or every machine would need the variable.
2527 //
2528 // Deliberately no named variable: `env` is keyed by the exact spelling
2529 // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
2530 // test asserting `env.PATH` passes on one runner and fails on another.
2531 // The map's non-emptiness is the platform-neutral claim.
2532 std::fs::write(
2533 &path,
2534 "[verify]\n\
2535 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
2536 \"populated={{ env | length > 0 }}\"]\n",
2537 )
2538 .unwrap();
2539 let cfg = Config::load(&path).expect("env lookup must render");
2540 assert_eq!(cfg.verify.gate[0], "cache=fallback");
2541 assert_eq!(cfg.verify.gate[1], "populated=true");
2542 }
2543
2544 #[test]
2545 fn a_broken_template_names_the_file() {
2546 let dir = tempfile::tempdir().unwrap();
2547 let path = dir.path().join("magi.toml");
2548 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
2549 let err = Config::load(&path).expect_err("must not silently ignore");
2550 assert!(err.to_string().contains("teravars"), "{err}");
2551 }
2552
2553 #[test]
2554 fn tera_syntax_in_comments_is_inert() {
2555 // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
2556 // comment may quote template syntax without rendering. Before 0.2.2 this
2557 // load failed: the commented-out braces reached the template parser.
2558 let dir = tempfile::tempdir().unwrap();
2559 let path = dir.path().join("magi.toml");
2560 std::fs::write(
2561 &path,
2562 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
2563 [graph]\ncandidates = 2\n",
2564 )
2565 .unwrap();
2566 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
2567 assert_eq!(cfg.graph.candidates, 2);
2568 }
2569
2570 #[test]
2571 fn opencode_defaults_to_file_delivery() {
2572 let mut s = spec("oc");
2573 s.kind = AgentKind::Opencode;
2574 assert_eq!(s.delivery(), Delivery::File);
2575 s.prompt_delivery = Some(Delivery::Argv);
2576 assert_eq!(s.delivery(), Delivery::Argv);
2577 }
2578 #[test]
2579 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
2580 // Both default on, and that pair is the safety property: `land` takes
2581 // over the watching an operator was doing by hand, `land_approval`
2582 // keeps the irreversible step a human decision. An unattended merge
2583 // needs BOTH flipped, which has to be chosen deliberately twice.
2584 let g = Graph::default();
2585 assert!(
2586 g.land,
2587 "stopping at an open PR left the watching to a human"
2588 );
2589 assert!(
2590 g.land_approval,
2591 "on-by-default land is only defensible while this is also on"
2592 );
2593 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
2594 assert!(
2595 g.hold_contested_merge,
2596 "a contested hand-off must still reach a human when approvals are off"
2597 );
2598 }
2599 #[test]
2600 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
2601 // teravars appends arrays. For an ordered list of seats, or an argv,
2602 // the concatenation is something neither file says - and the operator
2603 // pays for the extra seats by the token.
2604 let dir = tempfile::tempdir().unwrap();
2605 let machine = dir.path().join("machine.toml");
2606 let repo = dir.path().join("magi.toml");
2607 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
2608 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
2609
2610 let err = Config::load_layers(&[machine.clone(), repo.clone()])
2611 .expect_err("two layers naming one array must not merge silently")
2612 .to_string();
2613 assert!(err.contains("roles.implementers"), "{err}");
2614 // Both files are named: the fix is to delete one of them, and the
2615 // operator has to know which two to choose between.
2616 assert!(err.contains("machine.toml"), "{err}");
2617 assert!(err.contains("magi.toml"), "{err}");
2618 }
2619
2620 #[test]
2621 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
2622 // The split the layering exists for: state a preference machine-wide,
2623 // let the repository own its own lists.
2624 let dir = tempfile::tempdir().unwrap();
2625 let machine = dir.path().join("machine.toml");
2626 let repo = dir.path().join("magi.toml");
2627 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
2628 std::fs::write(
2629 &repo,
2630 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
2631 [roles]\nimplementers = [\"oc\"]\n",
2632 )
2633 .unwrap();
2634
2635 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
2636 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
2637 assert_eq!(cfg.roles.implementers, ["oc"]);
2638 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
2639 }
2640
2641 #[test]
2642 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
2643 // The `editorconfig-checker` distribution problem: a shared layer
2644 // wants to add a gate command without erasing the repository's own.
2645 let dir = tempfile::tempdir().unwrap();
2646 let machine = dir.path().join("machine.toml");
2647 let repo = dir.path().join("magi.toml");
2648 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
2649 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2650
2651 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2652 assert_eq!(
2653 cfg.verify.gate,
2654 [
2655 "editorconfig-checker".to_owned(),
2656 "cargo make check".to_owned()
2657 ],
2658 "low-priority (machine) command first, high-priority (repo) command after"
2659 );
2660 }
2661
2662 #[test]
2663 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
2664 let dir = tempfile::tempdir().unwrap();
2665 let machine = dir.path().join("machine.toml");
2666 let repo = dir.path().join("magi.toml");
2667 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
2668 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
2669
2670 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2671 assert_eq!(
2672 cfg.verify.e2e,
2673 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
2674 );
2675 }
2676
2677 #[test]
2678 fn two_layers_declaring_repos_roots_are_both_scanned() {
2679 let dir = tempfile::tempdir().unwrap();
2680 let machine = dir.path().join("machine.toml");
2681 let repo = dir.path().join("magi.toml");
2682 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
2683 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
2684
2685 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2686 assert_eq!(
2687 cfg.repos.roots,
2688 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
2689 );
2690 }
2691
2692 #[test]
2693 fn duplicate_gate_commands_across_layers_both_run() {
2694 // Dropping the duplicate would be a silent surprise; the operator
2695 // sees a slower gate, never a missing one.
2696 let dir = tempfile::tempdir().unwrap();
2697 let machine = dir.path().join("machine.toml");
2698 let repo = dir.path().join("magi.toml");
2699 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
2700 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
2701
2702 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2703 assert_eq!(
2704 cfg.verify.gate,
2705 ["same-command".to_owned(), "same-command".to_owned()]
2706 );
2707 }
2708
2709 #[test]
2710 fn notify_command_is_still_refused_across_two_layers() {
2711 // An argv, not a set: concatenating two of them is not a program.
2712 let dir = tempfile::tempdir().unwrap();
2713 let machine = dir.path().join("machine.toml");
2714 let repo = dir.path().join("magi.toml");
2715 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
2716 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
2717
2718 let err = Config::load_layers(&[machine.clone(), repo.clone()])
2719 .expect_err("an argv split across layers must not concatenate")
2720 .to_string();
2721 assert!(err.contains("notify.command"), "{err}");
2722 assert!(err.contains("machine.toml"), "{err}");
2723 assert!(err.contains("magi.toml"), "{err}");
2724 }
2725
2726 #[test]
2727 fn one_layer_declaring_verify_gate_runs_unchanged() {
2728 // The classification must not change behaviour for the configuration
2729 // this very repository has today: exactly one layer names the gate.
2730 let dir = tempfile::tempdir().unwrap();
2731 let path = dir.path().join("magi.toml");
2732 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2733
2734 let cfg = Config::load(&path).expect("single layer must still load");
2735 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
2736 }
2737
2738 #[test]
2739 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
2740 let dir = tempfile::tempdir().unwrap();
2741 let machine = dir.path().join("machine.toml");
2742 let repo = dir.path().join("magi.toml");
2743 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
2744 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2745 let paths = vec![machine.clone(), repo.clone()];
2746
2747 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
2748 let described =
2749 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
2750 assert!(described.contains("editorconfig-checker && cargo make check"));
2751 assert!(
2752 described.contains(&machine.display().to_string()),
2753 "{described}"
2754 );
2755 assert!(
2756 described.contains(&repo.display().to_string()),
2757 "{described}"
2758 );
2759
2760 // A single contributing layer stays the plain one-line summary.
2761 let single = vec![repo.clone()];
2762 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
2763 let solo_described =
2764 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
2765 assert_eq!(solo_described, "cargo make check");
2766 }
2767}