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