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