Skip to main content

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