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 /// Arbitrary command. The escape hatch, and what the test suite drives.
35 Command,
36}
37
38impl AgentKind {
39 /// Executable that must be on `PATH` for this kind, if any.
40 pub fn program(self) -> Option<&'static str> {
41 match self {
42 Self::Claude => Some("claude"),
43 Self::Opencode => Some("opencode"),
44 Self::Antigravity => Some("agy"),
45 Self::Codex => Some("codex"),
46 Self::Command => None,
47 }
48 }
49
50 /// Lowercase name as written in the config file.
51 pub fn as_str(self) -> &'static str {
52 match self {
53 Self::Claude => "claude",
54 Self::Opencode => "opencode",
55 Self::Antigravity => "antigravity",
56 Self::Codex => "codex",
57 Self::Command => "command",
58 }
59 }
60}
61
62/// How the prompt reaches the agent process.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
64#[serde(rename_all = "lowercase")]
65pub enum Delivery {
66 /// Piped on stdin.
67 Stdin,
68 /// Passed as a positional argument. Beware OS command-line limits.
69 Argv,
70 /// Written to a file; the agent is told to read it. No length limit.
71 File,
72}
73
74/// One addressable agent in the roster.
75#[derive(Debug, Clone, Deserialize, Serialize)]
76#[serde(deny_unknown_fields)]
77pub struct AgentSpec {
78 /// Stable identifier used by `[roles]` and by the stats tables.
79 pub id: String,
80 /// Which CLI to drive.
81 pub kind: AgentKind,
82 /// Model passed through to the CLI (`--model` / `-m`). CLI default if unset.
83 #[serde(default)]
84 pub model: Option<String>,
85 /// `kind = "command"` only: argv. Supports `{prompt_file}`, `{cwd}`,
86 /// `{label}`, `{session}` placeholders.
87 #[serde(default)]
88 pub command: Vec<String>,
89 /// Extra arguments appended to the built command line.
90 #[serde(default)]
91 pub extra_args: Vec<String>,
92 /// Extra environment variables for the child process.
93 #[serde(default)]
94 pub env: BTreeMap<String, String>,
95 /// Override the per-kind prompt delivery default.
96 #[serde(default)]
97 pub prompt_delivery: Option<Delivery>,
98}
99
100impl AgentSpec {
101 /// Default prompt delivery for this agent.
102 ///
103 /// `opencode` and `agy` take the prompt as an argument, which on Windows
104 /// caps out around 32 KiB — well under a judging prompt carrying three
105 /// patches — so both get a file instead.
106 pub fn delivery(&self) -> Delivery {
107 self.prompt_delivery.unwrap_or(match self.kind {
108 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
109 // `codex exec -` reads the prompt from stdin, so the whole
110 // instruction arrives without an argv length limit and without a
111 // tool round-trip to open a file.
112 AgentKind::Codex => Delivery::Stdin,
113 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
114 })
115 }
116
117 /// Human-facing label, e.g. `opus (claude:opus)`.
118 pub fn display(&self) -> String {
119 match &self.model {
120 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
121 None => format!("{} ({})", self.id, self.kind.as_str()),
122 }
123 }
124}
125
126/// Explicit role assignment. Empty lists are filled in by
127/// [`Config::resolve_roles`] by rotating the roster.
128#[derive(Debug, Clone, Default, Deserialize, Serialize)]
129#[serde(deny_unknown_fields, default)]
130pub struct Roles {
131 /// Agents that implement the task, one worktree each.
132 pub implementers: Vec<String>,
133 /// Agents that rank the candidates blind.
134 pub judges: Vec<String>,
135 /// Agents that review the winning patch.
136 pub reviewers: Vec<String>,
137 /// Agent that applies review findings. Defaults to the winner's author.
138 pub fixer: Option<String>,
139 /// Agent that runs the `magi plan` interview and the browser conversation.
140 ///
141 /// Unset picks a `claude` seat, else the first runnable agent in roster
142 /// order - which is roster *order*, not a judgement about who interviews
143 /// well. Naming one here is worth it because the interview is the one node
144 /// a human sits through: the model that asks good questions is not
145 /// necessarily the one that writes the best patch, and on a phone there is
146 /// no `--agent` to type.
147 pub planner: Option<String>,
148 /// Agent that answers the resident chat's quick turns (`src/chat.rs`),
149 /// distinct from `planner` on purpose.
150 ///
151 /// Unset falls back to `planner`, which was the only behaviour before
152 /// this field existed - so an existing config that named a planner needs
153 /// no change to keep working. Splitting it out matters once `planner` is
154 /// also carrying a judge seat: the resident chat is opened far more often
155 /// than `magi plan`, and every open competes with that judge seat for the
156 /// same account's concurrency. A timeout on an ordinary chat turn traced
157 /// to exactly this - `opus` triple-booked as planner, chatter, and judge
158 /// - is what this field exists to let an operator break apart.
159 pub chatter: Option<String>,
160 /// Seats for `magi plan`'s design-deliberation stage (see
161 /// [`crate::advise`]): independent, read-only design proposals gathered
162 /// between the interview and the task file it files.
163 ///
164 /// Empty falls back to `judges` rather than to the whole roster: a panel
165 /// trusted to rank patches independently is exactly the panel worth
166 /// asking to sketch a design independently, and an operator who has
167 /// already thought about judge diversity gets advisor diversity for free
168 /// instead of a fourth roster to maintain.
169 pub advisors: Vec<String>,
170}
171
172/// Graph shape and limits.
173#[derive(Debug, Clone, Deserialize, Serialize)]
174#[serde(deny_unknown_fields, default)]
175pub struct Graph {
176 /// Parallel implementations of the same task. **One by default.**
177 ///
178 /// Competition is the thing magi is for, and it is still here - it is just
179 /// no longer what every task buys without being asked. Three days and 13
180 /// runs on this repository, which is the workload these numbers are drawn
181 /// from:
182 ///
183 /// - **0 of 13** competed runs reached a merge. Everything that landed in
184 /// that window went through `magi review` - the cheap half, no
185 /// competition - and passed on the first try.
186 /// - The judges' first choices **split 73% of the time** (8 of 11
187 /// tallies). Candidates that close together make the ranking a weak
188 /// signal for what it costs to produce.
189 /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
190 /// review 28min, **verify 5min** - and verify is the node that caught a
191 /// defect every reviewer had passed as clean. The cheapest step is the
192 /// one that earns its place every time.
193 ///
194 /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
195 /// single-seat default would have shipped the worse implementation in
196 /// roughly a quarter of them. That is exactly why this is a *default* and
197 /// not a removal - `magi run --candidates N` and a per-task seat count are
198 /// how a task that deserves a competition gets one.
199 ///
200 /// A single-candidate run needs no special case: `Runner::review`'s doc
201 /// records that `execute` already degrades to implement -> review -> gate
202 /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
203 /// no two first choices to reconcile and `vote` returns early.
204 pub candidates: usize,
205 /// Independent judges.
206 pub judges: usize,
207 /// Deliberation rounds when the judges' first choices disagree.
208 pub deliberate_rounds: usize,
209 /// Reviewers per review round.
210 pub reviewers: usize,
211 /// Maximum review+fix rounds before the run is declared blocked.
212 pub review_rounds: usize,
213 /// Maximum agent processes running at once.
214 pub max_parallel: usize,
215 /// Language for the prose the agents write (`en` / `ja` / any language name).
216 pub language: String,
217 /// Keep one CLI conversation per seat, so a judge remembers its own
218 /// argument across deliberation rounds and the fixer remembers its own
219 /// implementation across review rounds.
220 ///
221 /// Sessions are scoped to a *seat*, never to an agent id: the same model
222 /// sitting as implementer and as judge gets two unrelated conversations,
223 /// which is what keeps blind judging blind.
224 pub sessions: bool,
225 /// Per-node timeouts, seconds.
226 pub timeout_implement: u64,
227 /// Per-node timeouts, seconds.
228 pub timeout_judge: u64,
229 /// Per-node timeouts, seconds.
230 pub timeout_review: u64,
231 /// Per-node timeouts, seconds.
232 pub timeout_fix: u64,
233 /// Retries for an agent invocation that fails or returns nothing usable.
234 pub retries: usize,
235 /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
236 pub worktree_root: Option<PathBuf>,
237 /// After the pull request is open, keep going: watch its checks and
238 /// reviews, run a fix round when they are unhappy, and ask to merge.
239 ///
240 /// On, because stopping at an open pull request left the operator doing
241 /// the watching by hand - six times in the session this was built in - and
242 /// that is the work the loop exists to take. It only engages for
243 /// `merge = "pr"`; every other merge mode ends the run as before.
244 ///
245 /// Turning this on does **not** hand magi the merge button:
246 /// [`Graph::land_approval`] is on too, and nothing merges without an
247 /// explicit answer. Setting both to their non-defaults is the only way to
248 /// get an unattended merge, and it has to be chosen twice.
249 pub land: bool,
250 /// Land rounds - watch, fix, push - before the run is left for a human.
251 pub land_rounds: usize,
252 /// Ask the owner before merging, showing what is about to land.
253 ///
254 /// On, and it is what makes `land` safe to have on: the question carries a
255 /// rendered panel - the diffstat, the patch, the checks, the review
256 /// comments that were addressed, and the subject the squash will use - so
257 /// the decision is made on evidence rather than on trust, from wherever
258 /// the operator happens to be.
259 ///
260 /// Silence is a hold. An unanswered approval never merges, and neither
261 /// does any answer other than the word `merge`.
262 pub land_approval: bool,
263 /// How long to wait for an owner to answer a question before the run is
264 /// abandoned, seconds. A parked run costs nothing, so this is generous;
265 /// it exists so a forgotten question cannot pin a worktree forever.
266 pub answer_timeout: u64,
267 /// What a round does when one or more reviewer seats never answered
268 /// (timeout, crash, unparsable output).
269 pub incomplete_review: IncompleteReviewPolicy,
270 /// Run `magi plan`'s design-deliberation stage: independent advisors
271 /// sketch a design each, headless, and the planner seat synthesizes them
272 /// into the task file's `## Context` and `## Change`. See
273 /// [`crate::advise`].
274 ///
275 /// On by default, and that is the point of this whole stage: candidate
276 /// diversity moved here from `implement` (see [`Graph::candidates`]'s
277 /// doc) precisely because a design sketch is a few paragraphs, not a
278 /// tool loop - so the competition magi is for is cheap enough to run on
279 /// every task again, not just the ones an operator remembers to ask for.
280 pub advise: bool,
281 /// How many independent design proposals the deliberation stage gathers.
282 /// **Three by default** - the number [`Graph::candidates`]'s doc names as
283 /// the point where a fourth judge's first choice stopped changing the
284 /// tally.
285 pub advisors: usize,
286}
287
288impl Default for Graph {
289 fn default() -> Self {
290 Self {
291 candidates: 1,
292 judges: 3,
293 deliberate_rounds: 1,
294 reviewers: 2,
295 review_rounds: 6,
296 max_parallel: 4,
297 language: "en".to_owned(),
298 sessions: true,
299 timeout_implement: 3600,
300 timeout_judge: 1200,
301 timeout_review: 1200,
302 timeout_fix: 1800,
303 retries: 1,
304 worktree_root: None,
305 land: true,
306 land_rounds: 4,
307 land_approval: true,
308 answer_timeout: 86_400,
309 incomplete_review: IncompleteReviewPolicy::Block,
310 advise: true,
311 advisors: 3,
312 }
313 }
314}
315
316/// What a review round does when a reviewer seat never answered.
317///
318/// A round where half the panel timed out is not evidence of a clean patch —
319/// it is evidence of nothing. The default refuses to call that clean; `warn`
320/// exists for an operator who would rather keep a flaky seat from stalling
321/// every run, and accepts that the gap is on them to read in the report.
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
323#[serde(rename_all = "lowercase")]
324pub enum IncompleteReviewPolicy {
325 /// A round with a missing seat is never `clean`: with nothing raised to
326 /// fix, the round is re-reviewed instead of gating; with the max rounds
327 /// exhausted, the run is left `Blocked` rather than declared ready.
328 Block,
329 /// A round with a missing seat can still gate as clean, once every seat
330 /// that *did* answer raised nothing blocking and verification is green.
331 /// The record keeps the gap visible (`magi show`, `magi stats`) even
332 /// though the run does not wait on it.
333 Warn,
334}
335
336/// What to do when vendor-identifying text is found in material shown to judges.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
338#[serde(rename_all = "lowercase")]
339pub enum LeakPolicy {
340 /// Record the leak, show the patch unmodified.
341 Warn,
342 /// Replace the token with `[REDACTED]` in the presented patch.
343 Redact,
344 /// Abort the run.
345 Fail,
346}
347
348/// Blindness policy.
349///
350/// Commit messages and candidate summaries are *always* stripped of
351/// attribution trailers and redacted — that is where signatures actually
352/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
353/// redaction would corrupt the artifact under judgement.
354#[derive(Debug, Clone, Deserialize, Serialize)]
355#[serde(deny_unknown_fields, default)]
356pub struct Blind {
357 /// Install a per-worktree `commit-msg` hook that deletes attribution
358 /// trailers before they can land in a candidate's history.
359 pub commit_msg_hook: bool,
360 /// Literal, case-insensitive substrings. A line containing any of them is
361 /// dropped from commit messages and summaries; the `commit-msg` hook is
362 /// generated from the same list.
363 pub strip_lines: Vec<String>,
364 /// Case-insensitive substrings that identify a vendor or model.
365 pub vendor_tokens: Vec<String>,
366 /// Policy for vendor tokens found in the patch body.
367 pub on_leak: LeakPolicy,
368 /// Seed for label assignment and per-judge presentation order. Derived from
369 /// the run id when unset; set it to make a run reproducible.
370 pub seed: Option<u64>,
371}
372
373impl Default for Blind {
374 fn default() -> Self {
375 Self {
376 commit_msg_hook: true,
377 strip_lines: [
378 "Co-Authored-By:",
379 "Signed-off-by:",
380 "Assisted-by:",
381 "Generated-by:",
382 "Generated with",
383 "\u{1f916}",
384 ]
385 .iter()
386 .map(|s| (*s).to_owned())
387 .collect(),
388 vendor_tokens: [
389 "claude",
390 "anthropic",
391 "codex",
392 "openai",
393 "chatgpt",
394 "gemini",
395 "grok",
396 "xai",
397 "copilot",
398 "opencode",
399 "qoder",
400 "cursor",
401 "\u{1f916}",
402 ]
403 .iter()
404 .map(|s| (*s).to_owned())
405 .collect(),
406 on_leak: LeakPolicy::Warn,
407 seed: None,
408 }
409 }
410}
411
412/// Shell commands that gate the winner.
413#[derive(Debug, Clone, Default, Deserialize, Serialize)]
414#[serde(deny_unknown_fields, default)]
415pub struct Verify {
416 /// Run in the winner's worktree once per review round. Its output is fed
417 /// back to the fixer. This is the "real machine" leg of the review.
418 pub e2e: Vec<String>,
419 /// Final gate. Must all exit 0 before a merge is attempted.
420 pub gate: Vec<String>,
421 /// Shell used to run the commands above. Defaults to `sh -c`, or
422 /// `cmd /C` when `sh` is not on `PATH`.
423 pub shell: Option<Vec<String>>,
424}
425
426impl Verify {
427 /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
428 /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
429 /// this reads back. One rendering is enough - they all set the same
430 /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
431 /// command is checked before the gate because the e2e rebuilds the crate.
432 pub fn cache_dir(&self) -> Option<PathBuf> {
433 self.e2e
434 .iter()
435 .chain(self.gate.iter())
436 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
437 }
438}
439
440/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
441///
442/// The numbers below come from one incident, not from theory: a machine with
443/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
444/// Three multi-gigabyte classes of junk accumulated side by side - per-run
445/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
446/// each verify round and each implementation wave recompiles the derived
447/// section of the project into, and the outputs of runs that were removed but
448/// whose folders nobody deleted.
449#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
450#[serde(deny_unknown_fields, default)]
451pub struct Disk {
452 /// Free space, in bytes, below which no new run may start: the daemon and
453 /// the `magi run` gate answer with "the disk is full" instead of letting
454 /// the graph fill it the rest of the way. `0` turns the gate off.
455 ///
456 /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
457 /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
458 /// competition triggers and small enough that a 1 TB disk with 100 GB free
459 /// is nowhere near the threshold.
460 pub min_free_bytes: u64,
461 /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
462 /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
463 /// worktrees removed. `0` turns the janitor off.
464 ///
465 /// Default true.
466 pub auto_fold: bool,
467 /// How old a finished run must be before the janitor folds it, seconds.
468 ///
469 /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
470 /// run that `Ready` a week ago is worktrees holding a compile each. Six
471 /// hours is long enough that nobody loses an answer in the gap between
472 /// reading the report and starting from it, and short enough that a backlog
473 /// cannot pile up across two nights.
474 pub fold_grace_secs: u64,
475 /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
476 /// verify commands), in bytes. When the janitor runs and the cache is over
477 /// it, files are dropped oldest-first until it is not. `0` turns pruning
478 /// off - the cache then only ever grows, which is the operator's call.
479 ///
480 /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
481 /// shared cache on top of ~16 GB in the primary target directory and 6.7-
482 /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
483 /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
484 /// pruning only costs the rebuild of the dropped files, not of the world)
485 /// without letting one addled cache swallow the machine.
486 pub cache_limit_bytes: u64,
487}
488
489impl Default for Disk {
490 fn default() -> Self {
491 Self {
492 min_free_bytes: 8 * 1024 * 1024 * 1024,
493 auto_fold: true,
494 fold_grace_secs: 6 * 60 * 60,
495 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
496 }
497 }
498}
499
500/// What to do with the winning branch.
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
502#[serde(rename_all = "lowercase")]
503pub enum MergeMode {
504 /// Leave the branch alone and print the merge command.
505 None,
506 /// `git merge --no-ff` into the base branch in the primary worktree.
507 Local,
508 /// Push the branch and open a PR with `gh pr create`.
509 Pr,
510}
511
512/// Merge policy.
513#[derive(Debug, Clone, Deserialize, Serialize)]
514#[serde(deny_unknown_fields, default)]
515pub struct Merge {
516 /// Default is [`MergeMode::None`]: magi never touches your base branch
517 /// unless you ask it to.
518 pub mode: MergeMode,
519 /// Base branch. Defaults to the branch checked out when the run started.
520 pub base: Option<String>,
521 /// Remote for `mode = "pr"`.
522 pub remote: String,
523}
524
525impl Default for Merge {
526 fn default() -> Self {
527 Self {
528 mode: MergeMode::None,
529 base: None,
530 remote: "origin".to_owned(),
531 }
532 }
533}
534
535/// How magi keeps itself current.
536#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
537#[serde(rename_all = "lowercase")]
538pub enum UpdateMode {
539 /// Never check.
540 Off,
541 /// Check in the background and print a one-line banner when a newer
542 /// release exists.
543 Notify,
544 /// Check and install silently.
545 Install,
546}
547
548/// Self-update policy.
549#[derive(Debug, Clone, Deserialize, Serialize)]
550#[serde(deny_unknown_fields, default)]
551pub struct Update {
552 /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
553 pub mode: UpdateMode,
554 /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
555 pub interval: Option<String>,
556}
557
558impl Default for Update {
559 fn default() -> Self {
560 Self {
561 mode: UpdateMode::Notify,
562 interval: None,
563 }
564 }
565}
566
567/// Top-level configuration.
568#[derive(Debug, Clone, Default, Deserialize, Serialize)]
569#[serde(deny_unknown_fields, default)]
570pub struct Config {
571 /// Agent roster.
572 pub agents: Vec<AgentSpec>,
573 /// Role assignment.
574 pub roles: Roles,
575 /// Graph shape.
576 pub graph: Graph,
577 /// Blindness policy.
578 pub blind: Blind,
579 /// Verification commands.
580 pub verify: Verify,
581 /// Disk hygiene.
582 pub disk: Disk,
583 /// Merge policy.
584 pub merge: Merge,
585 /// Self-update policy.
586 pub update: Update,
587 /// Project-specific text appended to the node prompts.
588 pub prompts: Prompts,
589 /// How the operator is told a run is waiting on them.
590 pub notify: Notify,
591 /// Local repositories the plan surface can start or derive a conversation
592 /// against.
593 pub repos: Repos,
594}
595
596/// Where `magi plan` and the browser interview look for a repository other
597/// than the one they were started against.
598///
599/// `roots` is one of the array keys [`array_merge_policy`] marks as
600/// append-across-layers: which checkouts exist in general is a *machine*
601/// fact in the same way the agent roster is - a repository's own `magi.toml`
602/// cannot state where its siblings live before magi has resolved which
603/// repository to read that file from in the first place - but a repository
604/// that genuinely has an extra root worth scanning is not forced to choose
605/// between an error and losing the machine's roots outright. Both layers'
606/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
607/// are still refused.
608#[derive(Debug, Clone, Deserialize, Serialize)]
609#[serde(deny_unknown_fields, default)]
610pub struct Repos {
611 /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
612 /// with a `.git` directory. Empty by default - nothing is scanned unless
613 /// asked to be.
614 pub roots: Vec<PathBuf>,
615 /// How long a scan is trusted before the next request re-scans it,
616 /// seconds. `0` means never trust it: scan on every request. Defaults to
617 /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
618 /// the same reason - a checkout does not usually appear or vanish inside
619 /// a session, so there is little to gain from scanning more often than
620 /// that, and an explicit refresh exists for the moment one does.
621 pub scan_ttl: u64,
622}
623
624impl Default for Repos {
625 fn default() -> Self {
626 Self {
627 roots: Vec::new(),
628 scan_ttl: 86_400,
629 }
630 }
631}
632
633/// Project-specific text appended to each node's prompt.
634///
635/// **Additive by construction.** These fields cannot replace magi's prompts,
636/// only extend them, and that restriction is the whole design. The built-in
637/// prompts carry the invariants the competition rests on: a judging prompt
638/// names no authors, every structured answer must arrive as one fenced `json`
639/// block, and a judge is told not to speculate about who wrote what. A config
640/// that could overwrite them would let a typo silently un-blind the panel or
641/// break the parser, and the symptom would be "the judges got worse" rather
642/// than an error.
643///
644/// Repository-wide context belongs in `AGENTS.md`, which every agent already
645/// reads from the checkout. Use these fields for the things a *magi node*
646/// needs to know and a repository file cannot say - for instance that
647/// reviewers here should ignore formatting because a hook owns it.
648#[derive(Debug, Clone, Default, Deserialize, Serialize)]
649#[serde(deny_unknown_fields, default)]
650pub struct Prompts {
651 /// Appended to every node's prompt.
652 pub all: String,
653 /// Appended for implementers.
654 pub implement: String,
655 /// Appended for judges, both ranking and voting.
656 pub judge: String,
657 /// Appended for reviewers.
658 pub review: String,
659 /// Appended for the fixer.
660 pub fix: String,
661}
662
663impl Prompts {
664 /// The overlay for one node, or `None` when nothing is configured.
665 ///
666 /// `node` is the graph's own node name, so a new node gets no overlay
667 /// rather than the wrong one.
668 pub fn overlay(&self, node: &str) -> Option<String> {
669 let specific = match node {
670 "implement" => &self.implement,
671 "judge" | "vote" | "deliberate" => &self.judge,
672 "review" => &self.review,
673 "fix" => &self.fix,
674 _ => "",
675 };
676 let mut parts: Vec<&str> = Vec::new();
677 for p in [self.all.trim(), specific.trim()] {
678 if !p.is_empty() {
679 parts.push(p);
680 }
681 }
682 if parts.is_empty() {
683 return None;
684 }
685 Some(parts.join("\n\n"))
686 }
687}
688
689/// How the operator is told that a run is waiting on them.
690///
691/// A command rather than a built-in integration: magi is one binary with no
692/// network dependencies, and every operator's notification path is different -
693/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
694/// Shelling out keeps all of them possible and none of them magi's problem.
695#[derive(Debug, Clone, Default, Deserialize, Serialize)]
696#[serde(deny_unknown_fields, default)]
697pub struct Notify {
698 /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
699 /// Empty means no notification - the web UI is then the only surface.
700 pub command: Vec<String>,
701}
702
703/// Roles resolved to concrete agent specs for one run.
704#[derive(Debug, Clone)]
705pub struct ResolvedRoles {
706 /// One per candidate.
707 pub implementers: Vec<AgentSpec>,
708 /// One per judge.
709 pub judges: Vec<AgentSpec>,
710 /// One per reviewer slot.
711 pub reviewers: Vec<AgentSpec>,
712 /// Explicit fixer, if configured.
713 pub fixer: Option<AgentSpec>,
714}
715
716/// Every array-valued key in a config table, as a dotted path.
717///
718/// Dotted so the error names `roles.implementers` rather than `implementers`:
719/// an operator with three config files needs to know which key, not just that
720/// there was one. `vars` is skipped because it is teravars' own input, merged
721/// on purpose and never deserialised into `Config`.
722fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
723 let mut out = Vec::new();
724 for (k, v) in table {
725 if prefix.is_empty() && k == "vars" {
726 continue;
727 }
728 let path = if prefix.is_empty() {
729 k.clone()
730 } else {
731 format!("{prefix}.{k}")
732 };
733 match v {
734 toml::Value::Array(_) => out.push(path),
735 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
736 _ => {}
737 }
738 }
739 out
740}
741
742/// How an array key behaves when two config layers both declare it.
743#[derive(Debug, Clone, Copy, PartialEq, Eq)]
744enum ArrayMerge {
745 /// Two layers may both declare it; the composed value is the
746 /// low-to-high-priority concatenation teravars already produces (see
747 /// [`Config::load_layers`]'s doc for why that order and no dedup).
748 Append,
749 /// Two layers declaring it is refused; see
750 /// [`Config::refuse_split_arrays`].
751 Replace,
752}
753
754/// The single place that decides, for a dotted array key (as returned by
755/// [`array_keys`]), whether declaring it in two config layers is a
756/// concatenation the operator asked for or a silent accident.
757///
758/// Kept as one match so the whole policy is visible in one place - the same
759/// reason `claude_quota` and `dropped_stream` close their own classification
760/// in one spot elsewhere in this codebase. Anything not listed defaults to
761/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
762/// reasoned about yet, and a new array key added later has to be added here
763/// deliberately to become appendable.
764///
765/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
766/// gate. Concatenating two of them is exactly the checks both layers
767/// wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
768/// live in a shared layer while a repository's own layer adds its own
769/// command, instead of every repository copying the shared command into
770/// its own file.
771/// - `repos.roots` — a set of directories to scan for checkouts. A
772/// repository adding its own root on top of the machine's is additive by
773/// nature, not a replacement of where the machine looks; see
774/// [`Repos::roots`].
775///
776/// Left on the refuse side, and why:
777/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
778/// list of *seats*, not a set. A machine's two implementers plus a
779/// repository's one is three seats nobody asked for and nobody is paying
780/// for on purpose.
781/// - `notify.command` — an argv. Concatenating two argvs does not produce a
782/// program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
783/// - `blind.strip_lines` — technically safe to concatenate (each entry is
784/// matched as an independent substring, so a longer list only strips
785/// *more*), but left on the refuse side anyway: the same list also drives
786/// `commit_msg_hook`'s generated `sed` addresses, where position matters,
787/// and a silent three-layer merge is exactly the kind of surprise
788/// `refuse_split_arrays` exists to catch rather than to reason about
789/// case-by-case. A repository that wants one more stripped phrase restates
790/// the whole list; that restatement is visible in review, an accidental
791/// concatenation would not be.
792fn array_merge_policy(key: &str) -> ArrayMerge {
793 match key {
794 "verify.e2e" | "verify.gate" | "repos.roots" => ArrayMerge::Append,
795 _ => ArrayMerge::Replace,
796 }
797}
798
799impl Config {
800 /// Load one file through teravars: Tera rendering, `[vars]` resolution,
801 /// and the `include = [...]` directive.
802 pub fn load(path: &Path) -> Result<Self> {
803 Self::load_layers(&[path.to_path_buf()])
804 }
805
806 /// The Tera render context shared by every layer: `system.*` (from
807 /// teravars), `env` (magi's own addition - a config that names a shared
808 /// build-cache directory or a machine-specific path needs
809 /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
810 /// derived from the last (highest-priority) path's parent directory.
811 ///
812 /// Factored out so [`Config::array_provenance`] can re-render a single
813 /// layer under the exact same context [`Config::load_layers`] uses for
814 /// the joint render, rather than drifting from it by accident.
815 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
816 let mut ctx = teravars::system_context();
817 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
818 ctx.insert("env", &env);
819 if let Some(last) = paths.last()
820 && let Some(dir) = last.parent()
821 {
822 ctx.insert("repo", &dir.to_string_lossy());
823 ctx.insert(
824 "repo_name",
825 &dir.file_name().unwrap_or_default().to_string_lossy(),
826 );
827 }
828 ctx
829 }
830
831 /// Load and deep-merge a stack of config files, later files winning.
832 ///
833 /// This is why the config is TOML-through-teravars rather than plain serde:
834 /// the roster is a *machine* fact (which CLIs and plans you pay for) while
835 /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
836 /// there). Picking one file and ignoring the other would force every repo
837 /// to restate the roster.
838 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
839 let mut engine = teravars::Engine::default();
840 let ctx = Self::render_ctx(paths);
841 if paths.len() > 1 {
842 Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
843 }
844 let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
845 format!(
846 "rendering config via teravars: {}",
847 paths
848 .iter()
849 .map(|p| p.display().to_string())
850 .collect::<Vec<_>>()
851 .join(", ")
852 )
853 })?;
854 let mut table = merged.config;
855 // `[vars]` is teravars' own input, already resolved into the render
856 // context; `deny_unknown_fields` must not trip over it.
857 table.remove("vars");
858 toml::Value::Table(table)
859 .try_into()
860 .context("deserializing magi config")
861 }
862
863 /// Refuse an array that two layers both declare, unless
864 /// [`array_merge_policy`] says that key is meant to accumulate.
865 ///
866 /// teravars **appends** arrays when it merges layers, and that is wrong for
867 /// most arrays magi has: `implementers` is an ordered list of seats,
868 /// `notify.command` is an argv. Concatenating two of them yields something
869 /// nobody wrote - three implementers out of a machine's two and a
870 /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
871 ///
872 /// Replacing instead would be the right merge rule for those keys, but the
873 /// rule lives in teravars, which several other projects depend on;
874 /// changing it there is a decision for that crate, not something to fake
875 /// here by re-reading the files with different semantics and hoping the
876 /// two paths agree.
877 ///
878 /// So magi refuses the ambiguity rather than resolving it silently, for
879 /// every array key except the short, deliberate list
880 /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
881 /// concatenation teravars already produces *is* what both files say, so
882 /// there is nothing to refuse. The cost of guessing wrong on the refused
883 /// keys is a roster the operator did not ask for and is paying for by the
884 /// token; the append keys carry no such risk because every element runs
885 /// (or every directory is scanned) regardless of order.
886 fn refuse_split_arrays(
887 paths: &[PathBuf],
888 engine: &mut teravars::Engine,
889 ctx: &teravars::Context,
890 ) -> Result<()> {
891 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
892 for path in paths {
893 let one = teravars::load_merged([path], engine, ctx)
894 .with_context(|| format!("rendering {}", path.display()))?;
895 for key in array_keys(&one.config, "") {
896 if array_merge_policy(&key) == ArrayMerge::Append {
897 continue;
898 }
899 if let Some(first) = seen.get(&key) {
900 bail!(
901 "`{key}` is an array declared in two config layers:\n \
902 {}\n {}\nteravars appends arrays when it merges, so \
903 magi would run the concatenation of both - which is \
904 not what either file says. Declare `{key}` in exactly \
905 one of them.",
906 first.display(),
907 path.display()
908 );
909 }
910 seen.insert(key, path.clone());
911 }
912 }
913 Ok(())
914 }
915
916 /// Which layers contributed to a composed, appendable array key (e.g.
917 /// `"verify.gate"`), in the same low-to-high-priority order
918 /// [`Config::load_layers`] concatenates them in. Layers that do not
919 /// declare `key` at all are omitted.
920 ///
921 /// This is a **display aid for `magi doctor` only.** The command list
922 /// that actually runs always comes from the one joint
923 /// [`teravars::load_merged`] call in `load_layers`, never from this
924 /// function - the exact hazard [`Config::refuse_split_arrays`] warns
925 /// about is two merge paths that might disagree, so this function must
926 /// never become a second source of the *composed* value, only of which
927 /// file wrote which line in it.
928 ///
929 /// Re-rendering each layer alone can, in principle, resolve a
930 /// `{{ vars.x }}` differently than the joint render would, if `x` is
931 /// defined in one layer and referenced in another - the same caveat
932 /// `refuse_split_arrays`'s structural, key-only check already lives with.
933 /// None of magi's own gate commands cross that line, and a doctor listing
934 /// is read by a human who can compare it against the joint one printed
935 /// alongside it, so this is judged worth the simplicity of not
936 /// threading provenance through the real load path.
937 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
938 let mut engine = teravars::Engine::default();
939 let ctx = Self::render_ctx(paths);
940 let mut out = Vec::new();
941 for path in paths {
942 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
943 continue;
944 };
945 let mut cur = &one.config;
946 let mut found = None;
947 let parts: Vec<&str> = key.split('.').collect();
948 for (i, part) in parts.iter().enumerate() {
949 match cur.get(*part) {
950 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
951 found = Some(a);
952 break;
953 }
954 Some(toml::Value::Table(t)) => cur = t,
955 _ => break,
956 }
957 }
958 let Some(values) = found else { continue };
959 let strings: Vec<String> = values
960 .iter()
961 .filter_map(|v| v.as_str().map(str::to_owned))
962 .collect();
963 if !strings.is_empty() {
964 out.push((path.clone(), strings));
965 }
966 }
967 out
968 }
969
970 /// Render a composed command list for `magi doctor`: the joined command
971 /// line the run actually uses, plus - only when more than one layer
972 /// contributed - which layer wrote which line.
973 ///
974 /// A single contributing layer (the common case today) stays the plain
975 /// one-line summary magi has always printed, `empty` included: that
976 /// honest "(none — ...)" is what caught a real gate-composition gap
977 /// before this array could compose at all, and composition should not
978 /// make the common case noisier.
979 pub fn describe_composed(
980 paths: &[PathBuf],
981 commands: &[String],
982 key: &str,
983 empty: &str,
984 ) -> String {
985 if commands.is_empty() {
986 return empty.to_owned();
987 }
988 let joined = commands.join(" && ");
989 let provenance = Self::array_provenance(paths, key);
990 if provenance.len() <= 1 {
991 return joined;
992 }
993 let mut out = joined;
994 for (path, cmds) in &provenance {
995 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
996 }
997 out
998 }
999
1000 /// Resolve the config for `repo`, honouring an explicit `--config` path.
1001 ///
1002 /// Returns the config and the layers it came from, empty for built-in
1003 /// defaults.
1004 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1005 if let Some(p) = explicit {
1006 let paths = vec![p.to_path_buf()];
1007 return Ok((Self::load_layers(&paths)?, paths));
1008 }
1009 let paths = Self::layers(repo);
1010 if paths.is_empty() {
1011 return Ok((Self::autodetected(), paths));
1012 }
1013 Ok((Self::load_layers(&paths)?, paths))
1014 }
1015 /// Environment variable that relocates the machine-wide config layer.
1016 ///
1017 /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
1018 /// of the one under [`dirs::config_dir`]; set it to the empty string and
1019 /// magi reads no machine layer at all.
1020 ///
1021 /// This exists because the machine layer is otherwise unavoidable, and a
1022 /// test that builds a config fixture is not asking for the operator's
1023 /// preferences to be merged into it. Adding `[repos] roots` to the real
1024 /// machine config on a development box turned two passing tests red -
1025 /// `repos_list_returns_name_and_path_for_every_configured_root` and
1026 /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
1027 /// declare `[repos] roots` of their own, which [`Config::layers`] then
1028 /// found in two layers and [`Config::refuse_split_arrays`] correctly
1029 /// refused. CI never saw it: a runner has no machine config, so the suite
1030 /// was green there and red only where somebody actually uses magi.
1031 ///
1032 /// An operator gets the same escape hatch for free: a second machine
1033 /// config, or none, without moving files about.
1034 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
1035
1036 /// Every config layer that applies to `repo`, in increasing precedence.
1037 ///
1038 /// The machine layer is whatever [`Config::machine_layer`] resolves to,
1039 /// which is nothing at all in a test build.
1040 pub fn layers(repo: &Path) -> Vec<PathBuf> {
1041 let mut paths = Vec::new();
1042 paths.extend(Self::machine_layer());
1043 paths.push(repo.join(".magi").join("config.toml"));
1044 paths.push(repo.join("magi.toml"));
1045 paths.retain(|p| p.is_file());
1046 paths
1047 }
1048
1049 /// The machine-wide layer's path, when there is one.
1050 ///
1051 /// **A test build has none unless it names one.** A fixture is a complete
1052 /// statement of the config under test, and the operator's own preferences
1053 /// have no business being merged into it - least of all silently, on one
1054 /// machine, in a suite that is green everywhere else.
1055 #[cfg(test)]
1056 fn machine_layer() -> Option<PathBuf> {
1057 std::env::var(Self::CONFIG_DIR_ENV)
1058 .ok()
1059 .filter(|dir| !dir.trim().is_empty())
1060 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
1061 }
1062
1063 /// The machine-wide layer's path, when there is one.
1064 #[cfg(not(test))]
1065 fn machine_layer() -> Option<PathBuf> {
1066 match std::env::var(Self::CONFIG_DIR_ENV) {
1067 // Named, and empty on purpose: no machine layer.
1068 Ok(dir) if dir.trim().is_empty() => None,
1069 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1070 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1071 }
1072 }
1073
1074 /// Built-in config whose roster is the agent CLIs found on `PATH`.
1075 pub fn autodetected() -> Self {
1076 let mut cfg = Self::default();
1077 for (kind, id, model) in [
1078 (AgentKind::Claude, "opus", Some("opus")),
1079 (AgentKind::Claude, "sonnet", Some("sonnet")),
1080 (AgentKind::Antigravity, "antigravity", None),
1081 (AgentKind::Opencode, "opencode", None),
1082 (AgentKind::Codex, "codex", None),
1083 ] {
1084 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1085 cfg.agents.push(AgentSpec {
1086 id: id.to_owned(),
1087 kind,
1088 model: model.map(str::to_owned),
1089 command: Vec::new(),
1090 extra_args: Vec::new(),
1091 env: BTreeMap::new(),
1092 prompt_delivery: None,
1093 });
1094 }
1095 }
1096 cfg
1097 }
1098
1099 /// The shared build cache the verify commands and the agents both build
1100 /// into, when the config declares one. See [`Verify::cache_dir`].
1101 pub fn cache_dir(&self) -> Option<PathBuf> {
1102 self.verify.cache_dir()
1103 }
1104
1105 /// Look an agent up by id.
1106 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1107 self.agents
1108 .iter()
1109 .find(|a| a.id == id)
1110 .with_context(|| format!("no agent with id `{id}` in the roster"))
1111 }
1112
1113 /// Rotate `count` seats out of `ids`, or out of the whole roster at
1114 /// `offset` when `ids` is empty.
1115 ///
1116 /// Shared by [`Config::resolve_roles`] and [`Config::advisors`] so the
1117 /// same rotation rule - explicit ids cycle, an empty list rotates the
1118 /// roster - governs every seat count magi fills in, rather than each
1119 /// caller reimplementing it and drifting apart.
1120 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
1121 let mut out = Vec::with_capacity(count);
1122 for i in 0..count {
1123 let spec = if ids.is_empty() {
1124 self.agents[(i + offset) % self.agents.len()].clone()
1125 } else {
1126 self.agent(&ids[i % ids.len()])?.clone()
1127 };
1128 out.push(spec);
1129 }
1130 Ok(out)
1131 }
1132
1133 /// Fill the roles out to the configured widths.
1134 ///
1135 /// An empty role list rotates through the whole roster, so a three-agent
1136 /// roster with `candidates = 3` gives one implementation per agent, and
1137 /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1138 /// author of candidate *i* whenever the roster has more than one agent.
1139 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1140 if self.agents.is_empty() {
1141 bail!(
1142 "agent roster is empty: no agent CLI found on PATH and no \
1143 [[agents]] in the config. Run `magi init` to write a starter \
1144 magi.toml."
1145 );
1146 }
1147 Ok(ResolvedRoles {
1148 implementers: self.rotate(&self.roles.implementers, self.graph.candidates, 0)?,
1149 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
1150 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
1151 fixer: self
1152 .roles
1153 .fixer
1154 .as_deref()
1155 .map(|f| self.agent(f).cloned())
1156 .transpose()?,
1157 })
1158 }
1159
1160 /// Advisor seats for `magi plan`'s design-deliberation stage (see
1161 /// [`crate::advise`]): `[roles] advisors` when set, otherwise the judge
1162 /// roster - see [`Roles::advisors`] for why that fallback and not the
1163 /// whole roster.
1164 ///
1165 /// The fallback rotates with `offset = 1`, matching the judges line in
1166 /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
1167 /// `roles.judges`, which is empty whenever judges themselves are
1168 /// unconfigured and rotating the whole roster. Falling back with
1169 /// `offset = 0` there would silently hand the advisors a *different*
1170 /// agent set than the judges an unconfigured run would actually get,
1171 /// which is the one thing [`Roles::advisors`]'s doc promises will not
1172 /// happen.
1173 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
1174 if self.agents.is_empty() {
1175 bail!(
1176 "agent roster is empty: no agent CLI found on PATH and no \
1177 [[agents]] in the config. Run `magi init` to write a starter \
1178 magi.toml."
1179 );
1180 }
1181 if !self.roles.advisors.is_empty() {
1182 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
1183 }
1184 self.rotate(&self.roles.judges, self.graph.advisors, 1)
1185 }
1186
1187 /// Shell prefix for [`Verify`] commands.
1188 pub fn shell(&self) -> Vec<String> {
1189 if let Some(s) = &self.verify.shell {
1190 return s.clone();
1191 }
1192 if which("sh") {
1193 vec!["sh".to_owned(), "-c".to_owned()]
1194 } else {
1195 vec!["cmd".to_owned(), "/C".to_owned()]
1196 }
1197 }
1198
1199 /// Starter config, as written by `magi init`.
1200 pub fn starter_toml() -> String {
1201 let detected = Self::autodetected();
1202 let mut s = String::from(
1203 "# magi — blind multi-agent implementation competition.\n\
1204 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
1205 # -> blind judging -> deliberation -> private final vote\n\
1206 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
1207 #\n\
1208 # Rendered by teravars: a `[vars]` table, env\n\
1209 # and system lookups, and `include = [...]` all work. Tera\n\
1210 # braces are live everywhere in this file, but comments are\n\
1211 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
1212 # may quote `{{ ... }}` freely.\n\
1213 #\n\
1214 # Layers deep-merge in increasing\n\
1215 # precedence, so the roster can live once per machine in\n\
1216 # <config_dir>/magi/config.toml and each repo only states its own\n\
1217 # gate:\n\
1218 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
1219 [vars]\n\
1220 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
1221 # Single quotes inside the braces: teravars renders the raw file\n\
1222 # text, so TOML's own \\\" escaping never reaches Tera.\n\
1223 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
1224 );
1225 if detected.agents.is_empty() {
1226 s.push_str(
1227 "# No agent CLI was found on PATH. Fill this in by hand.\n\
1228 # kind = claude | opencode | antigravity | codex | command\n\
1229 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
1230 );
1231 } else {
1232 for a in &detected.agents {
1233 s.push_str("[[agents]]\n");
1234 s.push_str(&format!("id = {:?}\n", a.id));
1235 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
1236 if let Some(m) = &a.model {
1237 s.push_str(&format!("model = {m:?}\n"));
1238 }
1239 s.push('\n');
1240 }
1241 }
1242 s.push_str(
1243 "# Leave a role list empty to rotate through the roster.\n\
1244 [roles]\n\
1245 implementers = []\n\
1246 judges = []\n\
1247 reviewers = []\n\n\
1248 [graph]\n\
1249 candidates = 3\n\
1250 judges = 3\n\
1251 deliberate_rounds = 1\n\
1252 reviewers = 2\n\
1253 review_rounds = 6\n\
1254 max_parallel = 4\n\
1255 language = \"en\"\n\
1256 # One CLI conversation per seat: judges keep their own argument\n\
1257 # across deliberation, the fixer keeps its implementation context.\n\
1258 sessions = true\n\n\
1259 [verify]\n\
1260 # Run once per review round in the winner's worktree; failures are\n\
1261 # fed back to the fixer.\n\
1262 e2e = []\n\
1263 # Final gate. Every command must exit 0 before a merge.\n\
1264 gate = []\n\n\
1265 [merge]\n\
1266 # none | local | pr\n\
1267 mode = \"none\"\n\n\
1268 [update]\n\
1269 # off | notify | install — checked in the background, throttled.\n\
1270 mode = \"notify\"\n\
1271 # interval = \"24h\"\n",
1272 );
1273 s
1274 }
1275}
1276
1277/// Is `program` on `PATH`?
1278pub fn which(program: &str) -> bool {
1279 let Some(paths) = std::env::var_os("PATH") else {
1280 return false;
1281 };
1282 let exts: Vec<String> = std::env::var("PATHEXT")
1283 .map(|v| v.split(';').map(|e| e.to_lowercase()).collect())
1284 .unwrap_or_default();
1285 std::env::split_paths(&paths).any(|dir| {
1286 let direct = dir.join(program);
1287 if direct.is_file() {
1288 return true;
1289 }
1290 exts.iter().any(|ext| {
1291 let mut name = program.to_owned();
1292 name.push_str(ext);
1293 dir.join(name).is_file()
1294 })
1295 })
1296}
1297
1298#[cfg(test)]
1299mod tests {
1300 use super::*;
1301
1302 fn spec(id: &str) -> AgentSpec {
1303 AgentSpec {
1304 id: id.to_owned(),
1305 kind: AgentKind::Command,
1306 model: None,
1307 command: vec!["true".to_owned()],
1308 extra_args: Vec::new(),
1309 env: BTreeMap::new(),
1310 prompt_delivery: None,
1311 }
1312 }
1313
1314 #[test]
1315 fn empty_roles_rotate_judges_off_their_own_candidate() {
1316 // Three seats, said out loud: this is a test about *rotation*, and it
1317 // has nothing to say about how many candidates a task buys by default.
1318 let cfg = Config {
1319 agents: vec![spec("a"), spec("b"), spec("c")],
1320 graph: Graph {
1321 candidates: 3,
1322 ..Graph::default()
1323 },
1324 ..Config::default()
1325 };
1326 let roles = cfg.resolve_roles().unwrap();
1327 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
1328 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
1329 assert_eq!(impls, ["a", "b", "c"]);
1330 assert_eq!(judges, ["b", "c", "a"]);
1331 for (i, j) in judges.iter().enumerate() {
1332 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
1333 }
1334 }
1335
1336 #[test]
1337 fn single_agent_roster_fills_every_seat() {
1338 let cfg = Config {
1339 agents: vec![spec("solo")],
1340 graph: Graph {
1341 candidates: 3,
1342 ..Graph::default()
1343 },
1344 ..Config::default()
1345 };
1346 let roles = cfg.resolve_roles().unwrap();
1347 assert_eq!(roles.implementers.len(), 3);
1348 assert!(roles.judges.iter().all(|a| a.id == "solo"));
1349 }
1350
1351 #[test]
1352 fn explicit_roles_win() {
1353 let cfg = Config {
1354 agents: vec![spec("a"), spec("b")],
1355 roles: Roles {
1356 implementers: vec!["b".to_owned()],
1357 judges: vec!["a".to_owned()],
1358 reviewers: Vec::new(),
1359 fixer: Some("a".to_owned()),
1360 ..Roles::default()
1361 },
1362 ..Config::default()
1363 };
1364 let roles = cfg.resolve_roles().unwrap();
1365 assert!(roles.implementers.iter().all(|a| a.id == "b"));
1366 assert!(roles.judges.iter().all(|a| a.id == "a"));
1367 assert_eq!(roles.fixer.unwrap().id, "a");
1368 }
1369
1370 #[test]
1371 fn unknown_agent_id_is_an_error() {
1372 let cfg = Config {
1373 agents: vec![spec("a")],
1374 roles: Roles {
1375 judges: vec!["nope".to_owned()],
1376 ..Roles::default()
1377 },
1378 ..Config::default()
1379 };
1380 assert!(cfg.resolve_roles().is_err());
1381 }
1382
1383 #[test]
1384 fn empty_roster_is_an_error() {
1385 assert!(Config::default().resolve_roles().is_err());
1386 }
1387
1388 #[test]
1389 fn advisors_default_to_three_and_are_on() {
1390 let g = Graph::default();
1391 assert_eq!(g.advisors, 3);
1392 assert!(g.advise);
1393 }
1394
1395 #[test]
1396 fn unset_advisors_falls_back_to_the_judge_roster() {
1397 let cfg = Config {
1398 agents: vec![spec("a"), spec("b"), spec("c")],
1399 roles: Roles {
1400 judges: vec!["b".to_owned()],
1401 ..Roles::default()
1402 },
1403 graph: Graph {
1404 advisors: 2,
1405 ..Graph::default()
1406 },
1407 ..Config::default()
1408 };
1409 let advisors = cfg.advisors().expect("advisors resolve");
1410 assert!(
1411 advisors.iter().all(|a| a.id == "b"),
1412 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
1413 );
1414 }
1415
1416 #[test]
1417 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
1418 let cfg = Config {
1419 agents: vec![spec("a"), spec("b")],
1420 roles: Roles {
1421 judges: vec!["b".to_owned()],
1422 advisors: vec!["a".to_owned()],
1423 ..Roles::default()
1424 },
1425 graph: Graph {
1426 advisors: 2,
1427 ..Graph::default()
1428 },
1429 ..Config::default()
1430 };
1431 let advisors = cfg.advisors().expect("advisors resolve");
1432 assert!(advisors.iter().all(|a| a.id == "a"));
1433 }
1434
1435 /// Reported: with neither `[roles] advisors` nor `[roles] judges` set, the
1436 /// fallback rotated the roster from offset 0 while `resolve_roles` gives
1437 /// judges offset 1 - two different agent sets, contradicting the doc's
1438 /// promise that an unset `advisors` is "the judge roster".
1439 #[test]
1440 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
1441 let cfg = Config {
1442 agents: vec![spec("a"), spec("b"), spec("c"), spec("d")],
1443 graph: Graph {
1444 judges: 3,
1445 advisors: 3,
1446 ..Graph::default()
1447 },
1448 ..Config::default()
1449 };
1450 let judges = cfg.resolve_roles().expect("roles resolve").judges;
1451 let advisors = cfg.advisors().expect("advisors resolve");
1452 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
1453 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
1454 assert_eq!(
1455 advisor_ids, judge_ids,
1456 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
1457 );
1458 }
1459
1460 #[test]
1461 fn repos_default_to_no_roots_and_a_day_of_trust() {
1462 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
1463 assert_eq!(Config::default().repos.scan_ttl, 86_400);
1464 }
1465
1466 #[test]
1467 fn a_config_file_with_no_repos_table_still_loads() {
1468 let dir = tempfile::tempdir().unwrap();
1469 let path = dir.path().join("magi.toml");
1470 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
1471 let cfg = Config::load(&path).expect("must load without [repos]");
1472 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
1473 assert_eq!(cfg.repos.scan_ttl, 86_400);
1474 }
1475
1476 /// A fixture is the whole config under test.
1477 ///
1478 /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
1479 /// a machine where somebody had written `<config_dir>/magi/config.toml`
1480 /// the suite silently loaded it as the lowest layer. Adding `[repos]
1481 /// roots` there turned two web tests red - their fixtures declare
1482 /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
1483 /// array key spread across two layers. CI stayed green throughout,
1484 /// because a runner has no such file: the suite failed only where magi is
1485 /// actually used.
1486 ///
1487 /// So a test build has no machine layer unless it asks for one, and this
1488 /// is that promise. Written against a real file at the real location so
1489 /// it fails if `machine_layer` starts reading it again.
1490 #[test]
1491 fn a_test_build_does_not_read_the_operators_machine_config() {
1492 let repo = tempfile::tempdir().unwrap();
1493 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
1494
1495 let layers = Config::layers(repo.path());
1496 assert_eq!(
1497 layers,
1498 vec![repo.path().join("magi.toml")],
1499 "only the fixture's own file may be a layer"
1500 );
1501 if let Some(real) = dirs::config_dir() {
1502 let machine = real.join("magi").join("config.toml");
1503 assert!(
1504 !layers.contains(&machine),
1505 "the operator's {} must not be a layer in a test build",
1506 machine.display()
1507 );
1508 }
1509 }
1510
1511 #[test]
1512 fn starter_toml_loads_through_teravars() {
1513 let dir = tempfile::tempdir().unwrap();
1514 let path = dir.path().join("magi.toml");
1515 std::fs::write(&path, Config::starter_toml()).unwrap();
1516 let parsed = Config::load(&path).expect("starter config must load");
1517 assert_eq!(parsed.graph.candidates, 3);
1518 assert_eq!(parsed.merge.mode, MergeMode::None);
1519 assert!(parsed.graph.sessions);
1520 assert_eq!(parsed.update.mode, UpdateMode::Notify);
1521 }
1522
1523 #[test]
1524 fn later_layers_win_and_vars_render() {
1525 let dir = tempfile::tempdir().unwrap();
1526 let machine = dir.path().join("machine.toml");
1527 let project = dir.path().join("magi.toml");
1528 // The machine layer owns the roster...
1529 std::fs::write(
1530 &machine,
1531 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
1532 [graph]\ncandidates = 3\nmax_parallel = 8\n",
1533 )
1534 .unwrap();
1535 // ...and the project layer only states what is repo-specific, plus a
1536 // `[vars]` value interpolated into a command.
1537 std::fs::write(
1538 &project,
1539 "[vars]\ncache = \"/shared\"\n\n\
1540 [graph]\ncandidates = 2\n\n\
1541 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
1542 )
1543 .unwrap();
1544
1545 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
1546 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
1547 assert_eq!(cfg.graph.candidates, 2, "project layer wins");
1548 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
1549 assert_eq!(
1550 cfg.verify.gate,
1551 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
1552 );
1553 // The rendered command is where the cache path is read back from.
1554 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
1555 }
1556
1557 #[test]
1558 fn the_disk_defaults_are_the_measurements_made_up_front() {
1559 let cfg = Config::default();
1560 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
1561 assert!(cfg.disk.auto_fold);
1562 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
1563 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
1564 }
1565
1566 #[test]
1567 fn an_unset_disk_section_is_the_safe_default() {
1568 let dir = tempfile::tempdir().unwrap();
1569 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
1570 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
1571 assert_eq!(cfg.disk, Disk::default());
1572 }
1573
1574 #[test]
1575 fn env_is_available_to_templates_with_a_default() {
1576 let dir = tempfile::tempdir().unwrap();
1577 let path = dir.path().join("magi.toml");
1578 // teravars ships no `env`; magi adds it, and the `default` filter has
1579 // to cover the unset case or every machine would need the variable.
1580 //
1581 // Deliberately no named variable: `env` is keyed by the exact spelling
1582 // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
1583 // test asserting `env.PATH` passes on one runner and fails on another.
1584 // The map's non-emptiness is the platform-neutral claim.
1585 std::fs::write(
1586 &path,
1587 "[verify]\n\
1588 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
1589 \"populated={{ env | length > 0 }}\"]\n",
1590 )
1591 .unwrap();
1592 let cfg = Config::load(&path).expect("env lookup must render");
1593 assert_eq!(cfg.verify.gate[0], "cache=fallback");
1594 assert_eq!(cfg.verify.gate[1], "populated=true");
1595 }
1596
1597 #[test]
1598 fn a_broken_template_names_the_file() {
1599 let dir = tempfile::tempdir().unwrap();
1600 let path = dir.path().join("magi.toml");
1601 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
1602 let err = Config::load(&path).expect_err("must not silently ignore");
1603 assert!(err.to_string().contains("teravars"), "{err}");
1604 }
1605
1606 #[test]
1607 fn tera_syntax_in_comments_is_inert() {
1608 // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
1609 // comment may quote template syntax without rendering. Before 0.2.2 this
1610 // load failed: the commented-out braces reached the template parser.
1611 let dir = tempfile::tempdir().unwrap();
1612 let path = dir.path().join("magi.toml");
1613 std::fs::write(
1614 &path,
1615 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
1616 [graph]\ncandidates = 2\n",
1617 )
1618 .unwrap();
1619 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
1620 assert_eq!(cfg.graph.candidates, 2);
1621 }
1622
1623 #[test]
1624 fn opencode_defaults_to_file_delivery() {
1625 let mut s = spec("oc");
1626 s.kind = AgentKind::Opencode;
1627 assert_eq!(s.delivery(), Delivery::File);
1628 s.prompt_delivery = Some(Delivery::Argv);
1629 assert_eq!(s.delivery(), Delivery::Argv);
1630 }
1631 #[test]
1632 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
1633 // Both default on, and that pair is the safety property: `land` takes
1634 // over the watching an operator was doing by hand, `land_approval`
1635 // keeps the irreversible step a human decision. An unattended merge
1636 // needs BOTH flipped, which has to be chosen deliberately twice.
1637 let g = Graph::default();
1638 assert!(
1639 g.land,
1640 "stopping at an open PR left the watching to a human"
1641 );
1642 assert!(
1643 g.land_approval,
1644 "on-by-default land is only defensible while this is also on"
1645 );
1646 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
1647 }
1648 #[test]
1649 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
1650 // teravars appends arrays. For an ordered list of seats, or an argv,
1651 // the concatenation is something neither file says - and the operator
1652 // pays for the extra seats by the token.
1653 let dir = tempfile::tempdir().unwrap();
1654 let machine = dir.path().join("machine.toml");
1655 let repo = dir.path().join("magi.toml");
1656 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
1657 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
1658
1659 let err = Config::load_layers(&[machine.clone(), repo.clone()])
1660 .expect_err("two layers naming one array must not merge silently")
1661 .to_string();
1662 assert!(err.contains("roles.implementers"), "{err}");
1663 // Both files are named: the fix is to delete one of them, and the
1664 // operator has to know which two to choose between.
1665 assert!(err.contains("machine.toml"), "{err}");
1666 assert!(err.contains("magi.toml"), "{err}");
1667 }
1668
1669 #[test]
1670 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
1671 // The split the layering exists for: state a preference machine-wide,
1672 // let the repository own its own lists.
1673 let dir = tempfile::tempdir().unwrap();
1674 let machine = dir.path().join("machine.toml");
1675 let repo = dir.path().join("magi.toml");
1676 std::fs::write(&machine, "[roles]\nplanner = \"opus\"\n").unwrap();
1677 std::fs::write(
1678 &repo,
1679 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
1680 [roles]\nimplementers = [\"oc\"]\n",
1681 )
1682 .unwrap();
1683
1684 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
1685 assert_eq!(cfg.roles.planner.as_deref(), Some("opus"));
1686 assert_eq!(cfg.roles.implementers, ["oc"]);
1687 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
1688 }
1689
1690 #[test]
1691 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
1692 // The `editorconfig-checker` distribution problem: a shared layer
1693 // wants to add a gate command without erasing the repository's own.
1694 let dir = tempfile::tempdir().unwrap();
1695 let machine = dir.path().join("machine.toml");
1696 let repo = dir.path().join("magi.toml");
1697 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
1698 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
1699
1700 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
1701 assert_eq!(
1702 cfg.verify.gate,
1703 [
1704 "editorconfig-checker".to_owned(),
1705 "cargo make check".to_owned()
1706 ],
1707 "low-priority (machine) command first, high-priority (repo) command after"
1708 );
1709 }
1710
1711 #[test]
1712 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
1713 let dir = tempfile::tempdir().unwrap();
1714 let machine = dir.path().join("machine.toml");
1715 let repo = dir.path().join("magi.toml");
1716 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
1717 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
1718
1719 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
1720 assert_eq!(
1721 cfg.verify.e2e,
1722 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
1723 );
1724 }
1725
1726 #[test]
1727 fn two_layers_declaring_repos_roots_are_both_scanned() {
1728 let dir = tempfile::tempdir().unwrap();
1729 let machine = dir.path().join("machine.toml");
1730 let repo = dir.path().join("magi.toml");
1731 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
1732 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
1733
1734 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
1735 assert_eq!(
1736 cfg.repos.roots,
1737 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
1738 );
1739 }
1740
1741 #[test]
1742 fn duplicate_gate_commands_across_layers_both_run() {
1743 // Dropping the duplicate would be a silent surprise; the operator
1744 // sees a slower gate, never a missing one.
1745 let dir = tempfile::tempdir().unwrap();
1746 let machine = dir.path().join("machine.toml");
1747 let repo = dir.path().join("magi.toml");
1748 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
1749 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
1750
1751 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
1752 assert_eq!(
1753 cfg.verify.gate,
1754 ["same-command".to_owned(), "same-command".to_owned()]
1755 );
1756 }
1757
1758 #[test]
1759 fn notify_command_is_still_refused_across_two_layers() {
1760 // An argv, not a set: concatenating two of them is not a program.
1761 let dir = tempfile::tempdir().unwrap();
1762 let machine = dir.path().join("machine.toml");
1763 let repo = dir.path().join("magi.toml");
1764 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
1765 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
1766
1767 let err = Config::load_layers(&[machine.clone(), repo.clone()])
1768 .expect_err("an argv split across layers must not concatenate")
1769 .to_string();
1770 assert!(err.contains("notify.command"), "{err}");
1771 assert!(err.contains("machine.toml"), "{err}");
1772 assert!(err.contains("magi.toml"), "{err}");
1773 }
1774
1775 #[test]
1776 fn one_layer_declaring_verify_gate_runs_unchanged() {
1777 // The classification must not change behaviour for the configuration
1778 // this very repository has today: exactly one layer names the gate.
1779 let dir = tempfile::tempdir().unwrap();
1780 let path = dir.path().join("magi.toml");
1781 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
1782
1783 let cfg = Config::load(&path).expect("single layer must still load");
1784 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
1785 }
1786
1787 #[test]
1788 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
1789 let dir = tempfile::tempdir().unwrap();
1790 let machine = dir.path().join("machine.toml");
1791 let repo = dir.path().join("magi.toml");
1792 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
1793 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
1794 let paths = vec![machine.clone(), repo.clone()];
1795
1796 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
1797 let described =
1798 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
1799 assert!(described.contains("editorconfig-checker && cargo make check"));
1800 assert!(
1801 described.contains(&machine.display().to_string()),
1802 "{described}"
1803 );
1804 assert!(
1805 described.contains(&repo.display().to_string()),
1806 "{described}"
1807 );
1808
1809 // A single contributing layer stays the plain one-line summary.
1810 let single = vec![repo.clone()];
1811 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
1812 let solo_described =
1813 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
1814 assert_eq!(solo_described, "cargo make check");
1815 }
1816}