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}
149
150/// Graph shape and limits.
151#[derive(Debug, Clone, Deserialize, Serialize)]
152#[serde(deny_unknown_fields, default)]
153pub struct Graph {
154    /// Parallel implementations of the same task. **One by default.**
155    ///
156    /// Competition is the thing magi is for, and it is still here - it is just
157    /// no longer what every task buys without being asked. Three days and 13
158    /// runs on this repository, which is the workload these numbers are drawn
159    /// from:
160    ///
161    /// - **0 of 13** competed runs reached a merge. Everything that landed in
162    ///   that window went through `magi review` - the cheap half, no
163    ///   competition - and passed on the first try.
164    /// - The judges' first choices **split 73% of the time** (8 of 11
165    ///   tallies). Candidates that close together make the ranking a weak
166    ///   signal for what it costs to produce.
167    /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
168    ///   review 28min, **verify 5min** - and verify is the node that caught a
169    ///   defect every reviewer had passed as clean. The cheapest step is the
170    ///   one that earns its place every time.
171    ///
172    /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
173    /// single-seat default would have shipped the worse implementation in
174    /// roughly a quarter of them. That is exactly why this is a *default* and
175    /// not a removal - `magi run --candidates N` and a per-task seat count are
176    /// how a task that deserves a competition gets one.
177    ///
178    /// A single-candidate run needs no special case: `Runner::review`'s doc
179    /// records that `execute` already degrades to implement -> review -> gate
180    /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
181    /// no two first choices to reconcile and `vote` returns early.
182    pub candidates: usize,
183    /// Independent judges.
184    pub judges: usize,
185    /// Deliberation rounds when the judges' first choices disagree.
186    pub deliberate_rounds: usize,
187    /// Reviewers per review round.
188    pub reviewers: usize,
189    /// Maximum review+fix rounds before the run is declared blocked.
190    pub review_rounds: usize,
191    /// Maximum agent processes running at once.
192    pub max_parallel: usize,
193    /// Language for the prose the agents write (`en` / `ja` / any language name).
194    pub language: String,
195    /// Keep one CLI conversation per seat, so a judge remembers its own
196    /// argument across deliberation rounds and the fixer remembers its own
197    /// implementation across review rounds.
198    ///
199    /// Sessions are scoped to a *seat*, never to an agent id: the same model
200    /// sitting as implementer and as judge gets two unrelated conversations,
201    /// which is what keeps blind judging blind.
202    pub sessions: bool,
203    /// Per-node timeouts, seconds.
204    pub timeout_implement: u64,
205    /// Per-node timeouts, seconds.
206    pub timeout_judge: u64,
207    /// Per-node timeouts, seconds.
208    pub timeout_review: u64,
209    /// Per-node timeouts, seconds.
210    pub timeout_fix: u64,
211    /// Retries for an agent invocation that fails or returns nothing usable.
212    pub retries: usize,
213    /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
214    pub worktree_root: Option<PathBuf>,
215    /// After the pull request is open, keep going: watch its checks and
216    /// reviews, run a fix round when they are unhappy, and ask to merge.
217    ///
218    /// On, because stopping at an open pull request left the operator doing
219    /// the watching by hand - six times in the session this was built in - and
220    /// that is the work the loop exists to take. It only engages for
221    /// `merge = "pr"`; every other merge mode ends the run as before.
222    ///
223    /// Turning this on does **not** hand magi the merge button:
224    /// [`Graph::land_approval`] is on too, and nothing merges without an
225    /// explicit answer. Setting both to their non-defaults is the only way to
226    /// get an unattended merge, and it has to be chosen twice.
227    pub land: bool,
228    /// Land rounds - watch, fix, push - before the run is left for a human.
229    pub land_rounds: usize,
230    /// Ask the owner before merging, showing what is about to land.
231    ///
232    /// On, and it is what makes `land` safe to have on: the question carries a
233    /// rendered panel - the diffstat, the patch, the checks, the review
234    /// comments that were addressed, and the subject the squash will use - so
235    /// the decision is made on evidence rather than on trust, from wherever
236    /// the operator happens to be.
237    ///
238    /// Silence is a hold. An unanswered approval never merges, and neither
239    /// does any answer other than the word `merge`.
240    pub land_approval: bool,
241    /// How long to wait for an owner to answer a question before the run is
242    /// abandoned, seconds. A parked run costs nothing, so this is generous;
243    /// it exists so a forgotten question cannot pin a worktree forever.
244    pub answer_timeout: u64,
245}
246
247impl Default for Graph {
248    fn default() -> Self {
249        Self {
250            candidates: 1,
251            judges: 3,
252            deliberate_rounds: 1,
253            reviewers: 2,
254            review_rounds: 6,
255            max_parallel: 4,
256            language: "en".to_owned(),
257            sessions: true,
258            timeout_implement: 3600,
259            timeout_judge: 1200,
260            timeout_review: 1200,
261            timeout_fix: 1800,
262            retries: 1,
263            worktree_root: None,
264            land: true,
265            land_rounds: 4,
266            land_approval: true,
267            answer_timeout: 86_400,
268        }
269    }
270}
271
272/// What to do when vendor-identifying text is found in material shown to judges.
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
274#[serde(rename_all = "lowercase")]
275pub enum LeakPolicy {
276    /// Record the leak, show the patch unmodified.
277    Warn,
278    /// Replace the token with `[REDACTED]` in the presented patch.
279    Redact,
280    /// Abort the run.
281    Fail,
282}
283
284/// Blindness policy.
285///
286/// Commit messages and candidate summaries are *always* stripped of
287/// attribution trailers and redacted — that is where signatures actually
288/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
289/// redaction would corrupt the artifact under judgement.
290#[derive(Debug, Clone, Deserialize, Serialize)]
291#[serde(deny_unknown_fields, default)]
292pub struct Blind {
293    /// Install a per-worktree `commit-msg` hook that deletes attribution
294    /// trailers before they can land in a candidate's history.
295    pub commit_msg_hook: bool,
296    /// Literal, case-insensitive substrings. A line containing any of them is
297    /// dropped from commit messages and summaries; the `commit-msg` hook is
298    /// generated from the same list.
299    pub strip_lines: Vec<String>,
300    /// Case-insensitive substrings that identify a vendor or model.
301    pub vendor_tokens: Vec<String>,
302    /// Policy for vendor tokens found in the patch body.
303    pub on_leak: LeakPolicy,
304    /// Seed for label assignment and per-judge presentation order. Derived from
305    /// the run id when unset; set it to make a run reproducible.
306    pub seed: Option<u64>,
307}
308
309impl Default for Blind {
310    fn default() -> Self {
311        Self {
312            commit_msg_hook: true,
313            strip_lines: [
314                "Co-Authored-By:",
315                "Signed-off-by:",
316                "Assisted-by:",
317                "Generated-by:",
318                "Generated with",
319                "\u{1f916}",
320            ]
321            .iter()
322            .map(|s| (*s).to_owned())
323            .collect(),
324            vendor_tokens: [
325                "claude",
326                "anthropic",
327                "codex",
328                "openai",
329                "chatgpt",
330                "gemini",
331                "grok",
332                "xai",
333                "copilot",
334                "opencode",
335                "qoder",
336                "cursor",
337                "\u{1f916}",
338            ]
339            .iter()
340            .map(|s| (*s).to_owned())
341            .collect(),
342            on_leak: LeakPolicy::Warn,
343            seed: None,
344        }
345    }
346}
347
348/// Shell commands that gate the winner.
349#[derive(Debug, Clone, Default, Deserialize, Serialize)]
350#[serde(deny_unknown_fields, default)]
351pub struct Verify {
352    /// Run in the winner's worktree once per review round. Its output is fed
353    /// back to the fixer. This is the "real machine" leg of the review.
354    pub e2e: Vec<String>,
355    /// Final gate. Must all exit 0 before a merge is attempted.
356    pub gate: Vec<String>,
357    /// Shell used to run the commands above. Defaults to `sh -c`, or
358    /// `cmd /C` when `sh` is not on `PATH`.
359    pub shell: Option<Vec<String>>,
360}
361
362impl Verify {
363    /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
364    /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
365    /// this reads back. One rendering is enough - they all set the same
366    /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
367    /// command is checked before the gate because the e2e rebuilds the crate.
368    pub fn cache_dir(&self) -> Option<PathBuf> {
369        self.e2e
370            .iter()
371            .chain(self.gate.iter())
372            .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
373    }
374}
375
376/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
377///
378/// The numbers below come from one incident, not from theory: a machine with
379/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
380/// Three multi-gigabyte classes of junk accumulated side by side - per-run
381/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
382/// each verify round and each implementation wave recompiles the derived
383/// section of the project into, and the outputs of runs that were removed but
384/// whose folders nobody deleted.
385#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
386#[serde(deny_unknown_fields, default)]
387pub struct Disk {
388    /// Free space, in bytes, below which no new run may start: the daemon and
389    /// the `magi run` gate answer with "the disk is full" instead of letting
390    /// the graph fill it the rest of the way. `0` turns the gate off.
391    ///
392    /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
393    /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
394    /// competition triggers and small enough that a 1 TB disk with 100 GB free
395    /// is nowhere near the threshold.
396    pub min_free_bytes: u64,
397    /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
398    /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
399    /// worktrees removed. `0` turns the janitor off.
400    ///
401    /// Default true.
402    pub auto_fold: bool,
403    /// How old a finished run must be before the janitor folds it, seconds.
404    ///
405    /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
406    /// run that `Ready` a week ago is worktrees holding a compile each. Six
407    /// hours is long enough that nobody loses an answer in the gap between
408    /// reading the report and starting from it, and short enough that a backlog
409    /// cannot pile up across two nights.
410    pub fold_grace_secs: u64,
411    /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
412    /// verify commands), in bytes. When the janitor runs and the cache is over
413    /// it, files are dropped oldest-first until it is not. `0` turns pruning
414    /// off - the cache then only ever grows, which is the operator's call.
415    ///
416    /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
417    /// shared cache on top of ~16 GB in the primary target directory and 6.7-
418    /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
419    /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
420    /// pruning only costs the rebuild of the dropped files, not of the world)
421    /// without letting one addled cache swallow the machine.
422    pub cache_limit_bytes: u64,
423}
424
425impl Default for Disk {
426    fn default() -> Self {
427        Self {
428            min_free_bytes: 8 * 1024 * 1024 * 1024,
429            auto_fold: true,
430            fold_grace_secs: 6 * 60 * 60,
431            cache_limit_bytes: 10 * 1024 * 1024 * 1024,
432        }
433    }
434}
435
436/// What to do with the winning branch.
437#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
438#[serde(rename_all = "lowercase")]
439pub enum MergeMode {
440    /// Leave the branch alone and print the merge command.
441    None,
442    /// `git merge --no-ff` into the base branch in the primary worktree.
443    Local,
444    /// Push the branch and open a PR with `gh pr create`.
445    Pr,
446}
447
448/// Merge policy.
449#[derive(Debug, Clone, Deserialize, Serialize)]
450#[serde(deny_unknown_fields, default)]
451pub struct Merge {
452    /// Default is [`MergeMode::None`]: magi never touches your base branch
453    /// unless you ask it to.
454    pub mode: MergeMode,
455    /// Base branch. Defaults to the branch checked out when the run started.
456    pub base: Option<String>,
457    /// Remote for `mode = "pr"`.
458    pub remote: String,
459}
460
461impl Default for Merge {
462    fn default() -> Self {
463        Self {
464            mode: MergeMode::None,
465            base: None,
466            remote: "origin".to_owned(),
467        }
468    }
469}
470
471/// How magi keeps itself current.
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
473#[serde(rename_all = "lowercase")]
474pub enum UpdateMode {
475    /// Never check.
476    Off,
477    /// Check in the background and print a one-line banner when a newer
478    /// release exists.
479    Notify,
480    /// Check and install silently.
481    Install,
482}
483
484/// Self-update policy.
485#[derive(Debug, Clone, Deserialize, Serialize)]
486#[serde(deny_unknown_fields, default)]
487pub struct Update {
488    /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
489    pub mode: UpdateMode,
490    /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
491    pub interval: Option<String>,
492}
493
494impl Default for Update {
495    fn default() -> Self {
496        Self {
497            mode: UpdateMode::Notify,
498            interval: None,
499        }
500    }
501}
502
503/// Top-level configuration.
504#[derive(Debug, Clone, Default, Deserialize, Serialize)]
505#[serde(deny_unknown_fields, default)]
506pub struct Config {
507    /// Agent roster.
508    pub agents: Vec<AgentSpec>,
509    /// Role assignment.
510    pub roles: Roles,
511    /// Graph shape.
512    pub graph: Graph,
513    /// Blindness policy.
514    pub blind: Blind,
515    /// Verification commands.
516    pub verify: Verify,
517    /// Disk hygiene.
518    pub disk: Disk,
519    /// Merge policy.
520    pub merge: Merge,
521    /// Self-update policy.
522    pub update: Update,
523    /// Project-specific text appended to the node prompts.
524    pub prompts: Prompts,
525    /// How the operator is told a run is waiting on them.
526    pub notify: Notify,
527    /// Local repositories the plan surface can start or derive a conversation
528    /// against.
529    pub repos: Repos,
530}
531
532/// Where `magi plan` and the browser interview look for a repository other
533/// than the one they were started against.
534///
535/// `roots` is an array, so per [`array_keys`] it can only be declared in one
536/// config layer - the machine layer, since which checkouts exist on disk is a
537/// *machine* fact in the same way the agent roster is: a repository's own
538/// `magi.toml` cannot state where its siblings live before magi has resolved
539/// which repository to read that file from in the first place.
540#[derive(Debug, Clone, Deserialize, Serialize)]
541#[serde(deny_unknown_fields, default)]
542pub struct Repos {
543    /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
544    /// with a `.git` directory. Empty by default - nothing is scanned unless
545    /// asked to be.
546    pub roots: Vec<PathBuf>,
547    /// How long a scan is trusted before the next request re-scans it,
548    /// seconds. `0` means never trust it: scan on every request. Defaults to
549    /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
550    /// the same reason - a checkout does not usually appear or vanish inside
551    /// a session, so there is little to gain from scanning more often than
552    /// that, and an explicit refresh exists for the moment one does.
553    pub scan_ttl: u64,
554}
555
556impl Default for Repos {
557    fn default() -> Self {
558        Self {
559            roots: Vec::new(),
560            scan_ttl: 86_400,
561        }
562    }
563}
564
565/// Project-specific text appended to each node's prompt.
566///
567/// **Additive by construction.** These fields cannot replace magi's prompts,
568/// only extend them, and that restriction is the whole design. The built-in
569/// prompts carry the invariants the competition rests on: a judging prompt
570/// names no authors, every structured answer must arrive as one fenced `json`
571/// block, and a judge is told not to speculate about who wrote what. A config
572/// that could overwrite them would let a typo silently un-blind the panel or
573/// break the parser, and the symptom would be "the judges got worse" rather
574/// than an error.
575///
576/// Repository-wide context belongs in `AGENTS.md`, which every agent already
577/// reads from the checkout. Use these fields for the things a *magi node*
578/// needs to know and a repository file cannot say - for instance that
579/// reviewers here should ignore formatting because a hook owns it.
580#[derive(Debug, Clone, Default, Deserialize, Serialize)]
581#[serde(deny_unknown_fields, default)]
582pub struct Prompts {
583    /// Appended to every node's prompt.
584    pub all: String,
585    /// Appended for implementers.
586    pub implement: String,
587    /// Appended for judges, both ranking and voting.
588    pub judge: String,
589    /// Appended for reviewers.
590    pub review: String,
591    /// Appended for the fixer.
592    pub fix: String,
593}
594
595impl Prompts {
596    /// The overlay for one node, or `None` when nothing is configured.
597    ///
598    /// `node` is the graph's own node name, so a new node gets no overlay
599    /// rather than the wrong one.
600    pub fn overlay(&self, node: &str) -> Option<String> {
601        let specific = match node {
602            "implement" => &self.implement,
603            "judge" | "vote" | "deliberate" => &self.judge,
604            "review" => &self.review,
605            "fix" => &self.fix,
606            _ => "",
607        };
608        let mut parts: Vec<&str> = Vec::new();
609        for p in [self.all.trim(), specific.trim()] {
610            if !p.is_empty() {
611                parts.push(p);
612            }
613        }
614        if parts.is_empty() {
615            return None;
616        }
617        Some(parts.join("\n\n"))
618    }
619}
620
621/// How the operator is told that a run is waiting on them.
622///
623/// A command rather than a built-in integration: magi is one binary with no
624/// network dependencies, and every operator's notification path is different -
625/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
626/// Shelling out keeps all of them possible and none of them magi's problem.
627#[derive(Debug, Clone, Default, Deserialize, Serialize)]
628#[serde(deny_unknown_fields, default)]
629pub struct Notify {
630    /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
631    /// Empty means no notification - the web UI is then the only surface.
632    pub command: Vec<String>,
633}
634
635/// Roles resolved to concrete agent specs for one run.
636#[derive(Debug, Clone)]
637pub struct ResolvedRoles {
638    /// One per candidate.
639    pub implementers: Vec<AgentSpec>,
640    /// One per judge.
641    pub judges: Vec<AgentSpec>,
642    /// One per reviewer slot.
643    pub reviewers: Vec<AgentSpec>,
644    /// Explicit fixer, if configured.
645    pub fixer: Option<AgentSpec>,
646}
647
648/// Every array-valued key in a config table, as a dotted path.
649///
650/// Dotted so the error names `roles.implementers` rather than `implementers`:
651/// an operator with three config files needs to know which key, not just that
652/// there was one. `vars` is skipped because it is teravars' own input, merged
653/// on purpose and never deserialised into `Config`.
654fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
655    let mut out = Vec::new();
656    for (k, v) in table {
657        if prefix.is_empty() && k == "vars" {
658            continue;
659        }
660        let path = if prefix.is_empty() {
661            k.clone()
662        } else {
663            format!("{prefix}.{k}")
664        };
665        match v {
666            toml::Value::Array(_) => out.push(path),
667            toml::Value::Table(t) => out.extend(array_keys(t, &path)),
668            _ => {}
669        }
670    }
671    out
672}
673
674impl Config {
675    /// Load one file through teravars: Tera rendering, `[vars]` resolution,
676    /// and the `include = [...]` directive.
677    pub fn load(path: &Path) -> Result<Self> {
678        Self::load_layers(&[path.to_path_buf()])
679    }
680
681    /// Load and deep-merge a stack of config files, later files winning.
682    ///
683    /// This is why the config is TOML-through-teravars rather than plain serde:
684    /// the roster is a *machine* fact (which CLIs and plans you pay for) while
685    /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
686    /// there). Picking one file and ignoring the other would force every repo
687    /// to restate the roster.
688    pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
689        let mut engine = teravars::Engine::default();
690        let mut ctx = teravars::system_context();
691        // teravars ships `system.*` and `vars`; `env` is left to the consumer.
692        // A config that has to name a shared build-cache directory or a
693        // machine-specific path needs it, so magi provides it as a map:
694        // `{{ env.NAME | default(value='...') }}`.
695        let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
696        ctx.insert("env", &env);
697        if let Some(last) = paths.last()
698            && let Some(dir) = last.parent()
699        {
700            ctx.insert("repo", &dir.to_string_lossy());
701            ctx.insert(
702                "repo_name",
703                &dir.file_name().unwrap_or_default().to_string_lossy(),
704            );
705        }
706        if paths.len() > 1 {
707            Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
708        }
709        let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
710            format!(
711                "rendering config via teravars: {}",
712                paths
713                    .iter()
714                    .map(|p| p.display().to_string())
715                    .collect::<Vec<_>>()
716                    .join(", ")
717            )
718        })?;
719        let mut table = merged.config;
720        // `[vars]` is teravars' own input, already resolved into the render
721        // context; `deny_unknown_fields` must not trip over it.
722        table.remove("vars");
723        toml::Value::Table(table)
724            .try_into()
725            .context("deserializing magi config")
726    }
727
728    /// Refuse an array that two layers both declare.
729    ///
730    /// teravars **appends** arrays when it merges layers, and that is wrong for
731    /// every array magi has: `implementers` is an ordered list of seats,
732    /// `verify.gate` is the commands to run, `notify.command` is an argv.
733    /// Concatenating two of them yields something nobody wrote - three
734    /// implementers out of a machine's two and a repository's one, or an argv
735    /// of `["ntfy", "publish", "curl", "-X"]`.
736    ///
737    /// Replacing instead would be the right merge rule, but the rule lives in
738    /// teravars, which several other projects depend on; changing it there is
739    /// a decision for that crate, not something to fake here by re-reading the
740    /// files with different semantics and hoping the two paths agree.
741    ///
742    /// So magi refuses the ambiguity rather than resolving it silently. The
743    /// cost of guessing is a roster the operator did not ask for and is paying
744    /// for by the token.
745    fn refuse_split_arrays(
746        paths: &[PathBuf],
747        engine: &mut teravars::Engine,
748        ctx: &teravars::Context,
749    ) -> Result<()> {
750        let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
751        for path in paths {
752            let one = teravars::load_merged([path], engine, ctx)
753                .with_context(|| format!("rendering {}", path.display()))?;
754            for key in array_keys(&one.config, "") {
755                if let Some(first) = seen.get(&key) {
756                    bail!(
757                        "`{key}` is an array declared in two config layers:\n  \
758                         {}\n  {}\nteravars appends arrays when it merges, so \
759                         magi would run the concatenation of both - which is \
760                         not what either file says. Declare `{key}` in exactly \
761                         one of them.",
762                        first.display(),
763                        path.display()
764                    );
765                }
766                seen.insert(key, path.clone());
767            }
768        }
769        Ok(())
770    }
771
772    /// Resolve the config for `repo`, honouring an explicit `--config` path.
773    ///
774    /// Returns the config and the layers it came from, empty for built-in
775    /// defaults.
776    pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
777        if let Some(p) = explicit {
778            let paths = vec![p.to_path_buf()];
779            return Ok((Self::load_layers(&paths)?, paths));
780        }
781        let paths = Self::layers(repo);
782        if paths.is_empty() {
783            return Ok((Self::autodetected(), paths));
784        }
785        Ok((Self::load_layers(&paths)?, paths))
786    }
787    /// Environment variable that relocates the machine-wide config layer.
788    ///
789    /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
790    /// of the one under [`dirs::config_dir`]; set it to the empty string and
791    /// magi reads no machine layer at all.
792    ///
793    /// This exists because the machine layer is otherwise unavoidable, and a
794    /// test that builds a config fixture is not asking for the operator's
795    /// preferences to be merged into it. Adding `[repos] roots` to the real
796    /// machine config on a development box turned two passing tests red -
797    /// `repos_list_returns_name_and_path_for_every_configured_root` and
798    /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
799    /// declare `[repos] roots` of their own, which [`Config::layers`] then
800    /// found in two layers and [`Config::refuse_split_arrays`] correctly
801    /// refused. CI never saw it: a runner has no machine config, so the suite
802    /// was green there and red only where somebody actually uses magi.
803    ///
804    /// An operator gets the same escape hatch for free: a second machine
805    /// config, or none, without moving files about.
806    pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
807
808    /// Every config layer that applies to `repo`, in increasing precedence.
809    ///
810    /// The machine layer is whatever [`Config::machine_layer`] resolves to,
811    /// which is nothing at all in a test build.
812    pub fn layers(repo: &Path) -> Vec<PathBuf> {
813        let mut paths = Vec::new();
814        paths.extend(Self::machine_layer());
815        paths.push(repo.join(".magi").join("config.toml"));
816        paths.push(repo.join("magi.toml"));
817        paths.retain(|p| p.is_file());
818        paths
819    }
820
821    /// The machine-wide layer's path, when there is one.
822    ///
823    /// **A test build has none unless it names one.** A fixture is a complete
824    /// statement of the config under test, and the operator's own preferences
825    /// have no business being merged into it - least of all silently, on one
826    /// machine, in a suite that is green everywhere else.
827    #[cfg(test)]
828    fn machine_layer() -> Option<PathBuf> {
829        std::env::var(Self::CONFIG_DIR_ENV)
830            .ok()
831            .filter(|dir| !dir.trim().is_empty())
832            .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
833    }
834
835    /// The machine-wide layer's path, when there is one.
836    #[cfg(not(test))]
837    fn machine_layer() -> Option<PathBuf> {
838        match std::env::var(Self::CONFIG_DIR_ENV) {
839            // Named, and empty on purpose: no machine layer.
840            Ok(dir) if dir.trim().is_empty() => None,
841            Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
842            Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
843        }
844    }
845
846    /// Built-in config whose roster is the agent CLIs found on `PATH`.
847    pub fn autodetected() -> Self {
848        let mut cfg = Self::default();
849        for (kind, id, model) in [
850            (AgentKind::Claude, "opus", Some("opus")),
851            (AgentKind::Claude, "sonnet", Some("sonnet")),
852            (AgentKind::Antigravity, "antigravity", None),
853            (AgentKind::Opencode, "opencode", None),
854            (AgentKind::Codex, "codex", None),
855        ] {
856            if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
857                cfg.agents.push(AgentSpec {
858                    id: id.to_owned(),
859                    kind,
860                    model: model.map(str::to_owned),
861                    command: Vec::new(),
862                    extra_args: Vec::new(),
863                    env: BTreeMap::new(),
864                    prompt_delivery: None,
865                });
866            }
867        }
868        cfg
869    }
870
871    /// The shared build cache the verify commands and the agents both build
872    /// into, when the config declares one. See [`Verify::cache_dir`].
873    pub fn cache_dir(&self) -> Option<PathBuf> {
874        self.verify.cache_dir()
875    }
876
877    /// Look an agent up by id.
878    pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
879        self.agents
880            .iter()
881            .find(|a| a.id == id)
882            .with_context(|| format!("no agent with id `{id}` in the roster"))
883    }
884
885    /// Fill the roles out to the configured widths.
886    ///
887    /// An empty role list rotates through the whole roster, so a three-agent
888    /// roster with `candidates = 3` gives one implementation per agent, and
889    /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
890    /// author of candidate *i* whenever the roster has more than one agent.
891    pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
892        if self.agents.is_empty() {
893            bail!(
894                "agent roster is empty: no agent CLI found on PATH and no \
895                 [[agents]] in the config. Run `magi init` to write a starter \
896                 magi.toml."
897            );
898        }
899        let pick = |ids: &[String], count: usize, offset: usize| -> Result<Vec<AgentSpec>> {
900            let mut out = Vec::with_capacity(count);
901            for i in 0..count {
902                let spec = if ids.is_empty() {
903                    self.agents[(i + offset) % self.agents.len()].clone()
904                } else {
905                    self.agent(&ids[i % ids.len()])?.clone()
906                };
907                out.push(spec);
908            }
909            Ok(out)
910        };
911        Ok(ResolvedRoles {
912            implementers: pick(&self.roles.implementers, self.graph.candidates, 0)?,
913            judges: pick(&self.roles.judges, self.graph.judges, 1)?,
914            reviewers: pick(&self.roles.reviewers, self.graph.reviewers, 0)?,
915            fixer: self
916                .roles
917                .fixer
918                .as_deref()
919                .map(|f| self.agent(f).cloned())
920                .transpose()?,
921        })
922    }
923
924    /// Shell prefix for [`Verify`] commands.
925    pub fn shell(&self) -> Vec<String> {
926        if let Some(s) = &self.verify.shell {
927            return s.clone();
928        }
929        if which("sh") {
930            vec!["sh".to_owned(), "-c".to_owned()]
931        } else {
932            vec!["cmd".to_owned(), "/C".to_owned()]
933        }
934    }
935
936    /// Starter config, as written by `magi init`.
937    pub fn starter_toml() -> String {
938        let detected = Self::autodetected();
939        let mut s = String::from(
940            "# magi — blind multi-agent implementation competition.\n\
941             # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
942             #   -> blind judging -> deliberation -> private final vote\n\
943             #   -> fold losers -> review + E2E loop -> gate -> merge.\n\
944             #\n\
945             # Rendered by teravars: a `[vars]` table, env\n\
946             # and system lookups, and `include = [...]` all work. Tera\n\
947             # braces are live everywhere in this file, but comments are\n\
948             # stripped before rendering (teravars >= 0.2.2), so a comment\n\
949             # may quote `{{ ... }}` freely.\n\
950             #\n\
951             # Layers deep-merge in increasing\n\
952             # precedence, so the roster can live once per machine in\n\
953             # <config_dir>/magi/config.toml and each repo only states its own\n\
954             # gate:\n\
955             #   <config_dir>/magi/config.toml  <  .magi/config.toml  <  magi.toml\n\n\
956             [vars]\n\
957             # Reference it as vars.cache inside Tera braces, anywhere below.\n\
958             # Single quotes inside the braces: teravars renders the raw file\n\
959             # text, so TOML's own \\\" escaping never reaches Tera.\n\
960             cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
961        );
962        if detected.agents.is_empty() {
963            s.push_str(
964                "# No agent CLI was found on PATH. Fill this in by hand.\n\
965                 # kind = claude | opencode | antigravity | codex | command\n\
966                 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
967            );
968        } else {
969            for a in &detected.agents {
970                s.push_str("[[agents]]\n");
971                s.push_str(&format!("id = {:?}\n", a.id));
972                s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
973                if let Some(m) = &a.model {
974                    s.push_str(&format!("model = {m:?}\n"));
975                }
976                s.push('\n');
977            }
978        }
979        s.push_str(
980            "# Leave a role list empty to rotate through the roster.\n\
981             [roles]\n\
982             implementers = []\n\
983             judges = []\n\
984             reviewers = []\n\n\
985             [graph]\n\
986             candidates = 3\n\
987             judges = 3\n\
988             deliberate_rounds = 1\n\
989             reviewers = 2\n\
990             review_rounds = 6\n\
991             max_parallel = 4\n\
992             language = \"en\"\n\
993             # One CLI conversation per seat: judges keep their own argument\n\
994             # across deliberation, the fixer keeps its implementation context.\n\
995             sessions = true\n\n\
996             [verify]\n\
997             # Run once per review round in the winner's worktree; failures are\n\
998             # fed back to the fixer.\n\
999             e2e = []\n\
1000             # Final gate. Every command must exit 0 before a merge.\n\
1001             gate = []\n\n\
1002             [merge]\n\
1003             # none | local | pr\n\
1004             mode = \"none\"\n\n\
1005             [update]\n\
1006             # off | notify | install — checked in the background, throttled.\n\
1007             mode = \"notify\"\n\
1008             # interval = \"24h\"\n",
1009        );
1010        s
1011    }
1012}
1013
1014/// Is `program` on `PATH`?
1015pub fn which(program: &str) -> bool {
1016    let Some(paths) = std::env::var_os("PATH") else {
1017        return false;
1018    };
1019    let exts: Vec<String> = std::env::var("PATHEXT")
1020        .map(|v| v.split(';').map(|e| e.to_lowercase()).collect())
1021        .unwrap_or_default();
1022    std::env::split_paths(&paths).any(|dir| {
1023        let direct = dir.join(program);
1024        if direct.is_file() {
1025            return true;
1026        }
1027        exts.iter().any(|ext| {
1028            let mut name = program.to_owned();
1029            name.push_str(ext);
1030            dir.join(name).is_file()
1031        })
1032    })
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037    use super::*;
1038
1039    fn spec(id: &str) -> AgentSpec {
1040        AgentSpec {
1041            id: id.to_owned(),
1042            kind: AgentKind::Command,
1043            model: None,
1044            command: vec!["true".to_owned()],
1045            extra_args: Vec::new(),
1046            env: BTreeMap::new(),
1047            prompt_delivery: None,
1048        }
1049    }
1050
1051    #[test]
1052    fn empty_roles_rotate_judges_off_their_own_candidate() {
1053        // Three seats, said out loud: this is a test about *rotation*, and it
1054        // has nothing to say about how many candidates a task buys by default.
1055        let cfg = Config {
1056            agents: vec![spec("a"), spec("b"), spec("c")],
1057            graph: Graph {
1058                candidates: 3,
1059                ..Graph::default()
1060            },
1061            ..Config::default()
1062        };
1063        let roles = cfg.resolve_roles().unwrap();
1064        let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
1065        let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
1066        assert_eq!(impls, ["a", "b", "c"]);
1067        assert_eq!(judges, ["b", "c", "a"]);
1068        for (i, j) in judges.iter().enumerate() {
1069            assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
1070        }
1071    }
1072
1073    #[test]
1074    fn single_agent_roster_fills_every_seat() {
1075        let cfg = Config {
1076            agents: vec![spec("solo")],
1077            graph: Graph {
1078                candidates: 3,
1079                ..Graph::default()
1080            },
1081            ..Config::default()
1082        };
1083        let roles = cfg.resolve_roles().unwrap();
1084        assert_eq!(roles.implementers.len(), 3);
1085        assert!(roles.judges.iter().all(|a| a.id == "solo"));
1086    }
1087
1088    #[test]
1089    fn explicit_roles_win() {
1090        let cfg = Config {
1091            agents: vec![spec("a"), spec("b")],
1092            roles: Roles {
1093                implementers: vec!["b".to_owned()],
1094                judges: vec!["a".to_owned()],
1095                reviewers: Vec::new(),
1096                fixer: Some("a".to_owned()),
1097                ..Roles::default()
1098            },
1099            ..Config::default()
1100        };
1101        let roles = cfg.resolve_roles().unwrap();
1102        assert!(roles.implementers.iter().all(|a| a.id == "b"));
1103        assert!(roles.judges.iter().all(|a| a.id == "a"));
1104        assert_eq!(roles.fixer.unwrap().id, "a");
1105    }
1106
1107    #[test]
1108    fn unknown_agent_id_is_an_error() {
1109        let cfg = Config {
1110            agents: vec![spec("a")],
1111            roles: Roles {
1112                judges: vec!["nope".to_owned()],
1113                ..Roles::default()
1114            },
1115            ..Config::default()
1116        };
1117        assert!(cfg.resolve_roles().is_err());
1118    }
1119
1120    #[test]
1121    fn empty_roster_is_an_error() {
1122        assert!(Config::default().resolve_roles().is_err());
1123    }
1124
1125    #[test]
1126    fn repos_default_to_no_roots_and_a_day_of_trust() {
1127        assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
1128        assert_eq!(Config::default().repos.scan_ttl, 86_400);
1129    }
1130
1131    #[test]
1132    fn a_config_file_with_no_repos_table_still_loads() {
1133        let dir = tempfile::tempdir().unwrap();
1134        let path = dir.path().join("magi.toml");
1135        std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
1136        let cfg = Config::load(&path).expect("must load without [repos]");
1137        assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
1138        assert_eq!(cfg.repos.scan_ttl, 86_400);
1139    }
1140
1141    /// A fixture is the whole config under test.
1142    ///
1143    /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
1144    /// a machine where somebody had written `<config_dir>/magi/config.toml`
1145    /// the suite silently loaded it as the lowest layer. Adding `[repos]
1146    /// roots` there turned two web tests red - their fixtures declare
1147    /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
1148    /// array key spread across two layers. CI stayed green throughout,
1149    /// because a runner has no such file: the suite failed only where magi is
1150    /// actually used.
1151    ///
1152    /// So a test build has no machine layer unless it asks for one, and this
1153    /// is that promise. Written against a real file at the real location so
1154    /// it fails if `machine_layer` starts reading it again.
1155    #[test]
1156    fn a_test_build_does_not_read_the_operators_machine_config() {
1157        let repo = tempfile::tempdir().unwrap();
1158        std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
1159
1160        let layers = Config::layers(repo.path());
1161        assert_eq!(
1162            layers,
1163            vec![repo.path().join("magi.toml")],
1164            "only the fixture's own file may be a layer"
1165        );
1166        if let Some(real) = dirs::config_dir() {
1167            let machine = real.join("magi").join("config.toml");
1168            assert!(
1169                !layers.contains(&machine),
1170                "the operator's {} must not be a layer in a test build",
1171                machine.display()
1172            );
1173        }
1174    }
1175
1176    #[test]
1177    fn starter_toml_loads_through_teravars() {
1178        let dir = tempfile::tempdir().unwrap();
1179        let path = dir.path().join("magi.toml");
1180        std::fs::write(&path, Config::starter_toml()).unwrap();
1181        let parsed = Config::load(&path).expect("starter config must load");
1182        assert_eq!(parsed.graph.candidates, 3);
1183        assert_eq!(parsed.merge.mode, MergeMode::None);
1184        assert!(parsed.graph.sessions);
1185        assert_eq!(parsed.update.mode, UpdateMode::Notify);
1186    }
1187
1188    #[test]
1189    fn later_layers_win_and_vars_render() {
1190        let dir = tempfile::tempdir().unwrap();
1191        let machine = dir.path().join("machine.toml");
1192        let project = dir.path().join("magi.toml");
1193        // The machine layer owns the roster...
1194        std::fs::write(
1195            &machine,
1196            "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
1197             [graph]\ncandidates = 3\nmax_parallel = 8\n",
1198        )
1199        .unwrap();
1200        // ...and the project layer only states what is repo-specific, plus a
1201        // `[vars]` value interpolated into a command.
1202        std::fs::write(
1203            &project,
1204            "[vars]\ncache = \"/shared\"\n\n\
1205             [graph]\ncandidates = 2\n\n\
1206             [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
1207        )
1208        .unwrap();
1209
1210        let cfg = Config::load_layers(&[machine, project]).expect("layered load");
1211        assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
1212        assert_eq!(cfg.graph.candidates, 2, "project layer wins");
1213        assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
1214        assert_eq!(
1215            cfg.verify.gate,
1216            ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
1217        );
1218        // The rendered command is where the cache path is read back from.
1219        assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
1220    }
1221
1222    #[test]
1223    fn the_disk_defaults_are_the_measurements_made_up_front() {
1224        let cfg = Config::default();
1225        assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
1226        assert!(cfg.disk.auto_fold);
1227        assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
1228        assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
1229    }
1230
1231    #[test]
1232    fn an_unset_disk_section_is_the_safe_default() {
1233        let dir = tempfile::tempdir().unwrap();
1234        std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
1235        let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
1236        assert_eq!(cfg.disk, Disk::default());
1237    }
1238
1239    #[test]
1240    fn env_is_available_to_templates_with_a_default() {
1241        let dir = tempfile::tempdir().unwrap();
1242        let path = dir.path().join("magi.toml");
1243        // teravars ships no `env`; magi adds it, and the `default` filter has
1244        // to cover the unset case or every machine would need the variable.
1245        //
1246        // Deliberately no named variable: `env` is keyed by the exact spelling
1247        // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
1248        // test asserting `env.PATH` passes on one runner and fails on another.
1249        // The map's non-emptiness is the platform-neutral claim.
1250        std::fs::write(
1251            &path,
1252            "[verify]\n\
1253             gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
1254             \"populated={{ env | length > 0 }}\"]\n",
1255        )
1256        .unwrap();
1257        let cfg = Config::load(&path).expect("env lookup must render");
1258        assert_eq!(cfg.verify.gate[0], "cache=fallback");
1259        assert_eq!(cfg.verify.gate[1], "populated=true");
1260    }
1261
1262    #[test]
1263    fn a_broken_template_names_the_file() {
1264        let dir = tempfile::tempdir().unwrap();
1265        let path = dir.path().join("magi.toml");
1266        std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
1267        let err = Config::load(&path).expect_err("must not silently ignore");
1268        assert!(err.to_string().contains("teravars"), "{err}");
1269    }
1270
1271    #[test]
1272    fn tera_syntax_in_comments_is_inert() {
1273        // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
1274        // comment may quote template syntax without rendering. Before 0.2.2 this
1275        // load failed: the commented-out braces reached the template parser.
1276        let dir = tempfile::tempdir().unwrap();
1277        let path = dir.path().join("magi.toml");
1278        std::fs::write(
1279            &path,
1280            "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
1281             [graph]\ncandidates = 2\n",
1282        )
1283        .unwrap();
1284        let cfg = Config::load(&path).expect("comments must be inert, not rendered");
1285        assert_eq!(cfg.graph.candidates, 2);
1286    }
1287
1288    #[test]
1289    fn opencode_defaults_to_file_delivery() {
1290        let mut s = spec("oc");
1291        s.kind = AgentKind::Opencode;
1292        assert_eq!(s.delivery(), Delivery::File);
1293        s.prompt_delivery = Some(Delivery::Argv);
1294        assert_eq!(s.delivery(), Delivery::Argv);
1295    }
1296    #[test]
1297    fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
1298        // Both default on, and that pair is the safety property: `land` takes
1299        // over the watching an operator was doing by hand, `land_approval`
1300        // keeps the irreversible step a human decision. An unattended merge
1301        // needs BOTH flipped, which has to be chosen deliberately twice.
1302        let g = Graph::default();
1303        assert!(
1304            g.land,
1305            "stopping at an open PR left the watching to a human"
1306        );
1307        assert!(
1308            g.land_approval,
1309            "on-by-default land is only defensible while this is also on"
1310        );
1311        assert!(g.land_rounds > 0, "a loop with no budget never terminates");
1312    }
1313    #[test]
1314    fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
1315        // teravars appends arrays. For an ordered list of seats, or an argv,
1316        // the concatenation is something neither file says - and the operator
1317        // pays for the extra seats by the token.
1318        let dir = tempfile::tempdir().unwrap();
1319        let machine = dir.path().join("machine.toml");
1320        let repo = dir.path().join("magi.toml");
1321        std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
1322        std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
1323
1324        let err = Config::load_layers(&[machine.clone(), repo.clone()])
1325            .expect_err("two layers naming one array must not merge silently")
1326            .to_string();
1327        assert!(err.contains("roles.implementers"), "{err}");
1328        // Both files are named: the fix is to delete one of them, and the
1329        // operator has to know which two to choose between.
1330        assert!(err.contains("machine.toml"), "{err}");
1331        assert!(err.contains("magi.toml"), "{err}");
1332    }
1333
1334    #[test]
1335    fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
1336        // The split the layering exists for: state a preference machine-wide,
1337        // let the repository own its own lists.
1338        let dir = tempfile::tempdir().unwrap();
1339        let machine = dir.path().join("machine.toml");
1340        let repo = dir.path().join("magi.toml");
1341        std::fs::write(&machine, "[roles]\nplanner = \"opus\"\n").unwrap();
1342        std::fs::write(
1343            &repo,
1344            "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
1345             [roles]\nimplementers = [\"oc\"]\n",
1346        )
1347        .unwrap();
1348
1349        let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
1350        assert_eq!(cfg.roles.planner.as_deref(), Some("opus"));
1351        assert_eq!(cfg.roles.implementers, ["oc"]);
1352        assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
1353    }
1354}