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/// Explicit role assignment. Empty lists are filled in by
155/// [`Config::resolve_roles`] by rotating the roster.
156#[derive(Debug, Clone, Default, Deserialize, Serialize)]
157#[serde(deny_unknown_fields, default)]
158pub struct Roles {
159 /// Agents that implement the task, one worktree each.
160 pub implementers: Vec<String>,
161 /// Agents that rank the candidates blind.
162 pub judges: Vec<String>,
163 /// Agents that review the winning patch.
164 pub reviewers: Vec<String>,
165 /// Agent that applies review findings. Defaults to the winner's author.
166 pub fixer: Option<String>,
167 /// Agent that answers the standing chat's turns (`src/talk.rs`).
168 ///
169 /// Unset picks a `claude` seat, else the first runnable agent in roster
170 /// order (see [`crate::agent::pick`]) - which is roster *order*, not a
171 /// judgement about who converses well. Naming one here matters once an
172 /// agent is also sitting as a judge: the chat is opened far more often
173 /// than any single competition, and every open competes with that judge
174 /// seat for the same account's concurrency. A timeout on an ordinary chat
175 /// turn traced to exactly this - `opus` triple-booked as chatter and judge
176 /// - is what this field exists to let an operator break apart.
177 pub chatter: Option<String>,
178 /// Agent that arranges the queue between polls: `crate::conduct`'s single
179 /// seat, called once per cycle to decide a runnable task's `blocked_by`
180 /// and how a stalled or finished task recovers.
181 ///
182 /// The same precedent as [`Self::chatter`] for a seat that stands alone
183 /// rather than rotating through the roster - resolved through
184 /// [`crate::agent::pick`], so unset falls back to its own default order
185 /// (a claude seat, else the first runnable agent) rather than reusing a
186 /// judge or reviewer seat that the conductor's own poll-cycle cadence
187 /// would otherwise compete with for the same account's concurrency.
188 pub conductor: Option<String>,
189 /// Seats for the design-deliberation stage `graph::Runner::advise` runs
190 /// before `implement`: independent, read-only design proposals gathered
191 /// once a run has a settled task instruction and before any implementer
192 /// touches the repository.
193 ///
194 /// Empty falls back to `judges` rather than to the whole roster: a panel
195 /// trusted to rank patches independently is exactly the panel worth
196 /// asking to sketch a design independently, and an operator who has
197 /// already thought about judge diversity gets advisor diversity for free
198 /// instead of a fourth roster to maintain.
199 pub advisors: Vec<String>,
200}
201
202/// Graph shape and limits.
203#[derive(Debug, Clone, Deserialize, Serialize)]
204#[serde(deny_unknown_fields, default)]
205pub struct Graph {
206 /// Parallel implementations of the same task. **One by default.**
207 ///
208 /// Competition is the thing magi is for, and it is still here - it is just
209 /// no longer what every task buys without being asked. Three days and 13
210 /// runs on this repository, which is the workload these numbers are drawn
211 /// from:
212 ///
213 /// - **0 of 13** competed runs reached a merge. Everything that landed in
214 /// that window went through `magi review` - the cheap half, no
215 /// competition - and passed on the first try.
216 /// - The judges' first choices **split 73% of the time** (8 of 11
217 /// tallies). Candidates that close together make the ranking a weak
218 /// signal for what it costs to produce.
219 /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
220 /// review 28min, **verify 5min** - and verify is the node that caught a
221 /// defect every reviewer had passed as clean. The cheapest step is the
222 /// one that earns its place every time.
223 ///
224 /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
225 /// single-seat default would have shipped the worse implementation in
226 /// roughly a quarter of them. That is exactly why this is a *default* and
227 /// not a removal - `magi run --candidates N` and a per-task seat count are
228 /// how a task that deserves a competition gets one.
229 ///
230 /// A single-candidate run needs no special case: `Runner::review`'s doc
231 /// records that `execute` already degrades to implement -> review -> gate
232 /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
233 /// no two first choices to reconcile and `vote` returns early.
234 pub candidates: usize,
235 /// Independent judges.
236 pub judges: usize,
237 /// Deliberation rounds when the judges' first choices disagree.
238 pub deliberate_rounds: usize,
239 /// Reviewers per review round. **Three by default** - the smallest panel
240 /// a lens cycle (see [`crate::prompt::Lens`]) covers exactly once, so the
241 /// default panel reads the patch for spec compliance, regressions, and
242 /// simplicity without repeating an angle. Review is also the one stage
243 /// [`Self::candidates`]'s doc describes as running on every task
244 /// regardless of competition, which is what makes a panel worth its cost
245 /// here even though `candidates` itself defaults to one.
246 pub reviewers: usize,
247 /// Maximum review+fix rounds before the run is declared blocked.
248 pub review_rounds: usize,
249 /// Maximum agent processes running at once.
250 pub max_parallel: usize,
251 /// Language for the prose the agents write (`en` / `ja` / any language name).
252 pub language: String,
253 /// Keep one CLI conversation per seat, so a judge remembers its own
254 /// argument across deliberation rounds and the fixer remembers its own
255 /// implementation across review rounds.
256 ///
257 /// Sessions are scoped to a *seat*, never to an agent id: the same model
258 /// sitting as implementer and as judge gets two unrelated conversations,
259 /// which is what keeps blind judging blind.
260 pub sessions: bool,
261 /// Per-node timeouts, seconds.
262 pub timeout_implement: u64,
263 /// Per-node timeouts, seconds.
264 pub timeout_judge: u64,
265 /// Per-node timeouts, seconds.
266 pub timeout_review: u64,
267 /// Timeout for `verify.e2e` and `verify.gate`, seconds. Separate from
268 /// [`Self::timeout_review`] so shrinking a reviewer's budget cannot
269 /// silently shrink a real-machine command's budget too — the two used to
270 /// share `timeout_review`, and turning a slow reviewer down cut the
271 /// timeout `cargo test --all-targets` runs under along with it. When
272 /// omitted, preserves legacy configurations by using
273 /// [`Self::timeout_review`]. Set an explicit value to make verification
274 /// independent of later review-seat budget changes.
275 pub timeout_verify: Option<u64>,
276 /// Per-node timeouts, seconds.
277 pub timeout_fix: u64,
278 /// Wall-clock limit for one turn of [`crate::talk`]'s standing
279 /// conversation, seconds.
280 ///
281 /// An hour: the operator is not watching this turn resolve in real time,
282 /// so the budget can match what the work - reading files, running
283 /// commands, checking their output - actually needs rather than what a
284 /// person waiting on a phone can tolerate.
285 pub timeout_talk: u64,
286 /// Retries for an agent invocation that fails or returns nothing usable.
287 pub retries: usize,
288 /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
289 pub worktree_root: Option<PathBuf>,
290 /// After the pull request is open, keep going: watch its checks and
291 /// reviews, run a fix round when they are unhappy, and ask to merge.
292 ///
293 /// On, because stopping at an open pull request left the operator doing
294 /// the watching by hand - six times in the session this was built in - and
295 /// that is the work the loop exists to take. It only engages for
296 /// `merge = "pr"`; every other merge mode ends the run as before.
297 ///
298 /// Turning this on does **not** hand magi the merge button:
299 /// [`Graph::land_approval`] is on too, and nothing merges without an
300 /// explicit answer. Setting both to their non-defaults is the only way to
301 /// get an unattended merge, and it has to be chosen twice.
302 pub land: bool,
303 /// Land rounds - watch, fix, push - before the run is left for a human.
304 pub land_rounds: usize,
305 /// Ask the owner before merging, showing what is about to land.
306 ///
307 /// On, and it is what makes `land` safe to have on: the question carries a
308 /// rendered panel - the diffstat, the patch, the checks, the review
309 /// comments that were addressed, and the subject the squash will use - so
310 /// the decision is made on evidence rather than on trust, from wherever
311 /// the operator happens to be.
312 ///
313 /// Silence is a hold. An unanswered approval never merges, and neither
314 /// does any answer other than the word `merge`.
315 pub land_approval: bool,
316 /// How long to wait for an owner to answer a question before the run is
317 /// abandoned, seconds. A parked run costs nothing, so this is generous;
318 /// it exists so a forgotten question cannot pin a worktree forever.
319 pub answer_timeout: u64,
320 /// What a round does when one or more reviewer seats never answered
321 /// (timeout, crash, unparsable output).
322 pub incomplete_review: IncompleteReviewPolicy,
323 /// Run `verify.e2e` on every round, even one that already has blocking
324 /// findings and another round left to try.
325 ///
326 /// Off by default: a round with a blocking finding and rounds still left
327 /// is going back to the fixer regardless of what `verify.e2e` says, so
328 /// running it first only spends the round's slowest step (minutes, on a
329 /// Rust repo's `cargo test --all-targets`) on a head about to be
330 /// rewritten anyway. `verify.e2e` still runs once a round has no
331 /// blocking findings left (a round cannot go `clean` without it) and the
332 /// final `verify.gate` always runs on the actual tree that would land —
333 /// deferring is about *when* e2e runs mid-loop, never about skipping it.
334 ///
335 /// Set this to restore the old every-round diagnostic behaviour: e2e
336 /// output from a round that still has blocking findings is occasionally
337 /// useful on its own (a runtime failure a reviewer's panel would not
338 /// have caught by reading), and this is the way back to seeing it every
339 /// round instead of only once the panel has nothing left to flag.
340 pub e2e_every_round: bool,
341 /// Run the design-deliberation stage before `implement`: independent
342 /// advisor seats each sketch a design, and (when at least one produced a
343 /// usable proposal) a synthesis blends them into a brief carried in the
344 /// implementer's prompt. See `graph::Runner::advise`.
345 ///
346 /// On by default. A design sketch is a few paragraphs an agent can write
347 /// without touching the repository, where a full implementation is a
348 /// tool loop that re-reads the codebase on every turn - so three
349 /// sketches, gathered once before `implement` starts, cost a fraction of
350 /// a fourth candidate and buy back a form of the same disagreement
351 /// [`Self::candidates`]'s doc describes moving away from being the
352 /// default, on every run rather than only the ones an operator remembers
353 /// to ask for with `--candidates`.
354 pub advise: bool,
355 /// How many independent design proposals the deliberation stage gathers.
356 /// **Three by default** - the same number [`Self::candidates`]'s doc
357 /// names as the point where a fourth judge's first choice stopped
358 /// changing the tally.
359 pub advisors: usize,
360}
361
362impl Default for Graph {
363 fn default() -> Self {
364 Self {
365 candidates: 1,
366 judges: 3,
367 deliberate_rounds: 1,
368 reviewers: 3,
369 review_rounds: 6,
370 max_parallel: 4,
371 language: "en".to_owned(),
372 sessions: true,
373 timeout_implement: 3600,
374 timeout_judge: 1200,
375 timeout_review: 1200,
376 timeout_verify: None,
377 timeout_fix: 1800,
378 timeout_talk: 3600,
379 retries: 1,
380 worktree_root: None,
381 land: true,
382 land_rounds: 4,
383 land_approval: true,
384 answer_timeout: 86_400,
385 incomplete_review: IncompleteReviewPolicy::Block,
386 e2e_every_round: false,
387 advise: true,
388 advisors: 3,
389 }
390 }
391}
392
393impl Graph {
394 /// Effective machine-command budget. Older configuration files had only
395 /// `timeout_review`, which also governed verification, so absence is a
396 /// compatibility fallback rather than a new 1200-second default.
397 pub fn verify_timeout(&self) -> u64 {
398 self.timeout_verify.unwrap_or(self.timeout_review)
399 }
400}
401
402/// What a review round does when a reviewer seat never answered.
403///
404/// A round where half the panel timed out is not evidence of a clean patch —
405/// it is evidence of nothing. The default refuses to call that clean; `warn`
406/// exists for an operator who would rather keep a flaky seat from stalling
407/// every run, and accepts that the gap is on them to read in the report.
408#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
409#[serde(rename_all = "lowercase")]
410pub enum IncompleteReviewPolicy {
411 /// A round with a missing seat is never `clean`: with nothing raised to
412 /// fix, the round is re-reviewed instead of gating; with the max rounds
413 /// exhausted, the run is left `Blocked` rather than declared ready.
414 Block,
415 /// A round with a missing seat can still gate as clean, once every seat
416 /// that *did* answer raised nothing blocking and verification is green.
417 /// The record keeps the gap visible (`magi show`, `magi stats`) even
418 /// though the run does not wait on it.
419 Warn,
420}
421
422/// What to do when vendor-identifying text is found in material shown to judges.
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
424#[serde(rename_all = "lowercase")]
425pub enum LeakPolicy {
426 /// Record the leak, show the patch unmodified.
427 Warn,
428 /// Replace the token with `[REDACTED]` in the presented patch.
429 Redact,
430 /// Abort the run.
431 Fail,
432}
433
434/// Blindness policy.
435///
436/// Commit messages and candidate summaries are *always* stripped of
437/// attribution trailers and redacted — that is where signatures actually
438/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
439/// redaction would corrupt the artifact under judgement.
440#[derive(Debug, Clone, Deserialize, Serialize)]
441#[serde(deny_unknown_fields, default)]
442pub struct Blind {
443 /// Install a per-worktree `commit-msg` hook that deletes attribution
444 /// trailers before they can land in a candidate's history.
445 pub commit_msg_hook: bool,
446 /// Literal, case-insensitive substrings. A line containing any of them is
447 /// dropped from commit messages and summaries; the `commit-msg` hook is
448 /// generated from the same list.
449 pub strip_lines: Vec<String>,
450 /// Case-insensitive substrings that identify a vendor or model.
451 pub vendor_tokens: Vec<String>,
452 /// Policy for vendor tokens found in the patch body.
453 pub on_leak: LeakPolicy,
454 /// Seed for label assignment and per-judge presentation order. Derived from
455 /// the run id when unset; set it to make a run reproducible.
456 pub seed: Option<u64>,
457}
458
459impl Default for Blind {
460 fn default() -> Self {
461 Self {
462 commit_msg_hook: true,
463 strip_lines: [
464 "Co-Authored-By:",
465 "Signed-off-by:",
466 "Assisted-by:",
467 "Generated-by:",
468 "Generated with",
469 "\u{1f916}",
470 ]
471 .iter()
472 .map(|s| (*s).to_owned())
473 .collect(),
474 vendor_tokens: [
475 "claude",
476 "anthropic",
477 "codex",
478 "openai",
479 "chatgpt",
480 "gemini",
481 "grok",
482 "xai",
483 "copilot",
484 "opencode",
485 "qoder",
486 "cursor",
487 "\u{1f916}",
488 ]
489 .iter()
490 .map(|s| (*s).to_owned())
491 .collect(),
492 on_leak: LeakPolicy::Warn,
493 seed: None,
494 }
495 }
496}
497
498/// Shell commands that gate the winner.
499#[derive(Debug, Clone, Default, Deserialize, Serialize)]
500#[serde(deny_unknown_fields, default)]
501pub struct Verify {
502 /// Run in the winner's worktree once per review round. Its output is fed
503 /// back to the fixer. This is the "real machine" leg of the review.
504 pub e2e: Vec<String>,
505 /// Final gate. Must all exit 0 before a merge is attempted.
506 pub gate: Vec<String>,
507 /// Shell used to run the commands above. Defaults to `sh -c`, or
508 /// `cmd /C` when `sh` is not on `PATH`.
509 pub shell: Option<Vec<String>>,
510}
511
512impl Verify {
513 /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
514 /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
515 /// this reads back. One rendering is enough - they all set the same
516 /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
517 /// command is checked before the gate because the e2e rebuilds the crate.
518 pub fn cache_dir(&self) -> Option<PathBuf> {
519 self.e2e
520 .iter()
521 .chain(self.gate.iter())
522 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
523 }
524}
525
526/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
527///
528/// The numbers below come from one incident, not from theory: a machine with
529/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
530/// Three multi-gigabyte classes of junk accumulated side by side - per-run
531/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
532/// each verify round and each implementation wave recompiles the derived
533/// section of the project into, and the outputs of runs that were removed but
534/// whose folders nobody deleted.
535#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
536#[serde(deny_unknown_fields, default)]
537pub struct Disk {
538 /// Free space, in bytes, below which no new run may start: the daemon and
539 /// the `magi run` gate answer with "the disk is full" instead of letting
540 /// the graph fill it the rest of the way. `0` turns the gate off.
541 ///
542 /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
543 /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
544 /// competition triggers and small enough that a 1 TB disk with 100 GB free
545 /// is nowhere near the threshold.
546 pub min_free_bytes: u64,
547 /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
548 /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
549 /// worktrees removed. `0` turns the janitor off.
550 ///
551 /// Default true.
552 pub auto_fold: bool,
553 /// How old a finished run must be before the janitor folds it, seconds.
554 ///
555 /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
556 /// run that `Ready` a week ago is worktrees holding a compile each. Six
557 /// hours is long enough that nobody loses an answer in the gap between
558 /// reading the report and starting from it, and short enough that a backlog
559 /// cannot pile up across two nights.
560 pub fold_grace_secs: u64,
561 /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
562 /// verify commands), in bytes. When the janitor runs and the cache is over
563 /// it, files are dropped oldest-first until it is not. `0` turns pruning
564 /// off - the cache then only ever grows, which is the operator's call.
565 ///
566 /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
567 /// shared cache on top of ~16 GB in the primary target directory and 6.7-
568 /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
569 /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
570 /// pruning only costs the rebuild of the dropped files, not of the world)
571 /// without letting one addled cache swallow the machine.
572 pub cache_limit_bytes: u64,
573}
574
575impl Default for Disk {
576 fn default() -> Self {
577 Self {
578 min_free_bytes: 8 * 1024 * 1024 * 1024,
579 auto_fold: true,
580 fold_grace_secs: 6 * 60 * 60,
581 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
582 }
583 }
584}
585
586/// What to do with the winning branch.
587#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
588#[serde(rename_all = "lowercase")]
589pub enum MergeMode {
590 /// Leave the branch alone and print the merge command matching
591 /// [`Merge::style`].
592 None,
593 /// Merge into the base branch in the primary worktree, using
594 /// [`Merge::style`].
595 Local,
596 /// Push the branch and open a PR with `gh pr create`. Landing this PR
597 /// (`[graph] land`) always squashes — see `land`'s module doc — so
598 /// [`Merge::style`] does not apply here.
599 Pr,
600}
601
602/// How the winning branch is attached to the base branch: what
603/// `mode = "local"` runs, and what `mode = "none"`'s printed guidance tells
604/// the operator to run by hand.
605///
606/// Read from configuration rather than asked of the repository at run time
607/// (e.g. `gh api repos/{owner}/{repo}/rulesets`) for two reasons: it keeps
608/// `mode = "none"`'s guidance a pure function of `RunState`, assertable in a
609/// unit test the same way `land::decide` is kept pure (see that module's
610/// doc), and it works for a base branch that is not hosted on GitHub, or not
611/// reachable at all, at the moment the report is rendered. An operator whose
612/// base branch enforces a ruleset already knows what it allows; declaring it
613/// once here is cheaper than magi re-discovering it, with a network call, on
614/// every render.
615#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
616#[serde(rename_all = "lowercase")]
617pub enum MergeStyle {
618 /// `git merge --no-ff`: every candidate commit lands, plus a merge
619 /// commit that records the merge as its own event in history. Rejected
620 /// by a base branch whose ruleset requires linear history or forbids
621 /// merge commits outright.
622 #[default]
623 Merge,
624 /// `git merge --squash` followed by a commit under an explicit message:
625 /// every candidate commit folds into one, and none of the candidate's
626 /// own placeholder subjects (`magi: candidate A (uncommitted work)`)
627 /// reach the base branch. No merge commit, so this satisfies a linear-
628 /// history ruleset.
629 Squash,
630 /// A fast-forward-only merge: every candidate commit lands verbatim, in
631 /// order, with no merge commit. Only succeeds because the winner was
632 /// already rebased onto the tracked base tip before this runs (see
633 /// `Runner::sync_to_base`) — equivalent to GitHub's "rebase and merge"
634 /// once that has happened.
635 Rebase,
636}
637
638/// Merge policy.
639#[derive(Debug, Clone, Deserialize, Serialize)]
640#[serde(deny_unknown_fields, default)]
641pub struct Merge {
642 /// Default is [`MergeMode::None`]: magi never touches your base branch
643 /// unless you ask it to.
644 pub mode: MergeMode,
645 /// Base branch. Defaults to the branch checked out when the run started.
646 pub base: Option<String>,
647 /// How the winner is attached to `base`; see [`MergeStyle`]. Ignored by
648 /// `mode = "pr"`.
649 pub style: MergeStyle,
650 /// Remote for `mode = "pr"`.
651 pub remote: String,
652 /// After a `mode = "pr"` run lands, open a `chore/release-vX.Y.Z` pull
653 /// request sized to the change by an agent's own judgement, so a version
654 /// bump does not depend on a human remembering to cut one.
655 ///
656 /// On by default. **Turning this off means a merge landed from the phone
657 /// never becomes a release**, so `POST /api/upgrade` keeps reporting
658 /// "already on the newest release" against a `main` that has moved past
659 /// it - the same gap this feature exists to close. Only for a repository
660 /// that wants to keep cutting releases by hand.
661 pub release_bump: bool,
662}
663
664impl Default for Merge {
665 fn default() -> Self {
666 Self {
667 mode: MergeMode::None,
668 base: None,
669 style: MergeStyle::default(),
670 remote: "origin".to_owned(),
671 release_bump: true,
672 }
673 }
674}
675
676/// How magi keeps itself current.
677#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
678#[serde(rename_all = "lowercase")]
679pub enum UpdateMode {
680 /// Never check.
681 Off,
682 /// Check in the background and print a one-line banner when a newer
683 /// release exists.
684 Notify,
685 /// Check and install silently.
686 Install,
687}
688
689/// Self-update policy.
690#[derive(Debug, Clone, Deserialize, Serialize)]
691#[serde(deny_unknown_fields, default)]
692pub struct Update {
693 /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
694 pub mode: UpdateMode,
695 /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
696 pub interval: Option<String>,
697}
698
699impl Default for Update {
700 fn default() -> Self {
701 Self {
702 mode: UpdateMode::Notify,
703 interval: None,
704 }
705 }
706}
707
708/// Top-level configuration.
709#[derive(Debug, Clone, Default, Deserialize, Serialize)]
710#[serde(deny_unknown_fields, default)]
711pub struct Config {
712 /// Agent roster.
713 pub agents: Vec<AgentSpec>,
714 /// Role assignment.
715 pub roles: Roles,
716 /// Graph shape.
717 pub graph: Graph,
718 /// Blindness policy.
719 pub blind: Blind,
720 /// Verification commands.
721 pub verify: Verify,
722 /// Disk hygiene.
723 pub disk: Disk,
724 /// Merge policy.
725 pub merge: Merge,
726 /// Self-update policy.
727 pub update: Update,
728 /// Project-specific text appended to the node prompts.
729 pub prompts: Prompts,
730 /// How the operator is told a run is waiting on them.
731 pub notify: Notify,
732 /// Local repositories the plan surface can start or derive a conversation
733 /// against.
734 pub repos: Repos,
735 /// Policy for the standing conversation ([`crate::talk`]).
736 pub talk: Talk,
737 /// How many runs `magi serve`'s own loop drives at once.
738 pub daemon: Daemon,
739}
740
741/// How the daemon loop itself behaves, as opposed to what one run does.
742///
743/// Machine-layer material in the same sense [`Repos::roots`] is: how many
744/// competitions this machine's own loop is willing to babysit at once is a
745/// fact about the machine running `magi serve`, not about any one
746/// repository's task, so it belongs in `<config_dir>/magi/config.toml`
747/// rather than a repository's own `magi.toml` - though, like `Repos::roots`,
748/// nothing stops a repository from setting it too, since a scalar field
749/// takes whichever layer has the highest precedence.
750#[derive(Debug, Clone, Deserialize, Serialize)]
751#[serde(deny_unknown_fields, default)]
752pub struct Daemon {
753 /// How many runs `magi serve` may have actively in flight at once.
754 /// **One by default** - today's behaviour, one run at a time.
755 ///
756 /// This is a different knob from [`Graph::max_parallel`], and the two
757 /// must not be confused: `max_parallel` bounds how many agent *processes*
758 /// one run starts inside itself (implementers, judges, reviewers -
759 /// candidates competing on a single task); this field bounds how many
760 /// *runs* - whole competitions, each with its own `max_parallel` budget -
761 /// the loop drives side by side, possibly across different tasks and
762 /// different repositories. Raising `max_parallel` buys a bigger panel for
763 /// one task; raising this buys more tasks worked at once. A config file
764 /// that meant one and wrote the other would either starve a competition
765 /// of judges or leave the rest of the backlog waiting for no reason.
766 ///
767 /// A run parked waiting on the operator's land-merge approval - see
768 /// [`crate::land`] - does not hold one of these slots while it waits: the
769 /// whole point of parking there is to let the loop spend the slot on
770 /// something runnable instead of sitting on a decision only a human can
771 /// make. So even at the default of `1`, an approval that comes back does
772 /// not queue behind whatever else the loop happens to be running.
773 pub max_concurrent_runs: usize,
774}
775
776impl Default for Daemon {
777 fn default() -> Self {
778 Self {
779 max_concurrent_runs: 1,
780 }
781 }
782}
783
784/// Where `magi repos` and `GET /api/repos` look for local checkouts.
785///
786/// `roots` is one of the array keys [`array_merge_policy`] marks as
787/// append-across-layers: which checkouts exist in general is a *machine*
788/// fact in the same way the agent roster is - a repository's own `magi.toml`
789/// cannot state where its siblings live before magi has resolved which
790/// repository to read that file from in the first place - but a repository
791/// that genuinely has an extra root worth scanning is not forced to choose
792/// between an error and losing the machine's roots outright. Both layers'
793/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
794/// are still refused.
795#[derive(Debug, Clone, Deserialize, Serialize)]
796#[serde(deny_unknown_fields, default)]
797pub struct Repos {
798 /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
799 /// with a `.git` directory. Empty by default - nothing is scanned unless
800 /// asked to be.
801 pub roots: Vec<PathBuf>,
802 /// How long a scan is trusted before the next request re-scans it,
803 /// seconds. `0` means never trust it: scan on every request. Defaults to
804 /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
805 /// the same reason - a checkout does not usually appear or vanish inside
806 /// a session, so there is little to gain from scanning more often than
807 /// that, and an explicit refresh exists for the moment one does.
808 pub scan_ttl: u64,
809}
810
811impl Default for Repos {
812 fn default() -> Self {
813 Self {
814 roots: Vec::new(),
815 scan_ttl: 86_400,
816 }
817 }
818}
819
820/// Project-specific text appended to each node's prompt.
821///
822/// **Additive by construction.** These fields cannot replace magi's prompts,
823/// only extend them, and that restriction is the whole design. The built-in
824/// prompts carry the invariants the competition rests on: a judging prompt
825/// names no authors, every structured answer must arrive as one fenced `json`
826/// block, and a judge is told not to speculate about who wrote what. A config
827/// that could overwrite them would let a typo silently un-blind the panel or
828/// break the parser, and the symptom would be "the judges got worse" rather
829/// than an error.
830///
831/// Repository-wide context belongs in `AGENTS.md`, which every agent already
832/// reads from the checkout. Use these fields for the things a *magi node*
833/// needs to know and a repository file cannot say - for instance that
834/// reviewers here should ignore formatting because a hook owns it.
835#[derive(Debug, Clone, Default, Deserialize, Serialize)]
836#[serde(deny_unknown_fields, default)]
837pub struct Prompts {
838 /// Appended to every node's prompt.
839 pub all: String,
840 /// Appended for implementers.
841 pub implement: String,
842 /// Appended for judges, both ranking and voting.
843 pub judge: String,
844 /// Appended for reviewers.
845 pub review: String,
846 /// Appended for the fixer.
847 pub fix: String,
848}
849
850impl Prompts {
851 /// The overlay for one node, or `None` when nothing is configured.
852 ///
853 /// `node` is the graph's own node name, so a new node gets no overlay
854 /// rather than the wrong one.
855 pub fn overlay(&self, node: &str) -> Option<String> {
856 let specific = match node {
857 "implement" => &self.implement,
858 "judge" | "vote" | "deliberate" => &self.judge,
859 "review" => &self.review,
860 "fix" => &self.fix,
861 _ => "",
862 };
863 let mut parts: Vec<&str> = Vec::new();
864 for p in [self.all.trim(), specific.trim()] {
865 if !p.is_empty() {
866 parts.push(p);
867 }
868 }
869 if parts.is_empty() {
870 return None;
871 }
872 Some(parts.join("\n\n"))
873 }
874}
875
876/// How the operator is told that a run is waiting on them.
877///
878/// A command rather than a built-in integration: magi is one binary with no
879/// network dependencies, and every operator's notification path is different -
880/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
881/// Shelling out keeps all of them possible and none of them magi's problem.
882#[derive(Debug, Clone, Default, Deserialize, Serialize)]
883#[serde(deny_unknown_fields, default)]
884pub struct Notify {
885 /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
886 /// Empty means no notification - the web UI is then the only surface.
887 pub command: Vec<String>,
888}
889
890/// Policy for [`crate::talk`], the standing conversation.
891#[derive(Debug, Clone, Default, Deserialize, Serialize)]
892#[serde(deny_unknown_fields, default)]
893pub struct Talk {
894 /// Let the conversation's agent edit files in the repository instead of
895 /// filing a task for one. **Off by default** - see
896 /// [`crate::talk`]'s module doc for why an edit made mid-conversation is
897 /// an edit no run and no review can be attributed to, which is exactly
898 /// the property a repository entered in a competition depends on. A
899 /// repository that is never judged - dotfiles, a personal config
900 /// checkout - has nothing to lose by turning this on in its own
901 /// `magi.toml`, and a one-line fix stops costing a queued task to get.
902 pub allow_write: bool,
903}
904
905/// Roles resolved to concrete agent specs for one run.
906#[derive(Debug, Clone)]
907pub struct ResolvedRoles {
908 /// One per candidate.
909 pub implementers: Vec<AgentSpec>,
910 /// One per judge.
911 pub judges: Vec<AgentSpec>,
912 /// One per reviewer slot.
913 pub reviewers: Vec<AgentSpec>,
914 /// Explicit fixer, if configured.
915 pub fixer: Option<AgentSpec>,
916 /// Queue conductor, explicitly selected or resolved by the standalone-seat fallback.
917 pub conductor: AgentSpec,
918}
919
920/// Every array-valued key in a config table, as a dotted path.
921///
922/// Dotted so the error names `roles.implementers` rather than `implementers`:
923/// an operator with three config files needs to know which key, not just that
924/// there was one. `vars` is skipped because it is teravars' own input, merged
925/// on purpose and never deserialised into `Config`.
926fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
927 let mut out = Vec::new();
928 for (k, v) in table {
929 if prefix.is_empty() && k == "vars" {
930 continue;
931 }
932 let path = if prefix.is_empty() {
933 k.clone()
934 } else {
935 format!("{prefix}.{k}")
936 };
937 match v {
938 toml::Value::Array(_) => out.push(path),
939 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
940 _ => {}
941 }
942 }
943 out
944}
945
946/// How an array key behaves when two config layers both declare it.
947#[derive(Debug, Clone, Copy, PartialEq, Eq)]
948enum ArrayMerge {
949 /// Two layers may both declare it; the composed value is the
950 /// low-to-high-priority concatenation teravars already produces (see
951 /// [`Config::load_layers`]'s doc for why that order and no dedup).
952 Append,
953 /// Two layers declaring it is refused; see
954 /// [`Config::refuse_split_arrays`].
955 Replace,
956}
957
958/// The single place that decides, for a dotted array key (as returned by
959/// [`array_keys`]), whether declaring it in two config layers is a
960/// concatenation the operator asked for or a silent accident.
961///
962/// Kept as one match so the whole policy is visible in one place - the same
963/// reason `claude_quota` and `dropped_stream` close their own classification
964/// in one spot elsewhere in this codebase. Anything not listed defaults to
965/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
966/// reasoned about yet, and a new array key added later has to be added here
967/// deliberately to become appendable.
968///
969/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
970/// gate. Concatenating two of them is exactly the checks both layers
971/// wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
972/// live in a shared layer while a repository's own layer adds its own
973/// command, instead of every repository copying the shared command into
974/// its own file.
975/// - `repos.roots` — a set of directories to scan for checkouts. A
976/// repository adding its own root on top of the machine's is additive by
977/// nature, not a replacement of where the machine looks; see
978/// [`Repos::roots`].
979///
980/// Left on the refuse side, and why:
981/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
982/// list of *seats*, not a set. A machine's two implementers plus a
983/// repository's one is three seats nobody asked for and nobody is paying
984/// for on purpose.
985/// - `notify.command` — an argv. Concatenating two argvs does not produce a
986/// program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
987/// - `blind.strip_lines` — technically safe to concatenate (each entry is
988/// matched as an independent substring, so a longer list only strips
989/// *more*), but left on the refuse side anyway: the same list also drives
990/// `commit_msg_hook`'s generated `sed` addresses, where position matters,
991/// and a silent three-layer merge is exactly the kind of surprise
992/// `refuse_split_arrays` exists to catch rather than to reason about
993/// case-by-case. A repository that wants one more stripped phrase restates
994/// the whole list; that restatement is visible in review, an accidental
995/// concatenation would not be.
996fn array_merge_policy(key: &str) -> ArrayMerge {
997 match key {
998 "verify.e2e" | "verify.gate" | "repos.roots" => ArrayMerge::Append,
999 _ => ArrayMerge::Replace,
1000 }
1001}
1002
1003impl Config {
1004 /// Load one file through teravars: Tera rendering, `[vars]` resolution,
1005 /// and the `include = [...]` directive.
1006 pub fn load(path: &Path) -> Result<Self> {
1007 Self::load_layers(&[path.to_path_buf()])
1008 }
1009
1010 /// The Tera render context shared by every layer: `system.*` (from
1011 /// teravars), `env` (magi's own addition - a config that names a shared
1012 /// build-cache directory or a machine-specific path needs
1013 /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
1014 /// derived from the last (highest-priority) path's parent directory.
1015 ///
1016 /// Factored out so [`Config::array_provenance`] can re-render a single
1017 /// layer under the exact same context [`Config::load_layers`] uses for
1018 /// the joint render, rather than drifting from it by accident.
1019 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1020 let mut ctx = teravars::system_context();
1021 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1022 ctx.insert("env", &env);
1023 if let Some(last) = paths.last()
1024 && let Some(dir) = last.parent()
1025 {
1026 ctx.insert("repo", &dir.to_string_lossy());
1027 ctx.insert(
1028 "repo_name",
1029 &dir.file_name().unwrap_or_default().to_string_lossy(),
1030 );
1031 }
1032 ctx
1033 }
1034
1035 /// Load and deep-merge a stack of config files, later files winning.
1036 ///
1037 /// This is why the config is TOML-through-teravars rather than plain serde:
1038 /// the roster is a *machine* fact (which CLIs and plans you pay for) while
1039 /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
1040 /// there). Picking one file and ignoring the other would force every repo
1041 /// to restate the roster.
1042 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1043 let mut engine = teravars::Engine::default();
1044 let ctx = Self::render_ctx(paths);
1045 if paths.len() > 1 {
1046 Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
1047 }
1048 let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
1049 format!(
1050 "rendering config via teravars: {}",
1051 paths
1052 .iter()
1053 .map(|p| p.display().to_string())
1054 .collect::<Vec<_>>()
1055 .join(", ")
1056 )
1057 })?;
1058 let mut table = merged.config;
1059 // `[vars]` is teravars' own input, already resolved into the render
1060 // context; `deny_unknown_fields` must not trip over it.
1061 table.remove("vars");
1062 toml::Value::Table(table)
1063 .try_into()
1064 .context("deserializing magi config")
1065 }
1066
1067 /// Refuse an array that two layers both declare, unless
1068 /// [`array_merge_policy`] says that key is meant to accumulate.
1069 ///
1070 /// teravars **appends** arrays when it merges layers, and that is wrong for
1071 /// most arrays magi has: `implementers` is an ordered list of seats,
1072 /// `notify.command` is an argv. Concatenating two of them yields something
1073 /// nobody wrote - three implementers out of a machine's two and a
1074 /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
1075 ///
1076 /// Replacing instead would be the right merge rule for those keys, but the
1077 /// rule lives in teravars, which several other projects depend on;
1078 /// changing it there is a decision for that crate, not something to fake
1079 /// here by re-reading the files with different semantics and hoping the
1080 /// two paths agree.
1081 ///
1082 /// So magi refuses the ambiguity rather than resolving it silently, for
1083 /// every array key except the short, deliberate list
1084 /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
1085 /// concatenation teravars already produces *is* what both files say, so
1086 /// there is nothing to refuse. The cost of guessing wrong on the refused
1087 /// keys is a roster the operator did not ask for and is paying for by the
1088 /// token; the append keys carry no such risk because every element runs
1089 /// (or every directory is scanned) regardless of order.
1090 fn refuse_split_arrays(
1091 paths: &[PathBuf],
1092 engine: &mut teravars::Engine,
1093 ctx: &teravars::Context,
1094 ) -> Result<()> {
1095 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1096 for path in paths {
1097 let one = teravars::load_merged([path], engine, ctx)
1098 .with_context(|| format!("rendering {}", path.display()))?;
1099 for key in array_keys(&one.config, "") {
1100 if array_merge_policy(&key) == ArrayMerge::Append {
1101 continue;
1102 }
1103 if let Some(first) = seen.get(&key) {
1104 bail!(
1105 "`{key}` is an array declared in two config layers:\n \
1106 {}\n {}\nteravars appends arrays when it merges, so \
1107 magi would run the concatenation of both - which is \
1108 not what either file says. Declare `{key}` in exactly \
1109 one of them.",
1110 first.display(),
1111 path.display()
1112 );
1113 }
1114 seen.insert(key, path.clone());
1115 }
1116 }
1117 Ok(())
1118 }
1119
1120 /// Which layers contributed to a composed, appendable array key (e.g.
1121 /// `"verify.gate"`), in the same low-to-high-priority order
1122 /// [`Config::load_layers`] concatenates them in. Layers that do not
1123 /// declare `key` at all are omitted.
1124 ///
1125 /// This is a **display aid for `magi doctor` only.** The command list
1126 /// that actually runs always comes from the one joint
1127 /// [`teravars::load_merged`] call in `load_layers`, never from this
1128 /// function - the exact hazard [`Config::refuse_split_arrays`] warns
1129 /// about is two merge paths that might disagree, so this function must
1130 /// never become a second source of the *composed* value, only of which
1131 /// file wrote which line in it.
1132 ///
1133 /// Re-rendering each layer alone can, in principle, resolve a
1134 /// `{{ vars.x }}` differently than the joint render would, if `x` is
1135 /// defined in one layer and referenced in another - the same caveat
1136 /// `refuse_split_arrays`'s structural, key-only check already lives with.
1137 /// None of magi's own gate commands cross that line, and a doctor listing
1138 /// is read by a human who can compare it against the joint one printed
1139 /// alongside it, so this is judged worth the simplicity of not
1140 /// threading provenance through the real load path.
1141 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1142 let mut engine = teravars::Engine::default();
1143 let ctx = Self::render_ctx(paths);
1144 let mut out = Vec::new();
1145 for path in paths {
1146 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1147 continue;
1148 };
1149 let mut cur = &one.config;
1150 let mut found = None;
1151 let parts: Vec<&str> = key.split('.').collect();
1152 for (i, part) in parts.iter().enumerate() {
1153 match cur.get(*part) {
1154 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1155 found = Some(a);
1156 break;
1157 }
1158 Some(toml::Value::Table(t)) => cur = t,
1159 _ => break,
1160 }
1161 }
1162 let Some(values) = found else { continue };
1163 let strings: Vec<String> = values
1164 .iter()
1165 .filter_map(|v| v.as_str().map(str::to_owned))
1166 .collect();
1167 if !strings.is_empty() {
1168 out.push((path.clone(), strings));
1169 }
1170 }
1171 out
1172 }
1173
1174 /// Render a composed command list for `magi doctor`: the joined command
1175 /// line the run actually uses, plus - only when more than one layer
1176 /// contributed - which layer wrote which line.
1177 ///
1178 /// A single contributing layer (the common case today) stays the plain
1179 /// one-line summary magi has always printed, `empty` included: that
1180 /// honest "(none — ...)" is what caught a real gate-composition gap
1181 /// before this array could compose at all, and composition should not
1182 /// make the common case noisier.
1183 pub fn describe_composed(
1184 paths: &[PathBuf],
1185 commands: &[String],
1186 key: &str,
1187 empty: &str,
1188 ) -> String {
1189 if commands.is_empty() {
1190 return empty.to_owned();
1191 }
1192 let joined = commands.join(" && ");
1193 let provenance = Self::array_provenance(paths, key);
1194 if provenance.len() <= 1 {
1195 return joined;
1196 }
1197 let mut out = joined;
1198 for (path, cmds) in &provenance {
1199 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1200 }
1201 out
1202 }
1203
1204 /// Resolve the config for `repo`, honouring an explicit `--config` path.
1205 ///
1206 /// Returns the config and the layers it came from, empty for built-in
1207 /// defaults.
1208 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1209 if let Some(p) = explicit {
1210 let paths = vec![p.to_path_buf()];
1211 return Ok((Self::load_layers(&paths)?, paths));
1212 }
1213 let paths = Self::layers(repo);
1214 if paths.is_empty() {
1215 return Ok((Self::autodetected(), paths));
1216 }
1217 Ok((Self::load_layers(&paths)?, paths))
1218 }
1219 /// Environment variable that relocates the machine-wide config layer.
1220 ///
1221 /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
1222 /// of the one under [`dirs::config_dir`]; set it to the empty string and
1223 /// magi reads no machine layer at all.
1224 ///
1225 /// This exists because the machine layer is otherwise unavoidable, and a
1226 /// test that builds a config fixture is not asking for the operator's
1227 /// preferences to be merged into it. Adding `[repos] roots` to the real
1228 /// machine config on a development box turned two passing tests red -
1229 /// `repos_list_returns_name_and_path_for_every_configured_root` and
1230 /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
1231 /// declare `[repos] roots` of their own, which [`Config::layers`] then
1232 /// found in two layers and [`Config::refuse_split_arrays`] correctly
1233 /// refused. CI never saw it: a runner has no machine config, so the suite
1234 /// was green there and red only where somebody actually uses magi.
1235 ///
1236 /// An operator gets the same escape hatch for free: a second machine
1237 /// config, or none, without moving files about.
1238 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
1239
1240 /// Every config layer that applies to `repo`, in increasing precedence.
1241 ///
1242 /// The machine layer is whatever [`Config::machine_layer`] resolves to,
1243 /// which is nothing at all in a test build.
1244 pub fn layers(repo: &Path) -> Vec<PathBuf> {
1245 let mut paths = Vec::new();
1246 paths.extend(Self::machine_layer());
1247 paths.push(repo.join(".magi").join("config.toml"));
1248 paths.push(repo.join("magi.toml"));
1249 paths.retain(|p| p.is_file());
1250 paths
1251 }
1252
1253 /// The machine-wide layer's path, when there is one.
1254 ///
1255 /// **A test build has none unless it names one.** A fixture is a complete
1256 /// statement of the config under test, and the operator's own preferences
1257 /// have no business being merged into it - least of all silently, on one
1258 /// machine, in a suite that is green everywhere else.
1259 #[cfg(test)]
1260 fn machine_layer() -> Option<PathBuf> {
1261 std::env::var(Self::CONFIG_DIR_ENV)
1262 .ok()
1263 .filter(|dir| !dir.trim().is_empty())
1264 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
1265 }
1266
1267 /// The machine-wide layer's path, when there is one.
1268 #[cfg(not(test))]
1269 fn machine_layer() -> Option<PathBuf> {
1270 match std::env::var(Self::CONFIG_DIR_ENV) {
1271 // Named, and empty on purpose: no machine layer.
1272 Ok(dir) if dir.trim().is_empty() => None,
1273 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1274 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1275 }
1276 }
1277
1278 /// Built-in config whose roster is the agent CLIs found on `PATH`.
1279 pub fn autodetected() -> Self {
1280 let mut cfg = Self::default();
1281 for (kind, id, model) in [
1282 (AgentKind::Claude, "opus", Some("opus")),
1283 (AgentKind::Claude, "sonnet", Some("sonnet")),
1284 (AgentKind::Antigravity, "antigravity", None),
1285 (AgentKind::Opencode, "opencode", None),
1286 (AgentKind::Codex, "codex", None),
1287 (AgentKind::Omp, "omp", None),
1288 ] {
1289 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1290 cfg.agents.push(AgentSpec {
1291 id: id.to_owned(),
1292 kind,
1293 model: model.map(str::to_owned),
1294 command: Vec::new(),
1295 extra_args: Vec::new(),
1296 env: BTreeMap::new(),
1297 prompt_delivery: None,
1298 });
1299 }
1300 }
1301 cfg
1302 }
1303
1304 /// The shared build cache the verify commands and the agents both build
1305 /// into, when the config declares one. See [`Verify::cache_dir`].
1306 pub fn cache_dir(&self) -> Option<PathBuf> {
1307 self.verify.cache_dir()
1308 }
1309
1310 /// Look an agent up by id.
1311 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1312 self.agents
1313 .iter()
1314 .find(|a| a.id == id)
1315 .with_context(|| format!("no agent with id `{id}` in the roster"))
1316 }
1317
1318 /// Rotate `count` seats out of `ids`, or out of the whole roster at
1319 /// `offset` when `ids` is empty.
1320 ///
1321 /// The one rotation rule - explicit ids cycle, an empty list rotates the
1322 /// roster - shared by every seat count [`Config::resolve_roles`] fills in,
1323 /// rather than each seat reimplementing it and drifting apart.
1324 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
1325 let mut out = Vec::with_capacity(count);
1326 for i in 0..count {
1327 let spec = if ids.is_empty() {
1328 self.agents[(i + offset) % self.agents.len()].clone()
1329 } else {
1330 self.agent(&ids[i % ids.len()])?.clone()
1331 };
1332 out.push(spec);
1333 }
1334 Ok(out)
1335 }
1336
1337 /// Fill the roles out to the configured widths.
1338 ///
1339 /// An empty role list rotates through the whole roster, so a three-agent
1340 /// roster with `candidates = 3` gives one implementation per agent, and
1341 /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1342 /// author of candidate *i* whenever the roster has more than one agent.
1343 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1344 if self.agents.is_empty() {
1345 bail!(
1346 "agent roster is empty: no agent CLI found on PATH and no \
1347 [[agents]] in the config. Run `magi init` to write a starter \
1348 magi.toml."
1349 );
1350 }
1351 Ok(ResolvedRoles {
1352 implementers: self.rotate(&self.roles.implementers, self.graph.candidates, 0)?,
1353 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
1354 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
1355 fixer: self
1356 .roles
1357 .fixer
1358 .as_deref()
1359 .map(|f| self.agent(f).cloned())
1360 .transpose()?,
1361 // Role resolution validates roster shape, but deliberately does
1362 // not preflight a CLI. The other graph seats have always deferred
1363 // that failure to invocation; doing it only for the conductor
1364 // made otherwise usable graph commands and `doctor` fail as one.
1365 conductor: match self.roles.conductor.as_deref() {
1366 Some(id) => self.agent(id)?.clone(),
1367 // Keep the normal standalone-seat preference when something
1368 // is installed, but retain a roster fallback when it is not.
1369 // Invocation then reports the unavailable CLI in the same
1370 // place it does for every other graph role.
1371 None => crate::agent::pick(&self.agents, None, &crate::agent::installed)
1372 .unwrap_or_else(|_| self.agents[0].clone()),
1373 },
1374 })
1375 }
1376
1377 /// Advisor seats for the design-deliberation stage (see
1378 /// `graph::Runner::advise`): `[roles] advisors` when set, otherwise the
1379 /// judge roster - see [`Roles::advisors`] for why that fallback and not
1380 /// the whole roster.
1381 ///
1382 /// The fallback rotates with `offset = 1`, matching the judges line in
1383 /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
1384 /// `roles.judges`, which is empty whenever judges themselves are
1385 /// unconfigured and rotating the whole roster. Falling back with
1386 /// `offset = 0` there would silently hand the advisors a *different*
1387 /// agent set than the judges an unconfigured run would actually get,
1388 /// which is the one thing [`Roles::advisors`]'s doc promises will not
1389 /// happen.
1390 ///
1391 /// Called lazily from the graph node itself rather than folded into
1392 /// [`Config::resolve_roles`]: unlike the other roles, a failure here must
1393 /// not stop a run from starting at all - the deliberation stage is an
1394 /// enrichment `[graph] advise` can turn off, not a seat later nodes
1395 /// cannot proceed without - and at the point `resolve_roles` runs (before
1396 /// [`crate::run::RunState`] exists, on `Runner::start`) there would be no
1397 /// run yet for a resolution failure to be reported against.
1398 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
1399 if self.agents.is_empty() {
1400 bail!(
1401 "agent roster is empty: no agent CLI found on PATH and no \
1402 [[agents]] in the config. Run `magi init` to write a starter \
1403 magi.toml."
1404 );
1405 }
1406 if !self.roles.advisors.is_empty() {
1407 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
1408 }
1409 self.rotate(&self.roles.judges, self.graph.advisors, 1)
1410 }
1411
1412 /// Shell prefix for [`Verify`] commands.
1413 pub fn shell(&self) -> Vec<String> {
1414 if let Some(s) = &self.verify.shell {
1415 return s.clone();
1416 }
1417 if which("sh") {
1418 vec!["sh".to_owned(), "-c".to_owned()]
1419 } else {
1420 vec!["cmd".to_owned(), "/C".to_owned()]
1421 }
1422 }
1423
1424 /// Starter config, as written by `magi init`.
1425 pub fn starter_toml() -> String {
1426 let detected = Self::autodetected();
1427 let mut s = String::from(
1428 "# magi — blind multi-agent implementation competition.\n\
1429 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
1430 # -> blind judging -> deliberation -> private final vote\n\
1431 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
1432 #\n\
1433 # Rendered by teravars: a `[vars]` table, env\n\
1434 # and system lookups, and `include = [...]` all work. Tera\n\
1435 # braces are live everywhere in this file, but comments are\n\
1436 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
1437 # may quote `{{ ... }}` freely.\n\
1438 #\n\
1439 # Layers deep-merge in increasing\n\
1440 # precedence, so the roster can live once per machine in\n\
1441 # <config_dir>/magi/config.toml and each repo only states its own\n\
1442 # gate:\n\
1443 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
1444 [vars]\n\
1445 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
1446 # Single quotes inside the braces: teravars renders the raw file\n\
1447 # text, so TOML's own \\\" escaping never reaches Tera.\n\
1448 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
1449 );
1450 if detected.agents.is_empty() {
1451 s.push_str(
1452 "# No agent CLI was found on PATH. Fill this in by hand.\n\
1453 # kind = claude | opencode | antigravity | codex | command\n\
1454 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
1455 );
1456 } else {
1457 for a in &detected.agents {
1458 s.push_str("[[agents]]\n");
1459 s.push_str(&format!("id = {:?}\n", a.id));
1460 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
1461 if let Some(m) = &a.model {
1462 s.push_str(&format!("model = {m:?}\n"));
1463 }
1464 s.push('\n');
1465 }
1466 }
1467 s.push_str(
1468 "# Leave a role list empty to rotate through the roster.\n\
1469 [roles]\n\
1470 implementers = []\n\
1471 judges = []\n\
1472 reviewers = []\n\
1473 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\n\
1474 [graph]\n\
1475 candidates = 3\n\
1476 judges = 3\n\
1477 deliberate_rounds = 1\n\
1478 reviewers = 3\n\
1479 review_rounds = 6\n\
1480 max_parallel = 4\n\
1481 language = \"en\"\n\
1482 # One CLI conversation per seat: judges keep their own argument\n\
1483 # across deliberation, the fixer keeps its implementation context.\n\
1484 sessions = true\n\
1485 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
1486 # the final gate inherit this value for compatibility.\n\
1487 timeout_review = 1200\n\
1488 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
1489 # verification independent if timeout_review changes later.\n\
1490 # timeout_verify = 1200\n\n\
1491 [verify]\n\
1492 # Run once per review round in the winner's worktree; failures are\n\
1493 # fed back to the fixer.\n\
1494 e2e = []\n\
1495 # Final gate. Every command must exit 0 before a merge.\n\
1496 gate = []\n\n\
1497 [merge]\n\
1498 # none | local | pr\n\
1499 mode = \"none\"\n\n\
1500 [update]\n\
1501 # off | notify | install — checked in the background, throttled.\n\
1502 mode = \"notify\"\n\
1503 # interval = \"24h\"\n",
1504 );
1505 s
1506 }
1507}
1508
1509/// Is `program` on `PATH`?
1510pub fn which(program: &str) -> bool {
1511 let Some(paths) = std::env::var_os("PATH") else {
1512 return false;
1513 };
1514 let exts: Vec<String> = std::env::var("PATHEXT")
1515 .map(|v| v.split(';').map(|e| e.to_lowercase()).collect())
1516 .unwrap_or_default();
1517 std::env::split_paths(&paths).any(|dir| {
1518 let direct = dir.join(program);
1519 if direct.is_file() {
1520 return true;
1521 }
1522 exts.iter().any(|ext| {
1523 let mut name = program.to_owned();
1524 name.push_str(ext);
1525 dir.join(name).is_file()
1526 })
1527 })
1528}
1529
1530#[cfg(test)]
1531mod tests {
1532 use super::*;
1533
1534 fn spec(id: &str) -> AgentSpec {
1535 AgentSpec {
1536 id: id.to_owned(),
1537 kind: AgentKind::Command,
1538 model: None,
1539 command: vec!["true".to_owned()],
1540 extra_args: Vec::new(),
1541 env: BTreeMap::new(),
1542 prompt_delivery: None,
1543 }
1544 }
1545
1546 #[test]
1547 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
1548 // `timeout_verify` used to not exist: `verify.e2e`/`verify.gate` ran
1549 // under `timeout_review`. A config written before this field existed
1550 // must run exactly as before, which means its default has to be the
1551 // same 1200s `timeout_review` has always defaulted to.
1552 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
1553 assert_eq!(g.timeout_verify, None);
1554 assert_eq!(g.verify_timeout(), 3600);
1555 }
1556
1557 #[test]
1558 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
1559 // The bug this field exists to close: `[graph] timeout_review = 45`
1560 // used to shrink the real-machine `verify.e2e`/`verify.gate` budget
1561 // along with the reviewer seats' own timeout, because both read the
1562 // same field.
1563 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
1564 assert_eq!(g.timeout_review, 45);
1565 assert_eq!(
1566 g.verify_timeout(),
1567 45,
1568 "an omitted legacy value follows review"
1569 );
1570 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
1571 .expect("parse explicit override");
1572 assert_eq!(explicit.verify_timeout(), 1200);
1573 }
1574
1575 #[test]
1576 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
1577 // `deny_unknown_fields` cuts both ways: a config from before
1578 // `timeout_verify`/`e2e_every_round` existed must still parse, with
1579 // both defaulted rather than refused as unknown-in-reverse.
1580 let g: Graph =
1581 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
1582 .expect("an old-shaped [graph] table must still parse");
1583 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
1584 assert!(
1585 !g.e2e_every_round,
1586 "off by default, same as before this field existed"
1587 );
1588 }
1589
1590 #[test]
1591 fn empty_roles_rotate_judges_off_their_own_candidate() {
1592 // Three seats, said out loud: this is a test about *rotation*, and it
1593 // has nothing to say about how many candidates a task buys by default.
1594 let cfg = Config {
1595 agents: vec![spec("a"), spec("b"), spec("c")],
1596 graph: Graph {
1597 candidates: 3,
1598 ..Graph::default()
1599 },
1600 ..Config::default()
1601 };
1602 let roles = cfg.resolve_roles().unwrap();
1603 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
1604 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
1605 assert_eq!(impls, ["a", "b", "c"]);
1606 assert_eq!(judges, ["b", "c", "a"]);
1607 for (i, j) in judges.iter().enumerate() {
1608 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
1609 }
1610 }
1611
1612 #[test]
1613 fn single_agent_roster_fills_every_seat() {
1614 let cfg = Config {
1615 agents: vec![spec("solo")],
1616 graph: Graph {
1617 candidates: 3,
1618 ..Graph::default()
1619 },
1620 ..Config::default()
1621 };
1622 let roles = cfg.resolve_roles().unwrap();
1623 assert_eq!(roles.implementers.len(), 3);
1624 assert!(roles.judges.iter().all(|a| a.id == "solo"));
1625 }
1626
1627 #[test]
1628 fn explicit_roles_win() {
1629 let cfg = Config {
1630 agents: vec![spec("a"), spec("b")],
1631 roles: Roles {
1632 implementers: vec!["b".to_owned()],
1633 judges: vec!["a".to_owned()],
1634 reviewers: Vec::new(),
1635 fixer: Some("a".to_owned()),
1636 ..Roles::default()
1637 },
1638 ..Config::default()
1639 };
1640 let roles = cfg.resolve_roles().unwrap();
1641 assert!(roles.implementers.iter().all(|a| a.id == "b"));
1642 assert!(roles.judges.iter().all(|a| a.id == "a"));
1643 assert_eq!(roles.fixer.unwrap().id, "a");
1644 assert_eq!(roles.conductor.id, "a");
1645 }
1646
1647 #[test]
1648 fn unknown_agent_id_is_an_error() {
1649 let cfg = Config {
1650 agents: vec![spec("a")],
1651 roles: Roles {
1652 judges: vec!["nope".to_owned()],
1653 ..Roles::default()
1654 },
1655 ..Config::default()
1656 };
1657 assert!(cfg.resolve_roles().is_err());
1658 }
1659
1660 #[test]
1661 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
1662 let mut cfg = Config {
1663 agents: vec![spec("a"), spec("b")],
1664 ..Config::default()
1665 };
1666 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
1667
1668 cfg.roles.conductor = Some("b".to_owned());
1669 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
1670
1671 cfg.roles.conductor = Some("missing".to_owned());
1672 assert!(cfg.resolve_roles().is_err());
1673 }
1674
1675 #[test]
1676 fn empty_roster_is_an_error() {
1677 assert!(Config::default().resolve_roles().is_err());
1678 }
1679
1680 #[test]
1681 fn advise_defaults_to_on_with_three_proposals() {
1682 let g = Graph::default();
1683 assert!(g.advise);
1684 assert_eq!(g.advisors, 3);
1685 }
1686
1687 #[test]
1688 fn unset_advisors_falls_back_to_the_judge_roster() {
1689 let cfg = Config {
1690 agents: vec![spec("a"), spec("b")],
1691 roles: Roles {
1692 judges: vec!["b".to_owned()],
1693 ..Roles::default()
1694 },
1695 graph: Graph {
1696 advisors: 2,
1697 ..Graph::default()
1698 },
1699 ..Config::default()
1700 };
1701 let advisors = cfg.advisors().expect("advisors resolve");
1702 assert_eq!(advisors.len(), 2);
1703 assert!(
1704 advisors.iter().all(|a| a.id == "b"),
1705 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
1706 );
1707 }
1708
1709 #[test]
1710 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
1711 let cfg = Config {
1712 agents: vec![spec("a"), spec("b")],
1713 roles: Roles {
1714 judges: vec!["b".to_owned()],
1715 advisors: vec!["a".to_owned()],
1716 ..Roles::default()
1717 },
1718 graph: Graph {
1719 advisors: 2,
1720 ..Graph::default()
1721 },
1722 ..Config::default()
1723 };
1724 let advisors = cfg.advisors().expect("advisors resolve");
1725 assert!(advisors.iter().all(|a| a.id == "a"));
1726 }
1727
1728 /// Neither `[roles] advisors` nor `[roles] judges` set: an unconfigured
1729 /// advisor roster must resolve to the exact same agents an unconfigured
1730 /// judge panel would get - same ids, same rotation offset - or the
1731 /// promise in [`Roles::advisors`]'s doc ("advisor diversity for free")
1732 /// does not actually hold.
1733 #[test]
1734 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
1735 let cfg = Config {
1736 agents: vec![spec("a"), spec("b"), spec("c")],
1737 graph: Graph {
1738 advisors: 3,
1739 judges: 3,
1740 ..Graph::default()
1741 },
1742 ..Config::default()
1743 };
1744 let advisors = cfg.advisors().expect("advisors resolve");
1745 let judges = cfg.resolve_roles().expect("roles resolve").judges;
1746 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
1747 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
1748 assert_eq!(
1749 advisor_ids, judge_ids,
1750 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
1751 );
1752 }
1753
1754 #[test]
1755 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
1756 let cfg = Config {
1757 agents: vec![spec("a")],
1758 roles: Roles {
1759 advisors: vec!["nope".to_owned()],
1760 ..Roles::default()
1761 },
1762 graph: Graph {
1763 advisors: 1,
1764 ..Graph::default()
1765 },
1766 ..Config::default()
1767 };
1768 let err = cfg.advisors().expect_err("`nope` is not in the roster");
1769 assert!(format!("{err:#}").contains("nope"));
1770 }
1771
1772 #[test]
1773 fn repos_default_to_no_roots_and_a_day_of_trust() {
1774 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
1775 assert_eq!(Config::default().repos.scan_ttl, 86_400);
1776 }
1777
1778 #[test]
1779 fn a_config_file_with_no_repos_table_still_loads() {
1780 let dir = tempfile::tempdir().unwrap();
1781 let path = dir.path().join("magi.toml");
1782 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
1783 let cfg = Config::load(&path).expect("must load without [repos]");
1784 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
1785 assert_eq!(cfg.repos.scan_ttl, 86_400);
1786 }
1787
1788 /// A fixture is the whole config under test.
1789 ///
1790 /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
1791 /// a machine where somebody had written `<config_dir>/magi/config.toml`
1792 /// the suite silently loaded it as the lowest layer. Adding `[repos]
1793 /// roots` there turned two web tests red - their fixtures declare
1794 /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
1795 /// array key spread across two layers. CI stayed green throughout,
1796 /// because a runner has no such file: the suite failed only where magi is
1797 /// actually used.
1798 ///
1799 /// So a test build has no machine layer unless it asks for one, and this
1800 /// is that promise. Written against a real file at the real location so
1801 /// it fails if `machine_layer` starts reading it again.
1802 #[test]
1803 fn a_test_build_does_not_read_the_operators_machine_config() {
1804 let repo = tempfile::tempdir().unwrap();
1805 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
1806
1807 let layers = Config::layers(repo.path());
1808 assert_eq!(
1809 layers,
1810 vec![repo.path().join("magi.toml")],
1811 "only the fixture's own file may be a layer"
1812 );
1813 if let Some(real) = dirs::config_dir() {
1814 let machine = real.join("magi").join("config.toml");
1815 assert!(
1816 !layers.contains(&machine),
1817 "the operator's {} must not be a layer in a test build",
1818 machine.display()
1819 );
1820 }
1821 }
1822
1823 #[test]
1824 fn starter_toml_loads_through_teravars() {
1825 let dir = tempfile::tempdir().unwrap();
1826 let path = dir.path().join("magi.toml");
1827 std::fs::write(&path, Config::starter_toml()).unwrap();
1828 let parsed = Config::load(&path).expect("starter config must load");
1829 assert_eq!(parsed.graph.candidates, 3);
1830 assert_eq!(parsed.merge.mode, MergeMode::None);
1831 assert_eq!(parsed.merge.style, MergeStyle::Merge);
1832 assert!(parsed.graph.sessions);
1833 assert_eq!(parsed.graph.timeout_review, 1200);
1834 assert_eq!(parsed.graph.verify_timeout(), 1200);
1835 assert_eq!(parsed.update.mode, UpdateMode::Notify);
1836 }
1837
1838 #[test]
1839 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
1840 let starter = Config::starter_toml();
1841 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
1842 assert!(starter.contains("verification independent if timeout_review changes later"));
1843 assert!(starter.contains("# timeout_verify = 1200"));
1844 }
1845
1846 /// A repository whose ruleset forbids merge commits declares that once,
1847 /// here, rather than magi asking GitHub about it on every render (see
1848 /// [`MergeStyle`]'s own doc for why).
1849 #[test]
1850 fn a_repository_can_declare_a_linear_history_merge_style() {
1851 let dir = tempfile::tempdir().unwrap();
1852 let path = dir.path().join("magi.toml");
1853 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
1854 let parsed = Config::load(&path).expect("config must load");
1855 assert_eq!(parsed.merge.style, MergeStyle::Squash);
1856 }
1857
1858 #[test]
1859 fn later_layers_win_and_vars_render() {
1860 let dir = tempfile::tempdir().unwrap();
1861 let machine = dir.path().join("machine.toml");
1862 let project = dir.path().join("magi.toml");
1863 // The machine layer owns the roster...
1864 std::fs::write(
1865 &machine,
1866 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
1867 [graph]\ncandidates = 3\nmax_parallel = 8\n",
1868 )
1869 .unwrap();
1870 // ...and the project layer only states what is repo-specific, plus a
1871 // `[vars]` value interpolated into a command.
1872 std::fs::write(
1873 &project,
1874 "[vars]\ncache = \"/shared\"\n\n\
1875 [graph]\ncandidates = 2\n\n\
1876 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
1877 )
1878 .unwrap();
1879
1880 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
1881 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
1882 assert_eq!(cfg.graph.candidates, 2, "project layer wins");
1883 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
1884 assert_eq!(
1885 cfg.verify.gate,
1886 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
1887 );
1888 // The rendered command is where the cache path is read back from.
1889 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
1890 }
1891
1892 #[test]
1893 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
1894 // An operator who writes no `[graph]` timeout keys at all must still
1895 // land on the hour, not on the five/fifteen minutes this turn used
1896 // to hardcode before it read from config.
1897 let g = Graph::default();
1898 assert_eq!(g.timeout_talk, 3600);
1899
1900 let dir = tempfile::tempdir().unwrap();
1901 let path = dir.path().join("magi.toml");
1902 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
1903 let cfg = Config::load(&path).expect("must load without timeout_talk set");
1904 assert_eq!(cfg.graph.timeout_talk, 3600);
1905 }
1906
1907 #[test]
1908 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
1909 let dir = tempfile::tempdir().unwrap();
1910 let path = dir.path().join("magi.toml");
1911 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
1912 let cfg = Config::load(&path).expect("must load");
1913 assert_eq!(cfg.graph.timeout_talk, 120);
1914 }
1915
1916 #[test]
1917 fn the_disk_defaults_are_the_measurements_made_up_front() {
1918 let cfg = Config::default();
1919 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
1920 assert!(cfg.disk.auto_fold);
1921 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
1922 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
1923 }
1924
1925 #[test]
1926 fn an_unset_disk_section_is_the_safe_default() {
1927 let dir = tempfile::tempdir().unwrap();
1928 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
1929 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
1930 assert_eq!(cfg.disk, Disk::default());
1931 }
1932
1933 #[test]
1934 fn env_is_available_to_templates_with_a_default() {
1935 let dir = tempfile::tempdir().unwrap();
1936 let path = dir.path().join("magi.toml");
1937 // teravars ships no `env`; magi adds it, and the `default` filter has
1938 // to cover the unset case or every machine would need the variable.
1939 //
1940 // Deliberately no named variable: `env` is keyed by the exact spelling
1941 // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
1942 // test asserting `env.PATH` passes on one runner and fails on another.
1943 // The map's non-emptiness is the platform-neutral claim.
1944 std::fs::write(
1945 &path,
1946 "[verify]\n\
1947 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
1948 \"populated={{ env | length > 0 }}\"]\n",
1949 )
1950 .unwrap();
1951 let cfg = Config::load(&path).expect("env lookup must render");
1952 assert_eq!(cfg.verify.gate[0], "cache=fallback");
1953 assert_eq!(cfg.verify.gate[1], "populated=true");
1954 }
1955
1956 #[test]
1957 fn a_broken_template_names_the_file() {
1958 let dir = tempfile::tempdir().unwrap();
1959 let path = dir.path().join("magi.toml");
1960 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
1961 let err = Config::load(&path).expect_err("must not silently ignore");
1962 assert!(err.to_string().contains("teravars"), "{err}");
1963 }
1964
1965 #[test]
1966 fn tera_syntax_in_comments_is_inert() {
1967 // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
1968 // comment may quote template syntax without rendering. Before 0.2.2 this
1969 // load failed: the commented-out braces reached the template parser.
1970 let dir = tempfile::tempdir().unwrap();
1971 let path = dir.path().join("magi.toml");
1972 std::fs::write(
1973 &path,
1974 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
1975 [graph]\ncandidates = 2\n",
1976 )
1977 .unwrap();
1978 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
1979 assert_eq!(cfg.graph.candidates, 2);
1980 }
1981
1982 #[test]
1983 fn opencode_defaults_to_file_delivery() {
1984 let mut s = spec("oc");
1985 s.kind = AgentKind::Opencode;
1986 assert_eq!(s.delivery(), Delivery::File);
1987 s.prompt_delivery = Some(Delivery::Argv);
1988 assert_eq!(s.delivery(), Delivery::Argv);
1989 }
1990 #[test]
1991 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
1992 // Both default on, and that pair is the safety property: `land` takes
1993 // over the watching an operator was doing by hand, `land_approval`
1994 // keeps the irreversible step a human decision. An unattended merge
1995 // needs BOTH flipped, which has to be chosen deliberately twice.
1996 let g = Graph::default();
1997 assert!(
1998 g.land,
1999 "stopping at an open PR left the watching to a human"
2000 );
2001 assert!(
2002 g.land_approval,
2003 "on-by-default land is only defensible while this is also on"
2004 );
2005 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
2006 }
2007 #[test]
2008 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
2009 // teravars appends arrays. For an ordered list of seats, or an argv,
2010 // the concatenation is something neither file says - and the operator
2011 // pays for the extra seats by the token.
2012 let dir = tempfile::tempdir().unwrap();
2013 let machine = dir.path().join("machine.toml");
2014 let repo = dir.path().join("magi.toml");
2015 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
2016 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
2017
2018 let err = Config::load_layers(&[machine.clone(), repo.clone()])
2019 .expect_err("two layers naming one array must not merge silently")
2020 .to_string();
2021 assert!(err.contains("roles.implementers"), "{err}");
2022 // Both files are named: the fix is to delete one of them, and the
2023 // operator has to know which two to choose between.
2024 assert!(err.contains("machine.toml"), "{err}");
2025 assert!(err.contains("magi.toml"), "{err}");
2026 }
2027
2028 #[test]
2029 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
2030 // The split the layering exists for: state a preference machine-wide,
2031 // let the repository own its own lists.
2032 let dir = tempfile::tempdir().unwrap();
2033 let machine = dir.path().join("machine.toml");
2034 let repo = dir.path().join("magi.toml");
2035 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
2036 std::fs::write(
2037 &repo,
2038 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
2039 [roles]\nimplementers = [\"oc\"]\n",
2040 )
2041 .unwrap();
2042
2043 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
2044 assert_eq!(cfg.roles.chatter.as_deref(), Some("opus"));
2045 assert_eq!(cfg.roles.implementers, ["oc"]);
2046 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
2047 }
2048
2049 #[test]
2050 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
2051 // The `editorconfig-checker` distribution problem: a shared layer
2052 // wants to add a gate command without erasing the repository's own.
2053 let dir = tempfile::tempdir().unwrap();
2054 let machine = dir.path().join("machine.toml");
2055 let repo = dir.path().join("magi.toml");
2056 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
2057 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2058
2059 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2060 assert_eq!(
2061 cfg.verify.gate,
2062 [
2063 "editorconfig-checker".to_owned(),
2064 "cargo make check".to_owned()
2065 ],
2066 "low-priority (machine) command first, high-priority (repo) command after"
2067 );
2068 }
2069
2070 #[test]
2071 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
2072 let dir = tempfile::tempdir().unwrap();
2073 let machine = dir.path().join("machine.toml");
2074 let repo = dir.path().join("magi.toml");
2075 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
2076 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
2077
2078 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2079 assert_eq!(
2080 cfg.verify.e2e,
2081 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
2082 );
2083 }
2084
2085 #[test]
2086 fn two_layers_declaring_repos_roots_are_both_scanned() {
2087 let dir = tempfile::tempdir().unwrap();
2088 let machine = dir.path().join("machine.toml");
2089 let repo = dir.path().join("magi.toml");
2090 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
2091 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
2092
2093 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2094 assert_eq!(
2095 cfg.repos.roots,
2096 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
2097 );
2098 }
2099
2100 #[test]
2101 fn duplicate_gate_commands_across_layers_both_run() {
2102 // Dropping the duplicate would be a silent surprise; the operator
2103 // sees a slower gate, never a missing one.
2104 let dir = tempfile::tempdir().unwrap();
2105 let machine = dir.path().join("machine.toml");
2106 let repo = dir.path().join("magi.toml");
2107 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
2108 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
2109
2110 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2111 assert_eq!(
2112 cfg.verify.gate,
2113 ["same-command".to_owned(), "same-command".to_owned()]
2114 );
2115 }
2116
2117 #[test]
2118 fn notify_command_is_still_refused_across_two_layers() {
2119 // An argv, not a set: concatenating two of them is not a program.
2120 let dir = tempfile::tempdir().unwrap();
2121 let machine = dir.path().join("machine.toml");
2122 let repo = dir.path().join("magi.toml");
2123 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
2124 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
2125
2126 let err = Config::load_layers(&[machine.clone(), repo.clone()])
2127 .expect_err("an argv split across layers must not concatenate")
2128 .to_string();
2129 assert!(err.contains("notify.command"), "{err}");
2130 assert!(err.contains("machine.toml"), "{err}");
2131 assert!(err.contains("magi.toml"), "{err}");
2132 }
2133
2134 #[test]
2135 fn one_layer_declaring_verify_gate_runs_unchanged() {
2136 // The classification must not change behaviour for the configuration
2137 // this very repository has today: exactly one layer names the gate.
2138 let dir = tempfile::tempdir().unwrap();
2139 let path = dir.path().join("magi.toml");
2140 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2141
2142 let cfg = Config::load(&path).expect("single layer must still load");
2143 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
2144 }
2145
2146 #[test]
2147 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
2148 let dir = tempfile::tempdir().unwrap();
2149 let machine = dir.path().join("machine.toml");
2150 let repo = dir.path().join("magi.toml");
2151 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
2152 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2153 let paths = vec![machine.clone(), repo.clone()];
2154
2155 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
2156 let described =
2157 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
2158 assert!(described.contains("editorconfig-checker && cargo make check"));
2159 assert!(
2160 described.contains(&machine.display().to_string()),
2161 "{described}"
2162 );
2163 assert!(
2164 described.contains(&repo.display().to_string()),
2165 "{described}"
2166 );
2167
2168 // A single contributing layer stays the plain one-line summary.
2169 let single = vec![repo.clone()];
2170 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
2171 let solo_described =
2172 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
2173 assert_eq!(solo_described, "cargo make check");
2174 }
2175}