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