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