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//! Layers, lowest precedence first: `<config_dir>/magi/config.toml` (machine),
5//! `.magi/config.toml`, `magi.toml`. With none, built-in defaults apply, the
6//! agent roster derived from the agent CLIs actually installed on this
7//! machine. `--config <path>` replaces the whole stack with that one file.
8//!
9//! **The repository layers are read from `<remote>/<base>`, never from the
10//! working tree.** A primary checkout is often stale or on a detached HEAD, so
11//! a gate read from it can be older than the one the branch under review is
12//! cut from (run ce6e failed on a gate step `origin/main` had already
13//! dropped). `git show <sha>:magi.toml` of the remote-tracking ref's commit is
14//! written to a content-addressed directory under the git common dir
15//! (`<common>/magi/config/<sha>-<hash of repo>/`, temp dir when that is not
16//! writable) and loaded from there.
17//!
18//! `remote` and `base` are themselves in the file, so they are resolved in a
19//! fixed order, first hit wins:
20//!
21//! 1. `[merge] base` / `remote` of the machine layer, rendered as a real load
22//!    would (env templates, includes);
23//! 2. the same keys, read minimally (only `[merge]`, nothing deserialized into
24//!    `Config`) from the checkout's `magi.toml`, then `.magi/config.toml` -
25//!    only to *locate* the ref; an unreadable file is ignored;
26//! 3. `remote` defaults to `origin`, `base` to what
27//!    `refs/remotes/<remote>/HEAD` points at.
28//!
29//! [`Config::discover`] is synchronous and reads the remote-tracking ref as it
30//! is (`daemon::fetch_loop` keeps it fresh); [`Config::discover_fetched`] runs
31//! `git fetch` first and is what every path that starts work uses. A failed
32//! fetch, a missing ref or an unresolvable base is an **error**, never a
33//! silent fall back to the working tree or a local branch. Two cases are not
34//! that: an explicit `--config`, and a `repo` that is not a git working tree
35//! at all (no branch exists, so nothing can be stale).
36//!
37//! A repository layer that declares `include = [...]` gets the whole tree of
38//! that commit extracted, so relative includes resolve against the same
39//! commit. The directory is built beside its name and renamed in, so a
40//! concurrent `discover` never reads a half-written layer.
41use std::collections::BTreeMap;
42use std::path::{Path, PathBuf};
43
44use anyhow::{Context as _, Result, bail};
45use serde::{Deserialize, Serialize};
46
47/// Which CLI drives an agent.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
49#[serde(rename_all = "lowercase")]
50pub enum AgentKind {
51    /// Anthropic Claude Code (`claude -p`).
52    Claude,
53    /// opencode (`opencode run`).
54    Opencode,
55    /// Antigravity CLI (`agy -p`). Gemini CLI is deliberately absent: Google
56    /// retired the standalone client for individual accounts in favour of this
57    /// one, so an adapter for it would be dead code on a live machine.
58    Antigravity,
59    /// OpenAI Codex CLI (`codex exec`). The one roster member with a real
60    /// read-only mode: `--sandbox read-only` is enforced by the CLI, not by
61    /// the prompt.
62    Codex,
63    /// oh-my-pi (`omp -p --mode=json`). Another CLI with no read-only mode of
64    /// its own - `--auto-approve` gates reads and writes together - so a
65    /// read-only seat rests on the prompt and on the worktree discipline the
66    /// other non-codex seats already rely on. It is also the roster member that
67    /// reaches DeepSeek, whose models ship in `omp`'s own catalog.
68    Omp,
69    /// Arbitrary command. The escape hatch, and what the test suite drives.
70    Command,
71}
72
73impl AgentKind {
74    /// Executable that must be on `PATH` for this kind, if any.
75    pub fn program(self) -> Option<&'static str> {
76        match self {
77            Self::Claude => Some("claude"),
78            Self::Opencode => Some("opencode"),
79            Self::Antigravity => Some("agy"),
80            Self::Codex => Some("codex"),
81            Self::Omp => Some("omp"),
82            Self::Command => None,
83        }
84    }
85
86    /// Lowercase name as written in the config file.
87    pub fn as_str(self) -> &'static str {
88        match self {
89            Self::Claude => "claude",
90            Self::Opencode => "opencode",
91            Self::Antigravity => "antigravity",
92            Self::Codex => "codex",
93            Self::Omp => "omp",
94            Self::Command => "command",
95        }
96    }
97
98    /// Every kind the roster can name, in display order.
99    ///
100    /// This is what `magi doctor` lists, and it has to be one list rather than
101    /// the same set typed out again wherever a kind is enumerated. The last
102    /// time it was typed out twice, `omp` was added as a roster member and the
103    /// doctor output went on saying the machine had four CLIs - which reads as
104    /// "that agent is not installed" to the person the command exists for.
105    pub const ALL: [Self; 6] = [
106        Self::Claude,
107        Self::Opencode,
108        Self::Antigravity,
109        Self::Codex,
110        Self::Omp,
111        Self::Command,
112    ];
113}
114
115/// How the prompt reaches the agent process.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
117#[serde(rename_all = "lowercase")]
118pub enum Delivery {
119    /// Piped on stdin.
120    Stdin,
121    /// Passed as a positional argument. Beware OS command-line limits.
122    Argv,
123    /// Written to a file; the agent is told to read it. No length limit.
124    File,
125}
126
127/// One addressable agent in the roster.
128#[derive(Debug, Clone, Deserialize, Serialize)]
129#[serde(deny_unknown_fields)]
130pub struct AgentSpec {
131    /// Stable identifier used by `[roles]` and by the stats tables.
132    pub id: String,
133    /// Which CLI to drive.
134    pub kind: AgentKind,
135    /// Model passed through to the CLI (`--model` / `-m`). CLI default if unset.
136    #[serde(default)]
137    pub model: Option<String>,
138    /// `kind = "command"` only: argv. Supports `{prompt_file}`, `{cwd}`,
139    /// `{label}`, `{session}` placeholders.
140    #[serde(default)]
141    pub command: Vec<String>,
142    /// Extra arguments appended to the built command line.
143    #[serde(default)]
144    pub extra_args: Vec<String>,
145    /// Extra environment variables for the child process.
146    #[serde(default)]
147    pub env: BTreeMap<String, String>,
148    /// Override the per-kind prompt delivery default.
149    #[serde(default)]
150    pub prompt_delivery: Option<Delivery>,
151}
152
153impl AgentSpec {
154    /// Default prompt delivery for this agent.
155    ///
156    /// `opencode` and `agy` take the prompt as an argument, which on Windows
157    /// caps out around 32 KiB — well under a judging prompt carrying three
158    /// patches — so both get a file instead.
159    pub fn delivery(&self) -> Delivery {
160        self.prompt_delivery.unwrap_or(match self.kind {
161            AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
162            // `codex exec -` reads the prompt from stdin, so the whole
163            // instruction arrives without an argv length limit and without a
164            // tool round-trip to open a file.
165            AgentKind::Codex => Delivery::Stdin,
166            // `omp -p` reads the prompt from stdin too, and a judging prompt
167            // carrying three patches is well past the Windows argv cap, so this
168            // is the only delivery that works for every node.
169            AgentKind::Omp => Delivery::Stdin,
170            AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
171        })
172    }
173
174    /// Human-facing label, e.g. `opus (claude:opus)`.
175    pub fn display(&self) -> String {
176        match &self.model {
177            Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
178            None => format!("{} ({})", self.id, self.kind.as_str()),
179        }
180    }
181}
182
183/// A standalone seat's agent: one roster id, or an ordered fallback chain.
184///
185/// The string form is what every existing config uses and serializes back as
186/// a string; the array form tries each id at most once, in order, moving on
187/// when a call ends in quota or fails (see [`crate::agent::pick_chain`]).
188/// An empty string or array is the same as unset.
189#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
190#[serde(untagged)]
191pub enum AgentChoice {
192    /// One agent id.
193    One(String),
194    /// Ordered fallback chain of agent ids.
195    Chain(Vec<String>),
196}
197
198impl AgentChoice {
199    /// The ids named, in order, with blanks dropped. Empty means unset.
200    pub fn ids(&self) -> Vec<&str> {
201        let all: Vec<&str> = match self {
202            Self::One(id) => vec![id.as_str()],
203            Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
204        };
205        all.into_iter()
206            .map(str::trim)
207            .filter(|id| !id.is_empty())
208            .collect()
209    }
210
211    /// The first id named, if any.
212    pub fn primary(&self) -> Option<&str> {
213        self.ids().into_iter().next()
214    }
215}
216
217impl From<&str> for AgentChoice {
218    fn from(id: &str) -> Self {
219        Self::One(id.to_owned())
220    }
221}
222
223/// The first id of an optional choice: what a single-seat caller resolves.
224pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
225    choice.and_then(AgentChoice::primary)
226}
227
228/// Explicit role assignment. Empty lists are filled in by
229/// [`Config::resolve_roles`] by rotating the roster.
230#[derive(Debug, Clone, Default, Deserialize, Serialize)]
231#[serde(deny_unknown_fields, default)]
232pub struct Roles {
233    /// Agents that implement the task, one worktree each.
234    pub implementers: Vec<String>,
235    /// Agents that rank the candidates blind.
236    pub judges: Vec<String>,
237    /// Agents that review the winning patch.
238    pub reviewers: Vec<String>,
239    /// Agent that applies review findings. Defaults to the winner's author.
240    ///
241    /// Accepts one id or an ordered array of ids: a fallback chain, see
242    /// [`AgentChoice`]. The review loop, the gate-fix round, `land`'s fix
243    /// rounds and the rebase conflict round move to the next id when one
244    /// errors, hits its quota or answers nothing usable; each id is tried at
245    /// most once per call, and once a fallback answered, the rest of the run
246    /// starts from it (see `crate::fixer`). Unset keeps the winner's author.
247    pub fixer: Option<AgentChoice>,
248    /// Agent that answers the standing chat's turns (`src/talk.rs`).
249    ///
250    /// Unset picks a `claude` seat, else the first runnable agent in roster
251    /// order (see [`crate::agent::pick`]) - which is roster *order*, not a
252    /// judgement about who converses well. Naming one here matters once an
253    /// agent is also sitting as a judge: the chat is opened far more often
254    /// than any single competition, and every open competes with that judge
255    /// seat for the same account's concurrency. A timeout on an ordinary chat
256    /// turn traced to exactly this - `opus` triple-booked as chatter and judge
257    /// - is what this field exists to let an operator break apart.
258    ///
259    /// Accepts one id or an ordered array of ids: a fallback chain, see
260    /// [`AgentChoice`].
261    pub chatter: Option<AgentChoice>,
262    /// Agent that arranges the queue between polls: `crate::conduct`'s single
263    /// seat, called once per cycle to decide a runnable task's `blocked_by`
264    /// and how a stalled or finished task recovers.
265    ///
266    /// The same precedent as [`Self::chatter`] for a seat that stands alone
267    /// rather than rotating through the roster - resolved through
268    /// [`crate::agent::pick`], so unset falls back to its own default order
269    /// (a claude seat, else the first runnable agent) rather than reusing a
270    /// judge or reviewer seat that the conductor's own poll-cycle cadence
271    /// would otherwise compete with for the same account's concurrency.
272    ///
273    /// Accepts a string or a fallback chain, like [`Self::chatter`].
274    pub conductor: Option<AgentChoice>,
275    /// Seats for the design-deliberation stage `graph::Runner::advise` runs
276    /// before `implement`: independent, read-only design proposals gathered
277    /// once a run has a settled task instruction and before any implementer
278    /// touches the repository.
279    ///
280    /// Empty falls back to `judges` rather than to the whole roster: a panel
281    /// trusted to rank patches independently is exactly the panel worth
282    /// asking to sketch a design independently, and an operator who has
283    /// already thought about judge diversity gets advisor diversity for free
284    /// instead of a fourth roster to maintain.
285    pub advisors: Vec<String>,
286    /// Agent that blends [`Self::advisors`]' proposals into the one design
287    /// brief `graph::Runner::synthesize_brief` carries into every
288    /// implementer's prompt.
289    ///
290    /// The same precedent as [`Self::chatter`] and [`Self::conductor`] for a
291    /// seat that stands alone rather than rotating through the roster -
292    /// resolved through [`crate::agent::pick`], so unset falls back to its
293    /// own default order (a claude seat, else the first runnable agent in
294    /// roster order) - exactly today's behavior, unchanged by leaving this
295    /// field out.
296    ///
297    /// Accepts a string or a fallback chain, like [`Self::chatter`].
298    pub synthesizer: Option<AgentChoice>,
299    /// Agent (normally a `kind = "command"` wrapper around Jev) that decides
300    /// whether a pull request title and prose are English, for
301    /// [`crate::github_text`]'s posting gate.
302    ///
303    /// Unset spawns nothing: the gate keeps its built-in heuristics. Set, a
304    /// failed, timed-out or unparsable call also falls back to them, so the
305    /// gate never depends on this seat being reachable. Accepts a string or a
306    /// fallback chain, like [`Self::chatter`].
307    pub language_judge: Option<AgentChoice>,
308}
309
310/// Graph shape and limits.
311#[derive(Debug, Clone, Deserialize, Serialize)]
312#[serde(deny_unknown_fields, default)]
313pub struct Graph {
314    /// Gate GitHub prose before posting. Secret redaction remains mandatory when disabled.
315    pub github_text_guard: bool,
316    /// Parallel implementations of the same task (the number of implementer
317    /// seats; pairs with [`Roles::implementers`]). **One by default.**
318    ///
319    /// Formerly `candidates`, still read as a deprecated alias.
320    ///
321    /// Competition is the thing magi is for, and it is still here - it is just
322    /// no longer what every task buys without being asked. Three days and 13
323    /// runs on this repository, which is the workload these numbers are drawn
324    /// from:
325    ///
326    /// - **0 of 13** competed runs reached a merge. Everything that landed in
327    ///   that window went through `magi review` - the cheap half, no
328    ///   competition - and passed on the first try.
329    /// - The judges' first choices **split 73% of the time** (8 of 11
330    ///   tallies). Candidates that close together make the ranking a weak
331    ///   signal for what it costs to produce.
332    /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
333    ///   review 28min, **verify 5min** - and verify is the node that caught a
334    ///   defect every reviewer had passed as clean. The cheapest step is the
335    ///   one that earns its place every time.
336    ///
337    /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
338    /// single-seat default would have shipped the worse implementation in
339    /// roughly a quarter of them. That is exactly why this is a *default* and
340    /// not a removal - `magi run --candidates N` and a per-task seat count are
341    /// how a task that deserves a competition gets one.
342    ///
343    /// A single-candidate run needs no special case: `Runner::review`'s doc
344    /// records that `execute` already degrades to implement -> review -> gate
345    /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
346    /// no two first choices to reconcile and `vote` returns early.
347    #[serde(alias = "candidates")]
348    pub implementers: usize,
349    /// Independent judges.
350    pub judges: usize,
351    /// Deliberation rounds when the judges' first choices disagree.
352    pub deliberate_rounds: usize,
353    /// Reviewers per review round. **Three by default** - the smallest panel
354    /// a lens cycle (see [`crate::prompt::Lens`]) covers exactly once, so the
355    /// default panel reads the patch for spec compliance, regressions, and
356    /// simplicity without repeating an angle. Review is also the one stage
357    /// [`Self::implementers`]'s doc describes as running on every task
358    /// regardless of competition, which is what makes a panel worth its cost
359    /// here even though `implementers` itself defaults to one.
360    pub reviewers: usize,
361    /// Maximum review+fix rounds before the run is declared blocked.
362    pub review_rounds: usize,
363    /// Fix rounds a failing `verify.gate` gets before the run is blocked. The
364    /// fixer is handed the gate's own output; `0` keeps the old behaviour of
365    /// blocking on the first red gate. Independent of [`Self::review_rounds`]
366    /// so a run that spent its review budget can still repair a one-line gate
367    /// failure.
368    pub gate_fix_rounds: usize,
369    /// Maximum agent processes running at once.
370    pub max_parallel: usize,
371    /// Language for the prose the agents write (`en` / `ja` / any language name).
372    pub language: String,
373    /// Keep one CLI conversation per seat, so a judge remembers its own
374    /// argument across deliberation rounds and the fixer remembers its own
375    /// implementation across review rounds.
376    ///
377    /// Sessions are scoped to a *seat*, never to an agent id: the same model
378    /// sitting as implementer and as judge gets two unrelated conversations,
379    /// which is what keeps blind judging blind.
380    pub sessions: bool,
381    /// Per-node timeouts, seconds.
382    pub timeout_implement: u64,
383    /// Per-node timeouts, seconds.
384    pub timeout_judge: u64,
385    /// Per-node timeouts, seconds.
386    pub timeout_review: u64,
387    /// Timeout for `verify.e2e` and `verify.gate`, seconds. Separate from
388    /// [`Self::timeout_review`] so shrinking a reviewer's budget cannot
389    /// silently shrink a real-machine command's budget too — the two used to
390    /// share `timeout_review`, and turning a slow reviewer down cut the
391    /// timeout `cargo test --all-targets` runs under along with it. When
392    /// omitted, preserves legacy configurations by using
393    /// [`Self::timeout_review`]. Set an explicit value to make verification
394    /// independent of later review-seat budget changes.
395    pub timeout_verify: Option<u64>,
396    /// Per-node timeouts, seconds.
397    pub timeout_fix: u64,
398    /// Wall-clock limit for one turn of [`crate::talk`]'s standing
399    /// conversation, seconds.
400    ///
401    /// An hour: the operator is not watching this turn resolve in real time,
402    /// so the budget can match what the work - reading files, running
403    /// commands, checking their output - actually needs rather than what a
404    /// person waiting on a phone can tolerate.
405    pub timeout_talk: u64,
406    /// Retries for an agent invocation that fails or returns nothing usable.
407    pub retries: usize,
408    /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
409    pub worktree_root: Option<PathBuf>,
410    /// After the pull request is open, keep going: watch its checks and
411    /// reviews, run a fix round when they are unhappy, and ask to merge.
412    ///
413    /// On, because stopping at an open pull request left the operator doing
414    /// the watching by hand - six times in the session this was built in - and
415    /// that is the work the loop exists to take. It only engages for
416    /// `merge = "pr"`; every other merge mode ends the run as before.
417    ///
418    /// Turning this on does **not** hand magi the merge button:
419    /// [`Graph::land_approval`] is on too, and nothing merges without an
420    /// explicit answer. Setting both to their non-defaults is the only way to
421    /// get an unattended merge, and it has to be chosen twice.
422    pub land: bool,
423    /// Land rounds - watch, fix, push - before the run is left for a human.
424    pub land_rounds: usize,
425    /// When `land` sees a required check fail on the head it is bound to, rerun
426    /// that check's workflow run once (`gh run rerun <id> --failed`) before
427    /// spending a fix round on it. A run id is rerun at most once, recorded
428    /// before the call, and forgotten when the head moves; the rerun costs no
429    /// fix round and no attempt. A failure with no workflow run (an external
430    /// status) goes straight to the fixer. On; off sends every red check to
431    /// the fixer at once.
432    pub rerun_flaky_checks: bool,
433    /// Ask the owner before merging, showing what is about to land.
434    ///
435    /// On, and it is what makes `land` safe to have on: the question carries a
436    /// rendered panel - the diffstat, the patch, the checks, the review
437    /// comments that were addressed, and the subject the squash will use - so
438    /// the decision is made on evidence rather than on trust, from wherever
439    /// the operator happens to be.
440    ///
441    /// Silence is a hold. An unanswered approval never merges, and neither
442    /// does any answer other than the word `merge`.
443    pub land_approval: bool,
444    /// Ask the owner before merging a run whose review loop handed off over a
445    /// contested finding: the last round ended with a Major-or-above finding
446    /// still open *and* at least one reviewer's final vote (after
447    /// reconsideration) was reject. Findings raised in the last round are
448    /// never fixed or re-reviewed, so this is the one case an unattended
449    /// merge would land over a reviewer's explicit objection.
450    ///
451    /// On. Interaction with [`Self::land_approval`]: when that is on, every
452    /// merge is asked about and this key changes nothing. When it is off,
453    /// this key alone decides whether a contested hand-off is asked about
454    /// (the question says why); every other run still merges unattended.
455    /// Read at land time, so turning it off restores the unattended merge at
456    /// once. The pull request is opened either way; only the merge waits.
457    pub hold_contested_merge: bool,
458    /// After a run's pull request merges, file the findings its last review
459    /// round left open as follow-up tasks (`crate::followup`) instead of
460    /// letting them vanish with the merge: every Major-or-above finding, and
461    /// every finding of a seat whose final vote was reject. Other Minor/Nit
462    /// findings are only listed in the pull-request comment. Does not affect
463    /// whether the merge happens. On; best-effort, a failure is a run event.
464    pub file_followups: bool,
465    /// After a run's pull request merges, release the follow-up tasks the
466    /// merge approval's deputy filed held for that pull request
467    /// (`crate::followup::settle_deputy_tasks`): only a task the deputy filed
468    /// for this run whose hold reason names this pull request, exactly once,
469    /// and never one that duplicates an automatic follow-up (that one is left
470    /// held with the reason). The generation cap applies. Independent of
471    /// `file_followups`. On; off leaves them held until `magi task release`.
472    pub release_deputy_followups: bool,
473    /// How long to wait for an owner to answer a question before the run is
474    /// abandoned, seconds. A parked run costs nothing, so this is generous;
475    /// it exists so a forgotten question cannot pin a worktree forever.
476    pub answer_timeout: u64,
477    /// What a round does when one or more reviewer seats never answered
478    /// (timeout, crash, unparsable output).
479    pub incomplete_review: IncompleteReviewPolicy,
480    /// Run `verify.e2e` on every round, even one that already has blocking
481    /// findings and another round left to try.
482    ///
483    /// Off by default: a round with a blocking finding and rounds still left
484    /// is going back to the fixer regardless of what `verify.e2e` says, so
485    /// running it first only spends the round's slowest step (minutes, on a
486    /// Rust repo's `cargo test --all-targets`) on a head about to be
487    /// rewritten anyway. `verify.e2e` still runs once a round has no
488    /// blocking findings left (a round cannot go `clean` without it) and the
489    /// final `verify.gate` always runs on the actual tree that would land —
490    /// deferring is about *when* e2e runs mid-loop, never about skipping it.
491    ///
492    /// Set this to restore the old every-round diagnostic behaviour: e2e
493    /// output from a round that still has blocking findings is occasionally
494    /// useful on its own (a runtime failure a reviewer's panel would not
495    /// have caught by reading), and this is the way back to seeing it every
496    /// round instead of only once the panel has nothing left to flag.
497    pub e2e_every_round: bool,
498    /// Run the design-deliberation stage before `implement`: independent
499    /// advisor seats each sketch a design, and (when at least one produced a
500    /// usable proposal) a synthesis blends them into a brief carried in the
501    /// implementer's prompt. See `graph::Runner::advise`.
502    ///
503    /// On by default. A design sketch is a few paragraphs an agent can write
504    /// without touching the repository, where a full implementation is a
505    /// tool loop that re-reads the codebase on every turn - so three
506    /// sketches, gathered once before `implement` starts, cost a fraction of
507    /// a fourth candidate and buy back a form of the same disagreement
508    /// [`Self::implementers`]'s doc describes moving away from being the
509    /// default, on every run rather than only the ones an operator remembers
510    /// to ask for with `--implementers`.
511    pub advise: bool,
512    /// How many independent design proposals the deliberation stage gathers.
513    /// **Three by default** - the same number [`Self::implementers`]'s doc
514    /// names as the point where a fourth judge's first choice stopped
515    /// changing the tally.
516    pub advisors: usize,
517    /// After the tally picks a winner and before the review loop, a fixer
518    /// round ports the strengths the judges explicitly attributed to the
519    /// losing candidates onto the winner (`graph::Runner::graft`). Skipped
520    /// for a single candidate, a run with no winner or no quorum, and when
521    /// no judge recorded a strength for a loser. Best-effort: a failure, a
522    /// quota hit, no change or a diff over the size limit restores the
523    /// winner's pre-graft commit and the run carries on as if this were off.
524    /// On by default.
525    pub graft_runner_up: bool,
526}
527
528impl Default for Graph {
529    fn default() -> Self {
530        Self {
531            github_text_guard: true,
532            implementers: 1,
533            judges: 3,
534            deliberate_rounds: 1,
535            reviewers: 3,
536            review_rounds: 6,
537            gate_fix_rounds: 1,
538            max_parallel: 4,
539            language: "en".to_owned(),
540            sessions: true,
541            timeout_implement: 3600,
542            timeout_judge: 1200,
543            timeout_review: 1200,
544            timeout_verify: None,
545            timeout_fix: 1800,
546            timeout_talk: 3600,
547            retries: 1,
548            worktree_root: None,
549            land: true,
550            land_rounds: 4,
551            rerun_flaky_checks: true,
552            land_approval: true,
553            hold_contested_merge: true,
554            file_followups: true,
555            release_deputy_followups: true,
556            answer_timeout: 86_400,
557            incomplete_review: IncompleteReviewPolicy::Block,
558            e2e_every_round: false,
559            advise: true,
560            advisors: 3,
561            graft_runner_up: true,
562        }
563    }
564}
565
566impl Graph {
567    /// Effective machine-command budget. Older configuration files had only
568    /// `timeout_review`, which also governed verification, so absence is a
569    /// compatibility fallback rather than a new 1200-second default.
570    pub fn verify_timeout(&self) -> u64 {
571        self.timeout_verify.unwrap_or(self.timeout_review)
572    }
573}
574
575/// What a review round does when a reviewer seat never answered.
576///
577/// A round where half the panel timed out is not evidence of a clean patch —
578/// it is evidence of nothing. The default refuses to call that clean; `warn`
579/// exists for an operator who would rather keep a flaky seat from stalling
580/// every run, and accepts that the gap is on them to read in the report.
581#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
582#[serde(rename_all = "lowercase")]
583pub enum IncompleteReviewPolicy {
584    /// A round with a missing seat is never `clean`: with nothing raised to
585    /// fix, the round is re-reviewed instead of gating; with the max rounds
586    /// exhausted, the run is left `Blocked` rather than declared ready.
587    Block,
588    /// A round with a missing seat can still gate as clean, once every seat
589    /// that *did* answer raised nothing blocking and verification is green.
590    /// The record keeps the gap visible (`magi show`, `magi stats`) even
591    /// though the run does not wait on it.
592    Warn,
593}
594
595/// What to do when vendor-identifying text is found in material shown to judges.
596#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
597#[serde(rename_all = "lowercase")]
598pub enum LeakPolicy {
599    /// Record the leak, show the patch unmodified.
600    Warn,
601    /// Replace the token with `[REDACTED]` in the presented patch.
602    Redact,
603    /// Abort the run.
604    Fail,
605}
606
607/// Blindness policy.
608///
609/// Commit messages and candidate summaries are *always* stripped of
610/// attribution trailers and redacted — that is where signatures actually
611/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
612/// redaction would corrupt the artifact under judgement.
613#[derive(Debug, Clone, Deserialize, Serialize)]
614#[serde(deny_unknown_fields, default)]
615pub struct Blind {
616    /// Install a per-worktree `commit-msg` hook that deletes attribution
617    /// trailers before they can land in a candidate's history.
618    pub commit_msg_hook: bool,
619    /// Literal, case-insensitive substrings. A line containing any of them is
620    /// dropped from commit messages and summaries; the `commit-msg` hook is
621    /// generated from the same list.
622    pub strip_lines: Vec<String>,
623    /// Case-insensitive substrings that identify a vendor or model.
624    pub vendor_tokens: Vec<String>,
625    /// Policy for vendor tokens found in the patch body.
626    pub on_leak: LeakPolicy,
627    /// Seed for label assignment and per-judge presentation order. Derived from
628    /// the run id when unset; set it to make a run reproducible.
629    pub seed: Option<u64>,
630}
631
632impl Default for Blind {
633    fn default() -> Self {
634        Self {
635            commit_msg_hook: true,
636            strip_lines: [
637                "Co-Authored-By:",
638                "Signed-off-by:",
639                "Assisted-by:",
640                "Generated-by:",
641                "Generated with",
642                "\u{1f916}",
643            ]
644            .iter()
645            .map(|s| (*s).to_owned())
646            .collect(),
647            vendor_tokens: [
648                "claude",
649                "anthropic",
650                "codex",
651                "openai",
652                "chatgpt",
653                "gemini",
654                "grok",
655                "xai",
656                "copilot",
657                "opencode",
658                "qoder",
659                "cursor",
660                "\u{1f916}",
661            ]
662            .iter()
663            .map(|s| (*s).to_owned())
664            .collect(),
665            on_leak: LeakPolicy::Warn,
666            seed: None,
667        }
668    }
669}
670
671/// Shell commands that gate the winner.
672#[derive(Debug, Clone, Default, Deserialize, Serialize)]
673#[serde(deny_unknown_fields, default)]
674pub struct Verify {
675    /// Run in the winner's worktree once per review round. Its output is fed
676    /// back to the fixer. This is the "real machine" leg of the review.
677    pub e2e: Vec<String>,
678    /// Final gate. Must all exit 0 before a merge is attempted.
679    pub gate: Vec<String>,
680    /// Mechanical fixers (formatters) run in the winner's worktree just before
681    /// `gate`, after review is clean. Anything they change is committed as one
682    /// neutral-identity commit so the gate and the PR see it. A command that
683    /// fails or times out is a warning, never a failed run: the gate stays the
684    /// single arbiter. Empty (the default) turns the feature off. Runs under
685    /// `graph.verify_timeout()` per command, like the gate. Meant for light
686    /// tools: it is not scanned for `CARGO_TARGET_DIR`, and it should be
687    /// idempotent since a resumed run may repeat it.
688    #[serde(default)]
689    pub pre_gate: Vec<String>,
690    /// Shell used to run the commands above. Defaults to `sh -c`, or
691    /// `cmd /C` when `sh` is not on `PATH`.
692    pub shell: Option<Vec<String>>,
693}
694
695impl Verify {
696    /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
697    /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
698    /// this reads back. One rendering is enough - they all set the same
699    /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
700    /// command is checked before the gate because the e2e rebuilds the crate.
701    pub fn cache_dir(&self) -> Option<PathBuf> {
702        self.e2e
703            .iter()
704            .chain(self.gate.iter())
705            .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
706    }
707
708    /// Every `--manifest-path` the e2e and gate commands pass to cargo, for the
709    /// shared cache's freshness check in repositories with no root manifest.
710    pub fn cargo_manifests(&self) -> Vec<PathBuf> {
711        let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
712        crate::cache::extract_manifest_paths(&all)
713    }
714}
715
716/// Per-repository worktree preparation, run right after magi creates a worktree.
717#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
718#[serde(deny_unknown_fields, default)]
719pub struct Worktree {
720    /// Ordered steps. Declare in one layer only. Empty (the default) changes
721    /// nothing. See [`crate::worktree_setup`].
722    pub setup: Vec<SetupStep>,
723}
724
725/// One setup step: exactly one of `copy` / `run`.
726#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
727#[serde(deny_unknown_fields, default)]
728pub struct SetupStep {
729    /// `"src -> dst"` (or just `"path"`): copy from the primary checkout (an
730    /// absolute source is allowed) into the worktree. Never overwrites.
731    pub copy: Option<String>,
732    /// With `copy`: a missing source is skipped instead of an error.
733    pub optional: bool,
734    /// Shell command, run with the worktree as cwd.
735    pub run: Option<String>,
736    /// With `run`: seconds before the command is killed. Defaults to
737    /// `graph.verify_timeout()`.
738    pub timeout_secs: Option<u64>,
739}
740
741impl Worktree {
742    /// Refuse a malformed step at load time rather than in the middle of a run.
743    pub fn validate(&self) -> Result<()> {
744        for (i, step) in self.setup.iter().enumerate() {
745            let n = i + 1;
746            match (&step.copy, &step.run) {
747                (Some(c), None) => {
748                    if step.timeout_secs.is_some() {
749                        bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
750                    }
751                    crate::worktree_setup::validate_copy(c)
752                        .with_context(|| format!("[worktree] setup step {n}"))?;
753                }
754                (None, Some(r)) => {
755                    if r.trim().is_empty() {
756                        bail!("[worktree] setup step {n}: `run` is empty");
757                    }
758                    if step.optional {
759                        bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
760                    }
761                }
762                _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
763            }
764        }
765        Ok(())
766    }
767}
768
769/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
770///
771/// The numbers below come from one incident, not from theory: a machine with
772/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
773/// Three multi-gigabyte classes of junk accumulated side by side - per-run
774/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
775/// each verify round and each implementation wave recompiles the derived
776/// section of the project into, and the outputs of runs that were removed but
777/// whose folders nobody deleted.
778#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
779#[serde(deny_unknown_fields, default)]
780pub struct Disk {
781    /// Free space, in bytes, below which no new run may start: the daemon and
782    /// the `magi run` gate answer with "the disk is full" instead of letting
783    /// the graph fill it the rest of the way. `0` turns the gate off.
784    ///
785    /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
786    /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
787    /// competition triggers and small enough that a 1 TB disk with 100 GB free
788    /// is nowhere near the threshold.
789    pub min_free_bytes: u64,
790    /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
791    /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
792    /// worktrees removed. `0` turns the janitor off.
793    ///
794    /// Default true.
795    pub auto_fold: bool,
796    /// How old a finished run must be before the janitor folds it, seconds.
797    ///
798    /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
799    /// run that `Ready` a week ago is worktrees holding a compile each. Six
800    /// hours is long enough that nobody loses an answer in the gap between
801    /// reading the report and starting from it, and short enough that a backlog
802    /// cannot pile up across two nights.
803    pub fold_grace_secs: u64,
804    /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
805    /// verify commands), in bytes. When the janitor runs and the cache is over
806    /// it, files are dropped oldest-first until it is not. `0` turns pruning
807    /// off - the cache then only ever grows, which is the operator's call.
808    ///
809    /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
810    /// shared cache on top of ~16 GB in the primary target directory and 6.7-
811    /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
812    /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
813    /// pruning only costs the rebuild of the dropped files, not of the world)
814    /// without letting one addled cache swallow the machine.
815    pub cache_limit_bytes: u64,
816}
817
818impl Default for Disk {
819    fn default() -> Self {
820        Self {
821            min_free_bytes: 8 * 1024 * 1024 * 1024,
822            auto_fold: true,
823            fold_grace_secs: 6 * 60 * 60,
824            cache_limit_bytes: 10 * 1024 * 1024 * 1024,
825        }
826    }
827}
828
829/// What to do with the winning branch.
830#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
831#[serde(rename_all = "lowercase")]
832pub enum MergeMode {
833    /// Leave the branch alone and print the merge command matching
834    /// [`Merge::style`].
835    None,
836    /// Merge into the base branch in the primary worktree, using
837    /// [`Merge::style`].
838    Local,
839    /// Push the branch and open a PR with `gh pr create`. Landing this PR
840    /// (`[graph] land`) always squashes — see `land`'s module doc — so
841    /// [`Merge::style`] does not apply here.
842    Pr,
843}
844
845/// How the winning branch is attached to the base branch: what
846/// `mode = "local"` runs, and what `mode = "none"`'s printed guidance tells
847/// the operator to run by hand.
848///
849/// Read from configuration rather than asked of the repository at run time
850/// (e.g. `gh api repos/{owner}/{repo}/rulesets`) for two reasons: it keeps
851/// `mode = "none"`'s guidance a pure function of `RunState`, assertable in a
852/// unit test the same way `land::decide` is kept pure (see that module's
853/// doc), and it works for a base branch that is not hosted on GitHub, or not
854/// reachable at all, at the moment the report is rendered. An operator whose
855/// base branch enforces a ruleset already knows what it allows; declaring it
856/// once here is cheaper than magi re-discovering it, with a network call, on
857/// every render.
858#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
859#[serde(rename_all = "lowercase")]
860pub enum MergeStyle {
861    /// `git merge --no-ff`: every candidate commit lands, plus a merge
862    /// commit that records the merge as its own event in history. Rejected
863    /// by a base branch whose ruleset requires linear history or forbids
864    /// merge commits outright.
865    #[default]
866    Merge,
867    /// `git merge --squash` followed by a commit under an explicit message:
868    /// every candidate commit folds into one, and none of the candidate's
869    /// own placeholder subjects (`magi: candidate A (uncommitted work)`)
870    /// reach the base branch. No merge commit, so this satisfies a linear-
871    /// history ruleset.
872    Squash,
873    /// A fast-forward-only merge: every candidate commit lands verbatim, in
874    /// order, with no merge commit. Only succeeds because the winner was
875    /// already rebased onto the tracked base tip before this runs (see
876    /// `Runner::sync_to_base`) — equivalent to GitHub's "rebase and merge"
877    /// once that has happened.
878    Rebase,
879}
880
881/// Merge policy.
882#[derive(Debug, Clone, Deserialize, Serialize)]
883#[serde(deny_unknown_fields, default)]
884pub struct Merge {
885    /// Default is [`MergeMode::None`]: magi never touches your base branch
886    /// unless you ask it to.
887    pub mode: MergeMode,
888    /// Base branch. Defaults to the branch checked out when the run started.
889    pub base: Option<String>,
890    /// How the winner is attached to `base`; see [`MergeStyle`]. Ignored by
891    /// `mode = "pr"`.
892    pub style: MergeStyle,
893    /// Remote for `mode = "pr"`.
894    pub remote: String,
895    /// After a `mode = "pr"` run lands, open a `chore/release-vX.Y.Z` pull
896    /// request sized to the change by an agent's own judgement, so a version
897    /// bump does not depend on a human remembering to cut one.
898    ///
899    /// Only acts on Rust repositories (a `Cargo.toml` at the root of the base
900    /// branch); on any other repository it is a no-op that records one event.
901    ///
902    /// On by default. **Turning this off means a merge landed from the phone
903    /// never becomes a release**, so `POST /api/upgrade` keeps reporting
904    /// "already on the newest release" against a `main` that has moved past
905    /// it - the same gap this feature exists to close. Only for a repository
906    /// that wants to keep cutting releases by hand.
907    pub release_bump: bool,
908}
909
910impl Default for Merge {
911    fn default() -> Self {
912        Self {
913            mode: MergeMode::None,
914            base: None,
915            style: MergeStyle::default(),
916            remote: "origin".to_owned(),
917            release_bump: true,
918        }
919    }
920}
921
922/// How magi keeps itself current.
923#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
924#[serde(rename_all = "lowercase")]
925pub enum UpdateMode {
926    /// Never check.
927    Off,
928    /// Check in the background and print a one-line banner when a newer
929    /// release exists.
930    Notify,
931    /// Check and install silently.
932    Install,
933}
934
935/// Self-update policy.
936#[derive(Debug, Clone, Deserialize, Serialize)]
937#[serde(deny_unknown_fields, default)]
938pub struct Update {
939    /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
940    pub mode: UpdateMode,
941    /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
942    pub interval: Option<String>,
943}
944
945impl Default for Update {
946    fn default() -> Self {
947        Self {
948            mode: UpdateMode::Notify,
949            interval: None,
950        }
951    }
952}
953
954/// Who performs the release after a `chore/release-vX.Y.Z` pull request merges.
955#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
956#[serde(rename_all = "lowercase")]
957pub enum ReleaseMode {
958    /// The repository's own workflows do (`auto-tag.yml` then `release.yml`),
959    /// and the release pull request merges on its checks.
960    #[default]
961    Actions,
962    /// magi does, from this machine: no CI is awaited, the owner approves the
963    /// merge, and magi then tags and runs [`Release::commands`]. See
964    /// [`crate::release_local`].
965    Local,
966}
967
968/// `[release]`: releasing without GitHub Actions. Opt-in per repository.
969#[derive(Debug, Clone, Deserialize, Serialize)]
970#[serde(deny_unknown_fields, default)]
971pub struct Release {
972    /// [`ReleaseMode::Actions`] (default: nothing changes) or
973    /// [`ReleaseMode::Local`].
974    pub mode: ReleaseMode,
975    /// Shell commands run in order, from a clean checkout of the merge commit,
976    /// once the tag is pushed. The first failure stops the list. They see
977    /// `MAGI_RELEASE_VERSION`, `MAGI_RELEASE_TAG`, `MAGI_RELEASE_COMMIT` and
978    /// `MAGI_RELEASE_PR` in the environment; `{{ ... }}` cannot carry the
979    /// version because teravars renders the whole file before any release
980    /// exists. Only read when `mode = "local"`.
981    pub commands: Vec<String>,
982    /// Minutes each command may run before it is killed and counted as failed.
983    pub timeout_minutes: u64,
984}
985
986impl Default for Release {
987    fn default() -> Self {
988        Self {
989            mode: ReleaseMode::Actions,
990            commands: Vec::new(),
991            timeout_minutes: 30,
992        }
993    }
994}
995
996impl Release {
997    /// Is this repository released by magi rather than by its workflows?
998    pub fn is_local(&self) -> bool {
999        self.mode == ReleaseMode::Local
1000    }
1001}
1002
1003/// Top-level configuration.
1004#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1005#[serde(deny_unknown_fields, default)]
1006pub struct Config {
1007    /// Agent roster.
1008    pub agents: Vec<AgentSpec>,
1009    /// Role assignment.
1010    pub roles: Roles,
1011    /// Graph shape.
1012    pub graph: Graph,
1013    /// Blindness policy.
1014    pub blind: Blind,
1015    /// Verification commands.
1016    pub verify: Verify,
1017    /// Worktree preparation.
1018    pub worktree: Worktree,
1019    /// Disk hygiene.
1020    pub disk: Disk,
1021    /// Merge policy.
1022    pub merge: Merge,
1023    /// Self-update policy.
1024    pub update: Update,
1025    /// Project-specific text appended to the node prompts.
1026    pub prompts: Prompts,
1027    /// How the operator is told a run is waiting on them.
1028    pub notify: Notify,
1029    /// Local repositories the plan surface can start or derive a conversation
1030    /// against.
1031    pub repos: Repos,
1032    /// Policy for the standing conversation ([`crate::talk`]).
1033    pub talk: Talk,
1034    /// How many runs `magi serve`'s own loop drives at once.
1035    pub daemon: Daemon,
1036    /// Who tags and publishes after a release pull request merges.
1037    pub release: Release,
1038    /// Context-window sizes in tokens, keyed by model name, merged over
1039    /// [`BUILTIN_CONTEXT_WINDOWS`]. See [`Config::context_window`].
1040    pub context_windows: BTreeMap<String, u64>,
1041}
1042
1043/// Context windows of models magi commonly drives, in tokens.
1044///
1045/// A convenience, not a source of truth: vendors resize windows and ship new
1046/// models faster than this table is edited, so an entry that is stale or
1047/// missing is fixed by `[context_windows]` in `magi.toml`, which wins. Matched
1048/// by [`Config::context_window`]: exact name first, then the longest key that
1049/// prefixes the model name (so a dated or suffixed id such as
1050/// `claude-sonnet-4-5-20250929` finds `claude-sonnet-4-5`). A model matching
1051/// nothing has no percentage - the UI shows the raw count.
1052const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1053    ("claude-opus-4", 200_000),
1054    ("claude-sonnet-4", 200_000),
1055    ("claude-haiku-4", 200_000),
1056    ("claude-3", 200_000),
1057    ("opus", 200_000),
1058    ("sonnet", 200_000),
1059    ("haiku", 200_000),
1060    ("gpt-5", 400_000),
1061    ("gpt-4.1", 1_000_000),
1062    ("gpt-4o", 128_000),
1063    ("o3", 200_000),
1064    ("o4-mini", 200_000),
1065    ("gemini-2.5", 1_000_000),
1066    ("deepseek", 128_000),
1067];
1068
1069impl Config {
1070    /// Context window in tokens for `model`: `[context_windows]` first, then
1071    /// the built-in table; within each, an exact name beats the longest
1072    /// prefix. `None` for an unknown model, which is a deliberate answer -
1073    /// guessing a denominator would print a confident wrong percentage.
1074    pub fn context_window(&self, model: &str) -> Option<u64> {
1075        fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1076            let mut best: Option<(usize, u64)> = None;
1077            for (key, window) in entries {
1078                if key == model {
1079                    return Some(window);
1080                }
1081                if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1082                    best = Some((key.len(), window));
1083                }
1084            }
1085            best.map(|(_, w)| w)
1086        }
1087        lookup(
1088            model,
1089            self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1090        )
1091        .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1092    }
1093}
1094
1095/// How the daemon loop itself behaves, as opposed to what one run does.
1096///
1097/// Machine-layer material in the same sense [`Repos::roots`] is: how many
1098/// competitions this machine's own loop is willing to babysit at once is a
1099/// fact about the machine running `magi serve`, not about any one
1100/// repository's task, so it belongs in `<config_dir>/magi/config.toml`
1101/// rather than a repository's own `magi.toml` - though, like `Repos::roots`,
1102/// nothing stops a repository from setting it too, since a scalar field
1103/// takes whichever layer has the highest precedence.
1104#[derive(Debug, Clone, Deserialize, Serialize)]
1105#[serde(deny_unknown_fields, default)]
1106pub struct Daemon {
1107    /// How many runs `magi serve` may have actively in flight at once.
1108    /// **One by default** - today's behaviour, one run at a time.
1109    ///
1110    /// This is a different knob from [`Graph::max_parallel`], and the two
1111    /// must not be confused: `max_parallel` bounds how many agent *processes*
1112    /// one run starts inside itself (implementers, judges, reviewers -
1113    /// candidates competing on a single task); this field bounds how many
1114    /// *runs* - whole competitions, each with its own `max_parallel` budget -
1115    /// the loop drives side by side, possibly across different tasks and
1116    /// different repositories. Raising `max_parallel` buys a bigger panel for
1117    /// one task; raising this buys more tasks worked at once. A config file
1118    /// that meant one and wrote the other would either starve a competition
1119    /// of judges or leave the rest of the backlog waiting for no reason.
1120    ///
1121    /// A run parked waiting on the operator's land-merge approval - see
1122    /// [`crate::land`] - does not hold one of these slots while it waits: the
1123    /// whole point of parking there is to let the loop spend the slot on
1124    /// something runnable instead of sitting on a decision only a human can
1125    /// make. So even at the default of `1`, an approval that comes back does
1126    /// not queue behind whatever else the loop happens to be running.
1127    pub max_concurrent_runs: usize,
1128    /// Let a task marked [`crate::queue::Task::interrupt`] (`magi task
1129    /// interrupt`) cut ahead of whatever `magi serve` already has in flight,
1130    /// instead of waiting for it to finish.
1131    ///
1132    /// **Off by default.** When enabled, a run that is in flight and is not
1133    /// itself the interrupt candidate may be paused at its next safe node
1134    /// boundary - see [`crate::graph::Runner::park_here`] - so the marked
1135    /// task can run alone; the paused run resumes automatically, through the
1136    /// same path any other parked run does, the moment the interrupting
1137    /// task's own run reaches a terminal status. This is opt-in because it
1138    /// bends the loop's own "one run at a time" principle (see this repository's
1139    /// `magi serve` help) for a specific, explicit operator request, and a
1140    /// repository that never files an interrupt task pays nothing for having
1141    /// it on - but an operator who does not want any run of theirs preempted,
1142    /// ever, should leave this `false`.
1143    pub pause_for_interrupts: bool,
1144    /// How many deputies `magi serve` runs at once. A deputy is the short-lived
1145    /// seat that waits on one open conductor question (see [`crate::deputy`]);
1146    /// each is a live agent conversation, so this is bounded - **two by
1147    /// default**, because the agent CLIs' quota is the scarce resource. A
1148    /// question over the limit keeps its place and starts when a deputy
1149    /// finishes; `0` runs none.
1150    pub max_deputies: usize,
1151    /// Minutes a release-bump pull request may make no progress before
1152    /// `magi serve` raises a notice and asks the owner (see
1153    /// [`crate::release_watch`]). Progress is a change of head commit or of any
1154    /// check's verdict. A required check that stays red after the one rerun the
1155    /// watcher is allowed escalates at once, whatever this says. **Sixty by
1156    /// default**; `0` turns the watcher off.
1157    pub release_stall_minutes: u64,
1158}
1159
1160impl Default for Daemon {
1161    fn default() -> Self {
1162        Self {
1163            max_concurrent_runs: 1,
1164            pause_for_interrupts: false,
1165            max_deputies: 2,
1166            release_stall_minutes: 60,
1167        }
1168    }
1169}
1170
1171/// Where `magi repos` and `GET /api/repos` look for local checkouts.
1172///
1173/// `roots` is one of the array keys [`array_merge_policy`] marks as
1174/// append-across-layers: which checkouts exist in general is a *machine*
1175/// fact in the same way the agent roster is - a repository's own `magi.toml`
1176/// cannot state where its siblings live before magi has resolved which
1177/// repository to read that file from in the first place - but a repository
1178/// that genuinely has an extra root worth scanning is not forced to choose
1179/// between an error and losing the machine's roots outright. Both layers'
1180/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
1181/// are still refused.
1182#[derive(Debug, Clone, Deserialize, Serialize)]
1183#[serde(deny_unknown_fields, default)]
1184pub struct Repos {
1185    /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
1186    /// with a `.git` directory. Empty by default - nothing is scanned unless
1187    /// asked to be.
1188    pub roots: Vec<PathBuf>,
1189    /// How long a scan is trusted before the next request re-scans it,
1190    /// seconds. `0` means never trust it: scan on every request. Defaults to
1191    /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
1192    /// the same reason - a checkout does not usually appear or vanish inside
1193    /// a session, so there is little to gain from scanning more often than
1194    /// that, and an explicit refresh exists for the moment one does.
1195    pub scan_ttl: u64,
1196    /// How often `magi serve` runs `git fetch origin` in every checkout under
1197    /// `roots`, seconds, so `origin/main` stays fresh whatever state the
1198    /// working tree is in. Fetch only: no branch, HEAD or working tree is
1199    /// touched. `0` disables it.
1200    pub fetch_interval: u64,
1201}
1202
1203impl Default for Repos {
1204    fn default() -> Self {
1205        Self {
1206            roots: Vec::new(),
1207            scan_ttl: 86_400,
1208            fetch_interval: 600,
1209        }
1210    }
1211}
1212
1213/// Project-specific text appended to each node's prompt.
1214///
1215/// **Additive by construction.** These fields cannot replace magi's prompts,
1216/// only extend them, and that restriction is the whole design. The built-in
1217/// prompts carry the invariants the competition rests on: a judging prompt
1218/// names no authors, every structured answer must arrive as one fenced `json`
1219/// block, and a judge is told not to speculate about who wrote what. A config
1220/// that could overwrite them would let a typo silently un-blind the panel or
1221/// break the parser, and the symptom would be "the judges got worse" rather
1222/// than an error.
1223///
1224/// Repository-wide context belongs in `AGENTS.md`, which every agent already
1225/// reads from the checkout. Use these fields for the things a *magi node*
1226/// needs to know and a repository file cannot say - for instance that
1227/// reviewers here should ignore formatting because a hook owns it.
1228#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1229#[serde(deny_unknown_fields, default)]
1230pub struct Prompts {
1231    /// Appended to every node's prompt.
1232    pub all: String,
1233    /// Appended for implementers.
1234    pub implement: String,
1235    /// Appended for judges, both ranking and voting.
1236    pub judge: String,
1237    /// Appended for reviewers.
1238    pub review: String,
1239    /// Appended for the fixer.
1240    pub fix: String,
1241}
1242
1243impl Prompts {
1244    /// The overlay for one node, or `None` when nothing is configured.
1245    ///
1246    /// `node` is the graph's own node name, so a new node gets no overlay
1247    /// rather than the wrong one.
1248    pub fn overlay(&self, node: &str) -> Option<String> {
1249        let specific = match node {
1250            "implement" => &self.implement,
1251            "judge" | "vote" | "deliberate" => &self.judge,
1252            "review" => &self.review,
1253            "fix" => &self.fix,
1254            _ => "",
1255        };
1256        let mut parts: Vec<&str> = Vec::new();
1257        for p in [self.all.trim(), specific.trim()] {
1258            if !p.is_empty() {
1259                parts.push(p);
1260            }
1261        }
1262        if parts.is_empty() {
1263            return None;
1264        }
1265        Some(parts.join("\n\n"))
1266    }
1267}
1268
1269/// How the operator is told that a run is waiting on them.
1270///
1271/// A command rather than a built-in integration: magi is one binary with no
1272/// network dependencies, and every operator's notification path is different -
1273/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
1274/// Shelling out keeps all of them possible and none of them magi's problem.
1275#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1276#[serde(deny_unknown_fields, default)]
1277pub struct Notify {
1278    /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
1279    /// Empty means no notification - the web UI is then the only surface.
1280    pub command: Vec<String>,
1281}
1282
1283/// Policy for [`crate::talk`], the standing conversation.
1284#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1285#[serde(deny_unknown_fields, default)]
1286pub struct Talk {
1287    /// Let the conversation's agent edit files in the repository instead of
1288    /// filing a task for one. **Off by default** - see
1289    /// [`crate::talk`]'s module doc for why an edit made mid-conversation is
1290    /// an edit no run and no review can be attributed to, which is exactly
1291    /// the property a repository entered in a competition depends on. A
1292    /// repository that is never judged - dotfiles, a personal config
1293    /// checkout - has nothing to lose by turning this on in its own
1294    /// `magi.toml`, and a one-line fix stops costing a queued task to get.
1295    pub allow_write: bool,
1296    /// Extra chat personas, `[[talk.personas]]`. They add to the built-ins in
1297    /// [`crate::persona`]; an entry with a built-in's id replaces it. Like every
1298    /// array outside [`array_merge_policy`]'s append list, declaring it in two
1299    /// layers is refused.
1300    pub personas: Vec<PersonaSpec>,
1301    /// What the chat calls the operator: the persona addresses them by this
1302    /// name and the web Chat labels their turns with it instead of `YOU`.
1303    /// Blank is unset; at most [`OPERATOR_NAME_MAX`] characters, one line.
1304    pub operator_name: Option<String>,
1305}
1306
1307/// Longest accepted `[talk] operator_name`, in characters.
1308pub const OPERATOR_NAME_MAX: usize = 64;
1309
1310impl Talk {
1311    /// The trimmed operator name, `None` when unset or blank.
1312    pub fn operator_name(&self) -> Option<&str> {
1313        self.operator_name
1314            .as_deref()
1315            .map(str::trim)
1316            .filter(|n| !n.is_empty())
1317    }
1318}
1319
1320/// One `[[talk.personas]]` entry: a tone for the standing chat, nothing more.
1321#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1322#[serde(deny_unknown_fields)]
1323pub struct PersonaSpec {
1324    /// Stable id the conversation stores. Not `default`.
1325    pub id: String,
1326    /// What the selector shows. May be omitted when `id` is a built-in's: the
1327    /// built-in's name is kept.
1328    #[serde(default)]
1329    pub name: String,
1330    /// The voice instruction appended to the chat's system prompt. May be
1331    /// omitted when `id` is a built-in's.
1332    #[serde(default)]
1333    pub prompt: String,
1334    /// Optional avatar, display only: a `data:image/(png|jpeg|gif|webp);base64,`
1335    /// URI or an absolute (or `~/`) path to a raster image. See
1336    /// [`crate::persona_icon`]. Never part of the briefing.
1337    #[serde(default, skip_serializing_if = "Option::is_none")]
1338    pub icon: Option<String>,
1339}
1340
1341/// Roles resolved to concrete agent specs for one run.
1342#[derive(Debug, Clone)]
1343pub struct ResolvedRoles {
1344    /// One per candidate.
1345    pub implementers: Vec<AgentSpec>,
1346    /// One per judge.
1347    pub judges: Vec<AgentSpec>,
1348    /// One per reviewer slot.
1349    pub reviewers: Vec<AgentSpec>,
1350    /// The configured fixer chain in order, if `[roles] fixer` is set
1351    /// (resolved like [`crate::agent::pick_chain`]: unknown or uninstalled ids
1352    /// skipped, duplicates keep their first place). `None` means the winner's
1353    /// own author.
1354    pub fixer: Option<Vec<AgentSpec>>,
1355    /// Queue conductor, explicitly selected or resolved by the standalone-seat fallback.
1356    pub conductor: AgentSpec,
1357    /// The full ordered implementer roster, in [`Roles::implementers`]'s own
1358    /// order — or `[[agents]]` in file order, when that list is empty. Unlike
1359    /// [`Self::implementers`], never truncated to `graph.implementers` and
1360    /// never `rotate`d/wrapped: a solo run (`implementers = 1`) resolves
1361    /// `implementers` down to a single slot, but `graph::Runner`'s per-seat
1362    /// quota fallback needs the *whole* list to walk forward through when
1363    /// that one slot's agent runs out of quota mid-run.
1364    pub implementer_roster: Vec<AgentSpec>,
1365    /// [`Self::implementer_roster`]'s counterpart for judge seats: the whole
1366    /// `[roles] judges` list (or every agent), untruncated and unrotated, for
1367    /// the per-seat handover when a judge's agent fails.
1368    pub judge_roster: Vec<AgentSpec>,
1369    /// Likewise for reviewer seats.
1370    pub reviewer_roster: Vec<AgentSpec>,
1371}
1372
1373/// Every array-valued key in a config table, as a dotted path.
1374///
1375/// Dotted so the error names `roles.implementers` rather than `implementers`:
1376/// an operator with three config files needs to know which key, not just that
1377/// there was one. `vars` is skipped because it is teravars' own input, merged
1378/// on purpose and never deserialised into `Config`.
1379fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1380    let mut out = Vec::new();
1381    for (k, v) in table {
1382        if prefix.is_empty() && k == "vars" {
1383            continue;
1384        }
1385        let path = if prefix.is_empty() {
1386            k.clone()
1387        } else {
1388            format!("{prefix}.{k}")
1389        };
1390        match v {
1391            toml::Value::Array(_) => out.push(path),
1392            toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1393            _ => {}
1394        }
1395    }
1396    out
1397}
1398
1399/// How an array key behaves when two config layers both declare it.
1400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1401enum ArrayMerge {
1402    /// Two layers may both declare it; the composed value is the
1403    /// low-to-high-priority concatenation teravars already produces (see
1404    /// [`Config::load_layers`]'s doc for why that order and no dedup).
1405    Append,
1406    /// Two layers declaring it is refused; see
1407    /// [`Config::refuse_split_arrays`].
1408    Replace,
1409}
1410
1411/// The single place that decides, for a dotted array key (as returned by
1412/// [`array_keys`]), whether declaring it in two config layers is a
1413/// concatenation the operator asked for or a silent accident.
1414///
1415/// Kept as one match so the whole policy is visible in one place - the same
1416/// reason `claude_quota` and `dropped_stream` close their own classification
1417/// in one spot elsewhere in this codebase. Anything not listed defaults to
1418/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
1419/// reasoned about yet, and a new array key added later has to be added here
1420/// deliberately to become appendable.
1421///
1422/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
1423///   gate. Concatenating two of them is exactly the checks both layers
1424///   wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
1425///   live in a shared layer while a repository's own layer adds its own
1426///   command, instead of every repository copying the shared command into
1427///   its own file.
1428/// - `repos.roots` — a set of directories to scan for checkouts. A
1429///   repository adding its own root on top of the machine's is additive by
1430///   nature, not a replacement of where the machine looks; see
1431///   [`Repos::roots`].
1432///
1433/// Left on the refuse side, and why:
1434/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
1435///   list of *seats*, not a set. A machine's two implementers plus a
1436///   repository's one is three seats nobody asked for and nobody is paying
1437///   for on purpose.
1438/// - `notify.command` — an argv. Concatenating two argvs does not produce a
1439///   program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
1440/// - `blind.strip_lines` — technically safe to concatenate (each entry is
1441///   matched as an independent substring, so a longer list only strips
1442///   *more*), but left on the refuse side anyway: the same list also drives
1443///   `commit_msg_hook`'s generated `sed` addresses, where position matters,
1444///   and a silent three-layer merge is exactly the kind of surprise
1445///   `refuse_split_arrays` exists to catch rather than to reason about
1446///   case-by-case. A repository that wants one more stripped phrase restates
1447///   the whole list; that restatement is visible in review, an accidental
1448///   concatenation would not be.
1449fn array_merge_policy(key: &str) -> ArrayMerge {
1450    match key {
1451        "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1452        _ => ArrayMerge::Replace,
1453    }
1454}
1455
1456impl Config {
1457    /// Load one file through teravars: Tera rendering, `[vars]` resolution,
1458    /// and the `include = [...]` directive.
1459    pub fn load(path: &Path) -> Result<Self> {
1460        Self::load_layers(&[path.to_path_buf()])
1461    }
1462
1463    /// The Tera render context shared by every layer: `system.*` (from
1464    /// teravars), `env` (magi's own addition - a config that names a shared
1465    /// build-cache directory or a machine-specific path needs
1466    /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
1467    /// derived from the last (highest-priority) path's parent directory.
1468    ///
1469    /// Factored out so [`Config::array_provenance`] can re-render a single
1470    /// layer under the exact same context [`Config::load_layers`] uses for
1471    /// the joint render, rather than drifting from it by accident.
1472    fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1473        let mut ctx = teravars::system_context();
1474        let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1475        ctx.insert("env", &env);
1476        if let Some(last) = paths.last()
1477            && let Some(dir) = last.parent()
1478        {
1479            // A layer extracted from `<remote>/<base>` records the checkout it
1480            // stands for beside itself; its own directory is a cache path.
1481            let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1482                .map(|s| PathBuf::from(s.trim()))
1483                .unwrap_or_else(|_| dir.to_path_buf());
1484            ctx.insert("repo", &dir.to_string_lossy());
1485            ctx.insert(
1486                "repo_name",
1487                &dir.file_name().unwrap_or_default().to_string_lossy(),
1488            );
1489        }
1490        ctx
1491    }
1492
1493    /// Load and deep-merge a stack of config files, later files winning.
1494    ///
1495    /// This is why the config is TOML-through-teravars rather than plain serde:
1496    /// the roster is a *machine* fact (which CLIs and plans you pay for) while
1497    /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
1498    /// there). Picking one file and ignoring the other would force every repo
1499    /// to restate the roster.
1500    pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1501        let mut engine = teravars::Engine::default();
1502        let ctx = Self::render_ctx(paths);
1503        if paths.len() > 1 {
1504            Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
1505        }
1506        let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
1507            format!(
1508                "rendering config via teravars: {}",
1509                paths
1510                    .iter()
1511                    .map(|p| p.display().to_string())
1512                    .collect::<Vec<_>>()
1513                    .join(", ")
1514            )
1515        })?;
1516        let mut table = merged.config;
1517        Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1518        // `[vars]` is teravars' own input, already resolved into the render
1519        // context; `deny_unknown_fields` must not trip over it.
1520        table.remove("vars");
1521        // No layer says anything about `agents`: the roster is whatever is on
1522        // `PATH` now, exactly as when no layer exists at all. An explicit
1523        // `agents = []` is a statement and is kept.
1524        let detect_agents = !table.contains_key("agents");
1525        let mut cfg: Self = toml::Value::Table(table)
1526            .try_into()
1527            .context("deserializing magi config")?;
1528        crate::persona::validate(&cfg.talk.personas)?;
1529        cfg.worktree.validate()?;
1530        if let Some(name) = cfg.talk.operator_name() {
1531            if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1532                bail!(
1533                    "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1534                );
1535            }
1536        }
1537        if detect_agents {
1538            cfg.agents = Self::autodetected().agents;
1539        }
1540        Ok(cfg)
1541    }
1542
1543    /// `graph.candidates` was renamed `graph.implementers`. Both spellings are
1544    /// read, but the layers are merged into one table before serde sees it, so
1545    /// an old name in a lower layer and the new name in a higher one would
1546    /// arrive together and fail as a duplicate field instead of letting the
1547    /// higher layer win. Resolve it here: a single layer that writes both is
1548    /// refused (naming both keys and the file); otherwise the value from the
1549    /// last layer that wrote either key becomes `implementers`.
1550    fn normalize_renamed_keys(
1551        paths: &[PathBuf],
1552        engine: &mut teravars::Engine,
1553        ctx: &teravars::Context,
1554        table: &mut toml::map::Map<String, toml::Value>,
1555    ) -> Result<()> {
1556        let both = matches!(
1557            table.get("graph"),
1558            Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1559        );
1560        if !both {
1561            return Ok(());
1562        }
1563        let mut winner: Option<toml::Value> = None;
1564        for path in paths {
1565            let one = teravars::load_merged([path], engine, ctx)
1566                .with_context(|| format!("rendering {}", path.display()))?;
1567            let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1568                continue;
1569            };
1570            if g.contains_key("candidates") && g.contains_key("implementers") {
1571                bail!(
1572                    "`[graph]` sets both `implementers` and its deprecated alias \n                     `candidates` in {}; keep only `implementers`.",
1573                    path.display()
1574                );
1575            }
1576            if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1577                winner = Some(v.clone());
1578            }
1579        }
1580        if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1581            g.remove("candidates");
1582            if let Some(v) = winner {
1583                g.insert("implementers".to_owned(), v);
1584            }
1585        }
1586        Ok(())
1587    }
1588
1589    /// Refuse an array that two layers both declare, unless
1590    /// [`array_merge_policy`] says that key is meant to accumulate.
1591    ///
1592    /// teravars **appends** arrays when it merges layers, and that is wrong for
1593    /// most arrays magi has: `implementers` is an ordered list of seats,
1594    /// `notify.command` is an argv. Concatenating two of them yields something
1595    /// nobody wrote - three implementers out of a machine's two and a
1596    /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
1597    ///
1598    /// Replacing instead would be the right merge rule for those keys, but the
1599    /// rule lives in teravars, which several other projects depend on;
1600    /// changing it there is a decision for that crate, not something to fake
1601    /// here by re-reading the files with different semantics and hoping the
1602    /// two paths agree.
1603    ///
1604    /// So magi refuses the ambiguity rather than resolving it silently, for
1605    /// every array key except the short, deliberate list
1606    /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
1607    /// concatenation teravars already produces *is* what both files say, so
1608    /// there is nothing to refuse. The cost of guessing wrong on the refused
1609    /// keys is a roster the operator did not ask for and is paying for by the
1610    /// token; the append keys carry no such risk because every element runs
1611    /// (or every directory is scanned) regardless of order.
1612    fn refuse_split_arrays(
1613        paths: &[PathBuf],
1614        engine: &mut teravars::Engine,
1615        ctx: &teravars::Context,
1616    ) -> Result<()> {
1617        let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1618        for path in paths {
1619            let one = teravars::load_merged([path], engine, ctx)
1620                .with_context(|| format!("rendering {}", path.display()))?;
1621            for key in array_keys(&one.config, "") {
1622                if array_merge_policy(&key) == ArrayMerge::Append {
1623                    continue;
1624                }
1625                if let Some(first) = seen.get(&key) {
1626                    bail!(
1627                        "`{key}` is an array declared in two config layers:\n  \
1628                         {}\n  {}\nteravars appends arrays when it merges, so \
1629                         magi would run the concatenation of both - which is \
1630                         not what either file says. Declare `{key}` in exactly \
1631                         one of them.",
1632                        first.display(),
1633                        path.display()
1634                    );
1635                }
1636                seen.insert(key, path.clone());
1637            }
1638        }
1639        Ok(())
1640    }
1641
1642    /// Which layers contributed to a composed, appendable array key (e.g.
1643    /// `"verify.gate"`), in the same low-to-high-priority order
1644    /// [`Config::load_layers`] concatenates them in. Layers that do not
1645    /// declare `key` at all are omitted.
1646    ///
1647    /// This is a **display aid for `magi doctor` only.** The command list
1648    /// that actually runs always comes from the one joint
1649    /// [`teravars::load_merged`] call in `load_layers`, never from this
1650    /// function - the exact hazard [`Config::refuse_split_arrays`] warns
1651    /// about is two merge paths that might disagree, so this function must
1652    /// never become a second source of the *composed* value, only of which
1653    /// file wrote which line in it.
1654    ///
1655    /// Re-rendering each layer alone can, in principle, resolve a
1656    /// `{{ vars.x }}` differently than the joint render would, if `x` is
1657    /// defined in one layer and referenced in another - the same caveat
1658    /// `refuse_split_arrays`'s structural, key-only check already lives with.
1659    /// None of magi's own gate commands cross that line, and a doctor listing
1660    /// is read by a human who can compare it against the joint one printed
1661    /// alongside it, so this is judged worth the simplicity of not
1662    /// threading provenance through the real load path.
1663    pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1664        let mut engine = teravars::Engine::default();
1665        let ctx = Self::render_ctx(paths);
1666        let mut out = Vec::new();
1667        for path in paths {
1668            let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1669                continue;
1670            };
1671            let mut cur = &one.config;
1672            let mut found = None;
1673            let parts: Vec<&str> = key.split('.').collect();
1674            for (i, part) in parts.iter().enumerate() {
1675                match cur.get(*part) {
1676                    Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1677                        found = Some(a);
1678                        break;
1679                    }
1680                    Some(toml::Value::Table(t)) => cur = t,
1681                    _ => break,
1682                }
1683            }
1684            let Some(values) = found else { continue };
1685            let strings: Vec<String> = values
1686                .iter()
1687                .filter_map(|v| v.as_str().map(str::to_owned))
1688                .collect();
1689            if !strings.is_empty() {
1690                out.push((path.clone(), strings));
1691            }
1692        }
1693        out
1694    }
1695
1696    /// Each layer rendered on its own, with the outcome per file: the
1697    /// settings screen's way of saying which layer a value came from and which
1698    /// layer is the one that does not parse. A **display aid only**, for the
1699    /// same reason as [`Config::array_provenance`]: the effective config
1700    /// always comes from the one joint [`Config::load_layers`].
1701    pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1702        let mut engine = teravars::Engine::default();
1703        let ctx = Self::render_ctx(paths);
1704        paths
1705            .iter()
1706            .map(|path| {
1707                let one = teravars::load_merged([path], &mut engine, &ctx)
1708                    .map(|m| m.config)
1709                    .with_context(|| format!("rendering {}", path.display()));
1710                (path.clone(), one)
1711            })
1712            .collect()
1713    }
1714
1715    /// Render a composed command list for `magi doctor`: the joined command
1716    /// line the run actually uses, plus - only when more than one layer
1717    /// contributed - which layer wrote which line.
1718    ///
1719    /// A single contributing layer (the common case today) stays the plain
1720    /// one-line summary magi has always printed, `empty` included: that
1721    /// honest "(none — ...)" is what caught a real gate-composition gap
1722    /// before this array could compose at all, and composition should not
1723    /// make the common case noisier.
1724    pub fn describe_composed(
1725        paths: &[PathBuf],
1726        commands: &[String],
1727        key: &str,
1728        empty: &str,
1729    ) -> String {
1730        if commands.is_empty() {
1731            return empty.to_owned();
1732        }
1733        let joined = commands.join(" && ");
1734        let provenance = Self::array_provenance(paths, key);
1735        if provenance.len() <= 1 {
1736            return joined;
1737        }
1738        let mut out = joined;
1739        for (path, cmds) in &provenance {
1740            out.push_str(&format!("\n    [{}] {}", path.display(), cmds.join(" && ")));
1741        }
1742        out
1743    }
1744
1745    /// Resolve the config for `repo`, honouring an explicit `--config` path.
1746    ///
1747    /// Returns the config and the layers it came from, empty for built-in
1748    /// defaults. The repository layers come from the remote-tracking ref as it
1749    /// stands (see the module doc); use [`Config::discover_fetched`] where a
1750    /// stale ref would matter.
1751    pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1752        if let Some(p) = explicit {
1753            let paths = vec![p.to_path_buf()];
1754            return Ok((Self::load_layers(&paths)?, paths));
1755        }
1756        let paths = Self::layers_checked(repo)?;
1757        if paths.is_empty() {
1758            return Ok((Self::autodetected(), paths));
1759        }
1760        Ok((Self::load_layers(&paths)?, paths))
1761    }
1762
1763    /// [`Config::discover`] after `git fetch <remote> <base>`: for every path
1764    /// that is about to start work. A failed fetch is an error.
1765    pub async fn discover_fetched(
1766        repo: &Path,
1767        explicit: Option<&Path>,
1768    ) -> Result<(Self, Vec<PathBuf>)> {
1769        if explicit.is_none() && is_git_worktree(repo) {
1770            // A checkout that was never cloned from the remote has no
1771            // `<remote>/HEAD`; learn it here (refs/remotes only) so an
1772            // ordinary start recovers instead of failing in `discover`.
1773            let (remote, cfg_base) = probe_remote_base(repo);
1774            let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref()).await?;
1775            let out = crate::git::fetch(repo, &remote, &base)
1776                .await
1777                .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))?;
1778            if !out.ok() {
1779                bail!(
1780                    "cannot read magi.toml: `git fetch {remote} {base}` failed ({});                      refusing to use the local checkout's copy, which may be stale",
1781                    out.stderr.lines().next().unwrap_or("").trim()
1782                );
1783            }
1784            if cfg_base.is_none() {
1785                crate::git::ensure_remote_head(repo, &remote, &base).await;
1786            }
1787        }
1788        Self::discover(repo, explicit)
1789    }
1790
1791    /// [`Config::layers`], but an unreadable remote ref is an error.
1792    fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
1793        if !is_git_worktree(repo) {
1794            return Ok(Self::layers(repo));
1795        }
1796        let mut paths: Vec<PathBuf> = Self::machine_layer()
1797            .into_iter()
1798            .filter(|p| p.is_file())
1799            .collect();
1800        paths.extend(Self::repo_layers(repo)?);
1801        Ok(paths)
1802    }
1803
1804    /// Only the repository layers (lowest first), from `<remote>/<base>` in a
1805    /// git working tree and from disk elsewhere.
1806    pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
1807        if !is_git_worktree(repo) {
1808            return Ok([
1809                repo.join(".magi").join("config.toml"),
1810                repo.join("magi.toml"),
1811            ]
1812            .into_iter()
1813            .filter(|p| p.is_file())
1814            .collect());
1815        }
1816        remote_layers(repo)
1817    }
1818
1819    /// Environment variable that relocates the machine-wide config layer.
1820    ///
1821    /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
1822    /// of the one under [`dirs::config_dir`]; set it to the empty string and
1823    /// magi reads no machine layer at all.
1824    ///
1825    /// This exists because the machine layer is otherwise unavoidable, and a
1826    /// test that builds a config fixture is not asking for the operator's
1827    /// preferences to be merged into it. Adding `[repos] roots` to the real
1828    /// machine config on a development box turned two passing tests red -
1829    /// `repos_list_returns_name_and_path_for_every_configured_root` and
1830    /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
1831    /// declare `[repos] roots` of their own, which [`Config::layers`] then
1832    /// found in two layers and [`Config::refuse_split_arrays`] correctly
1833    /// refused. CI never saw it: a runner has no machine config, so the suite
1834    /// was green there and red only where somebody actually uses magi.
1835    ///
1836    /// An operator gets the same escape hatch for free: a second machine
1837    /// config, or none, without moving files about.
1838    pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
1839
1840    /// Every config layer that applies to `repo`, in increasing precedence.
1841    ///
1842    /// The machine layer is whatever [`Config::machine_layer`] resolves to,
1843    /// which is nothing at all in a test build.
1844    pub fn layers(repo: &Path) -> Vec<PathBuf> {
1845        let mut paths = Vec::new();
1846        paths.extend(Self::machine_layer());
1847        paths.push(repo.join(".magi").join("config.toml"));
1848        paths.push(repo.join("magi.toml"));
1849        paths.retain(|p| p.is_file());
1850        paths
1851    }
1852
1853    /// The machine-wide layer's path, when there is one.
1854    ///
1855    /// **A test build has none unless it names one.** A fixture is a complete
1856    /// statement of the config under test, and the operator's own preferences
1857    /// have no business being merged into it - least of all silently, on one
1858    /// machine, in a suite that is green everywhere else.
1859    #[cfg(test)]
1860    pub(crate) fn machine_layer() -> Option<PathBuf> {
1861        std::env::var(Self::CONFIG_DIR_ENV)
1862            .ok()
1863            .filter(|dir| !dir.trim().is_empty())
1864            .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
1865    }
1866
1867    /// The machine-wide layer's path, when there is one.
1868    #[cfg(not(test))]
1869    pub(crate) fn machine_layer() -> Option<PathBuf> {
1870        match std::env::var(Self::CONFIG_DIR_ENV) {
1871            // Named, and empty on purpose: no machine layer.
1872            Ok(dir) if dir.trim().is_empty() => None,
1873            Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1874            Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1875        }
1876    }
1877
1878    /// Built-in config whose roster is the agent CLIs found on `PATH`.
1879    pub fn autodetected() -> Self {
1880        let mut cfg = Self::default();
1881        for (kind, id, model) in [
1882            (AgentKind::Claude, "opus", Some("opus")),
1883            (AgentKind::Claude, "sonnet", Some("sonnet")),
1884            (AgentKind::Antigravity, "antigravity", None),
1885            (AgentKind::Opencode, "opencode", None),
1886            (AgentKind::Codex, "codex", None),
1887            (AgentKind::Omp, "omp", None),
1888        ] {
1889            if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1890                cfg.agents.push(AgentSpec {
1891                    id: id.to_owned(),
1892                    kind,
1893                    model: model.map(str::to_owned),
1894                    command: Vec::new(),
1895                    extra_args: Vec::new(),
1896                    env: BTreeMap::new(),
1897                    prompt_delivery: None,
1898                });
1899            }
1900        }
1901        cfg
1902    }
1903
1904    /// The shared build cache the verify commands and the agents both build
1905    /// into, when the config declares one. See [`Verify::cache_dir`].
1906    pub fn cache_dir(&self) -> Option<PathBuf> {
1907        self.verify.cache_dir()
1908    }
1909
1910    /// Look an agent up by id.
1911    pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1912        self.agents
1913            .iter()
1914            .find(|a| a.id == id)
1915            .with_context(|| format!("no agent with id `{id}` in the roster"))
1916    }
1917
1918    /// Rotate `count` seats out of `ids`, or out of the whole roster at
1919    /// `offset` when `ids` is empty.
1920    ///
1921    /// The one rotation rule - explicit ids cycle, an empty list rotates the
1922    /// roster - shared by every seat count [`Config::resolve_roles`] fills in,
1923    /// rather than each seat reimplementing it and drifting apart.
1924    fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
1925        let mut out = Vec::with_capacity(count);
1926        for i in 0..count {
1927            let spec = if ids.is_empty() {
1928                self.agents[(i + offset) % self.agents.len()].clone()
1929            } else {
1930                self.agent(&ids[i % ids.len()])?.clone()
1931            };
1932            out.push(spec);
1933        }
1934        Ok(out)
1935    }
1936
1937    /// `ids`, resolved to specs in the order named, or the whole `[[agents]]`
1938    /// roster in file order when `ids` is empty — the same "explicit ids
1939    /// stand alone, an empty list means the whole roster" rule [`Self::rotate`]
1940    /// applies, but with no `count` to truncate to and no `offset` to wrap by.
1941    /// See [`ResolvedRoles::implementer_roster`] for why a truncated, rotated
1942    /// list cannot answer the question this exists for.
1943    fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
1944        if ids.is_empty() {
1945            Ok(self.agents.clone())
1946        } else {
1947            ids.iter().map(|id| self.agent(id).cloned()).collect()
1948        }
1949    }
1950
1951    /// Fill the roles out to the configured widths.
1952    ///
1953    /// An empty role list rotates through the whole roster, so a three-agent
1954    /// roster with `implementers = 3` gives one implementation per agent, and
1955    /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1956    /// author of candidate *i* whenever the roster has more than one agent.
1957    pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1958        if self.agents.is_empty() {
1959            bail!(
1960                "agent roster is empty: no agent CLI found on PATH and no \
1961                 [[agents]] in the config. Run `magi init` to write a starter \
1962                 magi.toml."
1963            );
1964        }
1965        Ok(ResolvedRoles {
1966            implementers: self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
1967            judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
1968            reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
1969            fixer: match self.roles.fixer.as_ref() {
1970                // Ids are validated against the roster here; whether the CLI
1971                // is installed is left to invocation, like every other seat.
1972                Some(choice) => Some(crate::agent::pick_chain(
1973                    &self.agents,
1974                    Some(choice),
1975                    &|_| true,
1976                    "fixer",
1977                )?),
1978                None => None,
1979            },
1980            // Role resolution validates roster shape, but deliberately does
1981            // not preflight a CLI. The other graph seats have always deferred
1982            // that failure to invocation; doing it only for the conductor
1983            // made otherwise usable graph commands and `doctor` fail as one.
1984            conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
1985                Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
1986                // A fallback chain: the first id the roster knows. The rest
1987                // are `agent::pick_chain`'s business at invocation.
1988                Some(ids) if !ids.is_empty() => ids
1989                    .iter()
1990                    .find_map(|id| self.agent(id).ok())
1991                    .cloned()
1992                    .with_context(|| {
1993                        format!("[roles] conductor names no agent in the roster: {ids:?}")
1994                    })?,
1995                // Keep the normal standalone-seat preference when something
1996                // is installed, but retain a roster fallback when it is not.
1997                // Invocation then reports the unavailable CLI in the same
1998                // place it does for every other graph role.
1999                _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2000                    .unwrap_or_else(|_| self.agents[0].clone()),
2001            },
2002            implementer_roster: self.full_roster(&self.roles.implementers)?,
2003            judge_roster: self.full_roster(&self.roles.judges)?,
2004            reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2005        })
2006    }
2007
2008    /// Advisor seats for the design-deliberation stage (see
2009    /// `graph::Runner::advise`): `[roles] advisors` when set, otherwise the
2010    /// judge roster - see [`Roles::advisors`] for why that fallback and not
2011    /// the whole roster.
2012    ///
2013    /// The fallback rotates with `offset = 1`, matching the judges line in
2014    /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
2015    /// `roles.judges`, which is empty whenever judges themselves are
2016    /// unconfigured and rotating the whole roster. Falling back with
2017    /// `offset = 0` there would silently hand the advisors a *different*
2018    /// agent set than the judges an unconfigured run would actually get,
2019    /// which is the one thing [`Roles::advisors`]'s doc promises will not
2020    /// happen.
2021    ///
2022    /// Called lazily from the graph node itself rather than folded into
2023    /// [`Config::resolve_roles`]: unlike the other roles, a failure here must
2024    /// not stop a run from starting at all - the deliberation stage is an
2025    /// enrichment `[graph] advise` can turn off, not a seat later nodes
2026    /// cannot proceed without - and at the point `resolve_roles` runs (before
2027    /// [`crate::run::RunState`] exists, on `Runner::start`) there would be no
2028    /// run yet for a resolution failure to be reported against.
2029    pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2030        if self.agents.is_empty() {
2031            bail!(
2032                "agent roster is empty: no agent CLI found on PATH and no \
2033                 [[agents]] in the config. Run `magi init` to write a starter \
2034                 magi.toml."
2035            );
2036        }
2037        if !self.roles.advisors.is_empty() {
2038            return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2039        }
2040        self.rotate(&self.roles.judges, self.graph.advisors, 1)
2041    }
2042
2043    /// The untruncated roster advisor seats hand over along: `[roles]
2044    /// advisors` when set, otherwise the judges' roster, exactly as
2045    /// [`Self::advisors`] chooses its own list.
2046    pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2047        if self.roles.advisors.is_empty() {
2048            self.full_roster(&self.roles.judges)
2049        } else {
2050            self.full_roster(&self.roles.advisors)
2051        }
2052    }
2053
2054    /// Shell prefix for [`Verify`] commands.
2055    pub fn shell(&self) -> Vec<String> {
2056        if let Some(s) = &self.verify.shell {
2057            return s.clone();
2058        }
2059        if which("sh") {
2060            vec!["sh".to_owned(), "-c".to_owned()]
2061        } else {
2062            vec!["cmd".to_owned(), "/C".to_owned()]
2063        }
2064    }
2065
2066    /// Starter config, as written by `magi init`.
2067    pub fn starter_toml() -> String {
2068        let detected = Self::autodetected();
2069        let mut s = String::from(
2070            "# magi — blind multi-agent implementation competition.\n\
2071             # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2072             #   -> blind judging -> deliberation -> private final vote\n\
2073             #   -> fold losers -> review + E2E loop -> gate -> merge.\n\
2074             #\n\
2075             # Rendered by teravars: a `[vars]` table, env\n\
2076             # and system lookups, and `include = [...]` all work. Tera\n\
2077             # braces are live everywhere in this file, but comments are\n\
2078             # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2079             # may quote `{{ ... }}` freely.\n\
2080             #\n\
2081             # Layers deep-merge in increasing\n\
2082             # precedence, so the roster can live once per machine in\n\
2083             # <config_dir>/magi/config.toml and each repo only states its own\n\
2084             # gate:\n\
2085             #   <config_dir>/magi/config.toml  <  .magi/config.toml  <  magi.toml\n\n\
2086             [vars]\n\
2087             # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2088             # Single quotes inside the braces: teravars renders the raw file\n\
2089             # text, so TOML's own \\\" escaping never reaches Tera.\n\
2090             cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2091        );
2092        if detected.agents.is_empty() {
2093            s.push_str(
2094                "# No agent CLI was found on PATH. Fill this in by hand.\n\
2095                 # kind = claude | opencode | antigravity | codex | command\n\
2096                 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2097            );
2098        } else {
2099            for a in &detected.agents {
2100                s.push_str("[[agents]]\n");
2101                s.push_str(&format!("id = {:?}\n", a.id));
2102                s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2103                if let Some(m) = &a.model {
2104                    s.push_str(&format!("model = {m:?}\n"));
2105                }
2106                s.push('\n');
2107            }
2108        }
2109        s.push_str(
2110            "# Leave a role list empty to rotate through the roster.\n\
2111             # A non-empty list is also an ordered backup list: seats take entries from the\n\
2112             # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2113             # next agent to its right, each tried once. Same for judges and reviewers.\n\
2114             # implementers = [\"opus\", \"codex\", \"sonnet\"]  # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2115             [roles]\n\
2116             implementers = []\n\
2117             judges = []\n\
2118             reviewers = []\n\
2119             # conductor = \"opus\"  # arranges the queue; unset picks a seat like chatter does\n\
2120             # synthesizer = \"opus\"  # blends the advisors into one brief; unset picks a seat like chatter does\n\
2121             # synthesizer = [\"opus\", \"codex\"]  # array form: fallback chain, each tried once on quota or failure\n\
2122             # language_judge = \"jev\"  # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2123             # fixer = \"opus\"  # applies review findings; unset keeps the winner's own author\n\
2124             # fixer = [\"opus\", \"codex\"]  # array form: fallback chain, each tried once on quota or failure\n\n\
2125             [graph]\n\
2126             # Gate GitHub prose; secret redaction is always enabled.\n\
2127             github_text_guard = true\n\
2128             implementers = 3\n\
2129             judges = 3\n\
2130             deliberate_rounds = 1\n\
2131             reviewers = 3\n\
2132             review_rounds = 6\n\
2133             # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2134             gate_fix_rounds = 1\n\
2135             # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2136             rerun_flaky_checks = true\n\
2137             # Port the strengths judges named in the losing candidates onto the\n\
2138             # winner before review (best-effort; rolled back on failure or a big diff).\n\
2139             graft_runner_up = true\n\
2140             max_parallel = 4\n\
2141             language = \"en\"\n\
2142             # One CLI conversation per seat: judges keep their own argument\n\
2143             # across deliberation, the fixer keeps its implementation context.\n\
2144             sessions = true\n\
2145             # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2146             # the final gate inherit this value for compatibility.\n\
2147             timeout_review = 1200\n\
2148             # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2149             # verification independent if timeout_review changes later.\n\
2150             # timeout_verify = 1200\n\n\
2151             # What the chat calls you (persona address and the Chat's turn label).\n\
2152             # [talk]\n\
2153             # operator_name = \"Commander\"\n\n\
2154             # Chat personas (tone only; the web Chat picks one per conversation).\n\
2155             # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2156             # them, and one with a built-in's id replaces it. `default` is the plain\n\
2157             # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2158             # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2159             # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2160             # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2161             # [[talk.personas]]\n\
2162             # id = \"gendo\"\n\
2163             # name = \"Gendo Ikari\"\n\
2164             # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2165             # icon = \"~/pictures/gendo.png\"\n\n\
2166             [verify]\n\
2167             # Run once per review round in the winner's worktree; failures are\n\
2168             # fed back to the fixer.\n\
2169             e2e = []\n\
2170             # Final gate. Every command must exit 0 before a merge.\n\
2171             gate = []\n\
2172             # Mechanical fixers (formatters) run in the winner's worktree just\n\
2173             # before the gate; whatever they change becomes one commit. A failing\n\
2174             # command only warns - the gate stays the arbiter. Same timeout as the\n\
2175             # gate (timeout_verify). Keep it light and idempotent.\n\
2176             # pre_gate = []\n\n\
2177             # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2178             # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2179             # before any agent or verify command touches it. `copy` reads from the\n\
2180             # primary checkout and never overwrites; `optional` skips a missing\n\
2181             # source. `run` goes through the shell with the worktree as cwd and\n\
2182             # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2183             # the verify timeout). Setup must not edit tracked files, and what it\n\
2184             # leaves untracked is kept out of magi's commits. Declare this in one\n\
2185             # layer only.\n\
2186             # [worktree]\n\
2187             # setup = [\n\
2188             #   { copy = \".env.example -> .env\" },\n\
2189             #   { copy = \".env.local\", optional = true },\n\
2190             #   { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2191             # ]\n\n\
2192             [merge]\n\
2193             # none | local | pr\n\
2194             mode = \"none\"\n\
2195             # release_bump = true  # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2196             [update]\n\
2197             # off | notify | install — checked in the background, throttled.\n\
2198             mode = \"notify\"\n\
2199             # interval = \"24h\"\n\n\
2200             [daemon]\n\
2201             # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2202             # no new commit and no check changing state before `magi serve`\n\
2203             # notices and asks you. A failed check is rerun once on its own;\n\
2204             # still red after that escalates at once. 0 turns the watcher off.\n\
2205             # release_stall_minutes = 60\n\n\
2206             [release]\n\
2207             # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2208             # Actions never run (private, no minutes): the release pull request\n\
2209             # does not wait for CI, you approve the merge in magi, and then\n\
2210             # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2211             # runs `commands` from a clean checkout of the merge commit. A\n\
2212             # failure holds the release with a notice; it is never retried blind.\n\
2213             # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2214             # mode = \"actions\"\n\
2215             # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2216             # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2217             # safe to repeat: a crash mid-command is treated as unfinished.\n\
2218             # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2219             # timeout_minutes = 30\n",
2220        );
2221        s
2222    }
2223}
2224
2225/// Is `program` on `PATH`?
2226pub fn which(program: &str) -> bool {
2227    find_program(program).is_some()
2228}
2229
2230/// The file a bare `program` name resolves to on `PATH`, the way the OS shell
2231/// would find it.
2232///
2233/// Spawn agents through this, not by bare name: on Windows Rust's std
2234/// only tries `name.exe`, so a CLI installed as an npm `.cmd` shim (codex
2235/// since its 2026-09-23 reinstall) is "not found" even though a shell runs it.
2236/// On Windows an extensionless file is never a match: npm writes an `sh`
2237/// script beside every `.cmd` shim, and spawning that fails with os error 193.
2238pub fn find_program(program: &str) -> Option<PathBuf> {
2239    find_program_on(program, &std::env::var_os("PATH")?)
2240}
2241
2242/// [`find_program`] against an explicit `PATH`, for a child whose environment
2243/// overrides it.
2244pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2245    let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2246    find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2247}
2248
2249fn find_program_in(
2250    program: &str,
2251    paths: &std::ffi::OsStr,
2252    pathext: Option<&str>,
2253) -> Option<PathBuf> {
2254    let p = Path::new(program);
2255    if p.components().count() > 1 {
2256        return p.is_file().then(|| p.to_path_buf());
2257    }
2258    std::env::split_paths(paths).find_map(|dir| match pathext {
2259        Some(exts) => {
2260            let bare = dir.join(program);
2261            if p.extension().is_some() && bare.is_file() {
2262                return Some(bare);
2263            }
2264            exts.split(';')
2265                .filter(|e| !e.is_empty())
2266                .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2267                .find(|c| c.is_file())
2268        }
2269        None => Some(dir.join(program)).filter(|c| c.is_file()),
2270    })
2271}
2272
2273/// Sidecar naming the checkout an extracted layer stands for.
2274const REPO_MARKER: &str = ".magi-repo";
2275
2276fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2277    use crate::proc::Quiet as _;
2278    let out = std::process::Command::new("git")
2279        .args(args)
2280        .quiet()
2281        .current_dir(repo)
2282        .stdin(std::process::Stdio::null())
2283        .output()
2284        .ok()?;
2285    out.status
2286        .success()
2287        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2288}
2289
2290/// Is `repo` inside a git working tree? A directory that is not has no branch
2291/// to be stale against, so its files are read as they are.
2292fn is_git_worktree(repo: &Path) -> bool {
2293    git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2294}
2295
2296#[derive(Deserialize, Default)]
2297struct ProbeMerge {
2298    base: Option<String>,
2299    remote: Option<String>,
2300}
2301
2302#[derive(Deserialize, Default)]
2303struct Probe {
2304    merge: Option<ProbeMerge>,
2305}
2306
2307/// `[merge]` base / remote from one file, nothing else. The file is rendered
2308/// (env templates, includes) exactly as a real load would, so a machine layer
2309/// saying `base = "{{ env.X }}"` locates the same ref; when rendering fails
2310/// (a checkout file that needs its own repo context) the plain TOML is read
2311/// instead. Unreadable is `None`: the real load reports it.
2312fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2313    if !path.is_file() {
2314        return None;
2315    }
2316    let paths = [path.to_path_buf()];
2317    let mut engine = teravars::Engine::default();
2318    let mut ctx = Config::render_ctx(&paths);
2319    // The layered load renders every layer for the checkout being resolved;
2320    // so does this, or `{{ repo_name }}` would name the file's own directory.
2321    ctx.insert("repo", &repo.to_string_lossy());
2322    ctx.insert(
2323        "repo_name",
2324        &repo.file_name().unwrap_or_default().to_string_lossy(),
2325    );
2326    if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2327        && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2328    {
2329        return probe.merge;
2330    }
2331    let text = std::fs::read_to_string(path).ok()?;
2332    toml::from_str::<Probe>(&text).ok()?.merge
2333}
2334
2335/// The `[merge] remote` / `base` the layers name, before any git lookup.
2336fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2337    let mut remote = None;
2338    let mut base = None;
2339    let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2340    sources.push(repo.join("magi.toml"));
2341    sources.push(repo.join(".magi").join("config.toml"));
2342    for path in sources {
2343        if let Some(m) = probe_merge(&path, repo) {
2344            remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2345            base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2346        }
2347    }
2348    (remote.unwrap_or_else(|| "origin".to_owned()), base)
2349}
2350
2351/// Where the remote ref is: see the module doc for the order.
2352fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2353    let (remote, base) = probe_remote_base(repo);
2354    let base = match base {
2355        Some(b) => b,
2356        None => {
2357            let head = format!("refs/remotes/{remote}/HEAD");
2358            git_out(repo, &["symbolic-ref", "--quiet", &head])
2359                .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2360                .with_context(|| {
2361                    format!(
2362                        "cannot tell which branch of `{remote}` holds magi.toml: \
2363                         set [merge] base, or run `git remote set-head {remote} -a`"
2364                    )
2365                })?
2366        }
2367    };
2368    Ok((remote, base))
2369}
2370
2371fn fnv_hex(text: &str) -> String {
2372    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2373    for b in text.bytes() {
2374        hash ^= u64::from(b);
2375        hash = hash.wrapping_mul(0x0100_0000_01b3);
2376    }
2377    format!("{hash:016x}")
2378}
2379
2380/// Does the text declare an `include` directive in any form teravars accepts
2381/// (root `include`, bare or quoted, or `[teravars] include`, as a table or an
2382/// inline table)? Parsed as TOML when it parses; a templated file that does
2383/// not parse is judged by a plain search for the word, because over-detecting
2384/// only costs an extra extraction while missing one fails the load.
2385fn declares_include(text: &str) -> bool {
2386    match toml::from_str::<toml::Table>(text) {
2387        Ok(table) => {
2388            table.contains_key("include")
2389                || table
2390                    .get("teravars")
2391                    .and_then(toml::Value::as_table)
2392                    .is_some_and(|t| t.contains_key("include"))
2393        }
2394        Err(_) => text.contains("include"),
2395    }
2396}
2397
2398/// Unpack the whole tree of `sha` into `dest`, so relative `include`s of a
2399/// repository layer resolve against the same commit.
2400fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2401    use crate::proc::Quiet as _;
2402    let mut archive = std::process::Command::new("git")
2403        .args(["archive", "--format=tar", sha])
2404        .quiet()
2405        .current_dir(repo)
2406        .stdin(std::process::Stdio::null())
2407        .stdout(std::process::Stdio::piped())
2408        .stderr(std::process::Stdio::null())
2409        .spawn()
2410        .context("running git archive")?;
2411    let tar = std::process::Command::new("tar")
2412        .arg("-x")
2413        .arg("-C")
2414        .arg(dest)
2415        .quiet()
2416        .stdin(archive.stdout.take().context("git archive has no stdout")?)
2417        .output()
2418        .context("running tar")?;
2419    let status = archive.wait().context("waiting for git archive")?;
2420    if !status.success() || !tar.status.success() {
2421        bail!(
2422            "cannot unpack {sha} for the config's includes: {}",
2423            String::from_utf8_lossy(&tar.stderr).trim()
2424        );
2425    }
2426    Ok(())
2427}
2428
2429/// The repository layers (`.magi/config.toml`, `magi.toml`; lowest first) of
2430/// `<remote>/<base>`, extracted from one commit so both files agree.
2431fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2432    let (remote, base) = resolve_remote_base(repo)?;
2433    let tracking = format!("refs/remotes/{remote}/{base}");
2434    let spec = format!("{tracking}^{{commit}}");
2435    let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2436        .map(|s| s.trim().to_owned())
2437        .filter(|s| !s.is_empty())
2438        .with_context(|| {
2439            format!(
2440                "`{remote}/{base}` does not exist in this checkout; fetch it \
2441                 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2442                 a possibly stale local magi.toml instead"
2443            )
2444        })?;
2445    let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2446    let rels = [".magi/config.toml", "magi.toml"];
2447    let mut texts: Vec<(&str, String)> = Vec::new();
2448    for rel in rels {
2449        let object = format!("{sha}:{rel}");
2450        if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2451            continue;
2452        }
2453        let Some(text) = git_out(repo, &["show", &object]) else {
2454            bail!("cannot read {rel} from {remote}/{base} ({sha})");
2455        };
2456        texts.push((rel, text));
2457    }
2458    let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2459    // Content-addressed and built beside the final name, then renamed in: a
2460    // concurrent `discover` sees the whole directory or none of it, never a
2461    // half-written file.
2462    let build = |root: &Path| -> Result<PathBuf> {
2463        let final_dir = root.join(&key);
2464        if !final_dir.is_dir() {
2465            std::fs::create_dir_all(root)?;
2466            let tmp = root.join(format!(
2467                "{key}.tmp-{}-{}",
2468                std::process::id(),
2469                std::time::SystemTime::now()
2470                    .duration_since(std::time::UNIX_EPOCH)
2471                    .map(|d| d.as_nanos())
2472                    .unwrap_or_default()
2473            ));
2474            let filled = (|| -> Result<()> {
2475                std::fs::create_dir_all(&tmp)?;
2476                if wants_tree {
2477                    extract_tree(repo, &sha, &tmp)?;
2478                }
2479                for (rel, text) in &texts {
2480                    let file = tmp.join(rel);
2481                    let parent = file.parent().unwrap_or(&tmp);
2482                    std::fs::create_dir_all(parent)?;
2483                    std::fs::write(&file, text)?;
2484                    std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2485                }
2486                Ok(())
2487            })();
2488            if let Err(e) = filled {
2489                let _ = std::fs::remove_dir_all(&tmp);
2490                return Err(e);
2491            }
2492            if std::fs::rename(&tmp, &final_dir).is_err() {
2493                // Lost the race to another process building the same commit.
2494                let _ = std::fs::remove_dir_all(&tmp);
2495                if !final_dir.is_dir() {
2496                    bail!("cannot place {}", final_dir.display());
2497                }
2498            }
2499        }
2500        Ok(final_dir)
2501    };
2502    let common = git_out(
2503        repo,
2504        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2505    )
2506    .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2507    let dir = match common.map(|c| build(&c)) {
2508        Some(Ok(d)) => d,
2509        _ => build(&std::env::temp_dir().join("magi-config"))
2510            .with_context(|| format!("extracting config from {remote}/{base}"))?,
2511    };
2512    Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2513}
2514
2515#[cfg(test)]
2516mod tests {
2517    #[test]
2518    fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
2519        let mut cfg = Config::default();
2520        assert_eq!(
2521            cfg.context_window("claude-sonnet-4-5-20250929"),
2522            Some(200_000)
2523        );
2524        assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
2525        assert_eq!(cfg.context_window("mystery-model"), None);
2526        cfg.context_windows
2527            .insert("claude-sonnet-4-5".into(), 1_000_000);
2528        cfg.context_windows.insert("claude-sonnet-4".into(), 5);
2529        cfg.context_windows.insert("mystery".into(), 32_768);
2530        // Longest user prefix beats a shorter one and the built-in table.
2531        assert_eq!(
2532            cfg.context_window("claude-sonnet-4-5-20250929"),
2533            Some(1_000_000)
2534        );
2535        // An exact name beats any prefix.
2536        cfg.context_windows
2537            .insert("claude-sonnet-4-5-20250929".into(), 7);
2538        assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
2539        assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
2540    }
2541
2542    use super::*;
2543
2544    /// npm writes an extensionless `sh` script beside `codex.cmd`; on Windows
2545    /// the `.cmd` is the spawnable one (os error 193 otherwise, 2026-09-23).
2546    #[test]
2547    fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
2548        let dir = tempfile::tempdir().unwrap();
2549        std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
2550        std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
2551        let paths = dir.path().as_os_str();
2552        assert_eq!(
2553            find_program_in("codex", paths, Some(".EXE;.CMD")),
2554            Some(dir.path().join("codex.cmd"))
2555        );
2556        assert_eq!(
2557            find_program_in("codex", paths, None),
2558            Some(dir.path().join("codex"))
2559        );
2560        assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
2561    }
2562
2563    fn spec(id: &str) -> AgentSpec {
2564        AgentSpec {
2565            id: id.to_owned(),
2566            kind: AgentKind::Command,
2567            model: None,
2568            command: vec!["true".to_owned()],
2569            extra_args: Vec::new(),
2570            env: BTreeMap::new(),
2571            prompt_delivery: None,
2572        }
2573    }
2574
2575    #[test]
2576    fn github_text_guard_defaults_on_and_can_be_disabled() {
2577        let default: Graph = toml::from_str("").unwrap();
2578        assert!(default.github_text_guard);
2579        let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
2580        assert!(!disabled.github_text_guard);
2581        let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
2582        assert!(!config.graph.github_text_guard);
2583        assert!(Config::starter_toml().contains("github_text_guard = true"));
2584    }
2585
2586    #[test]
2587    fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
2588        assert!(Graph::default().rerun_flaky_checks);
2589        let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
2590        assert!(!off.rerun_flaky_checks);
2591        assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
2592    }
2593
2594    #[test]
2595    fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
2596        // `timeout_verify` used to not exist: `verify.e2e`/`verify.gate` ran
2597        // under `timeout_review`. A config written before this field existed
2598        // must run exactly as before, which means its default has to be the
2599        // same 1200s `timeout_review` has always defaulted to.
2600        let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
2601        assert_eq!(g.timeout_verify, None);
2602        assert_eq!(g.verify_timeout(), 3600);
2603    }
2604
2605    #[test]
2606    fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
2607        // The bug this field exists to close: `[graph] timeout_review = 45`
2608        // used to shrink the real-machine `verify.e2e`/`verify.gate` budget
2609        // along with the reviewer seats' own timeout, because both read the
2610        // same field.
2611        let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
2612        assert_eq!(g.timeout_review, 45);
2613        assert_eq!(
2614            g.verify_timeout(),
2615            45,
2616            "an omitted legacy value follows review"
2617        );
2618        let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
2619            .expect("parse explicit override");
2620        assert_eq!(explicit.verify_timeout(), 1200);
2621    }
2622
2623    #[test]
2624    fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
2625        let g: Graph = toml::from_str("implementers = 4\n").unwrap();
2626        assert_eq!(g.implementers, 4);
2627        let g: Graph = toml::from_str("candidates = 5\n").unwrap();
2628        assert_eq!(g.implementers, 5);
2629    }
2630
2631    fn layered(lower: &str, upper: &str) -> Result<Config> {
2632        let dir = tempfile::tempdir().unwrap();
2633        let a = dir.path().join("a.toml");
2634        let b = dir.path().join("b.toml");
2635        std::fs::write(&a, lower).unwrap();
2636        std::fs::write(&b, upper).unwrap();
2637        Config::load_layers(&[a, b])
2638    }
2639
2640    #[test]
2641    fn graph_implementers_higher_layer_wins_across_spellings() {
2642        let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
2643        assert_eq!(c.graph.implementers, 5);
2644        let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
2645        assert_eq!(c.graph.implementers, 5);
2646        let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
2647        assert_eq!(c.graph.implementers, 2);
2648    }
2649
2650    #[test]
2651    fn graph_implementers_both_keys_in_one_layer_is_refused() {
2652        let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
2653            .unwrap_err()
2654            .to_string();
2655        assert!(
2656            err.contains("candidates") && err.contains("implementers"),
2657            "{err}"
2658        );
2659        assert!(err.contains("b.toml"), "{err}");
2660    }
2661
2662    #[test]
2663    fn a_toml_layer_written_before_these_fields_existed_still_parses() {
2664        // `deny_unknown_fields` cuts both ways: a config from before
2665        // `timeout_verify`/`e2e_every_round` existed must still parse, with
2666        // both defaulted rather than refused as unknown-in-reverse.
2667        let g: Graph =
2668            toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
2669                .expect("an old-shaped [graph] table must still parse");
2670        assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
2671        assert!(
2672            !g.e2e_every_round,
2673            "off by default, same as before this field existed"
2674        );
2675    }
2676
2677    #[test]
2678    fn empty_roles_rotate_judges_off_their_own_candidate() {
2679        // Three seats, said out loud: this is a test about *rotation*, and it
2680        // has nothing to say about how many candidates a task buys by default.
2681        let cfg = Config {
2682            agents: vec![spec("a"), spec("b"), spec("c")],
2683            graph: Graph {
2684                implementers: 3,
2685                ..Graph::default()
2686            },
2687            ..Config::default()
2688        };
2689        let roles = cfg.resolve_roles().unwrap();
2690        let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
2691        let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
2692        assert_eq!(impls, ["a", "b", "c"]);
2693        assert_eq!(judges, ["b", "c", "a"]);
2694        for (i, j) in judges.iter().enumerate() {
2695            assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
2696        }
2697    }
2698
2699    #[test]
2700    fn single_agent_roster_fills_every_seat() {
2701        let cfg = Config {
2702            agents: vec![spec("solo")],
2703            graph: Graph {
2704                implementers: 3,
2705                ..Graph::default()
2706            },
2707            ..Config::default()
2708        };
2709        let roles = cfg.resolve_roles().unwrap();
2710        assert_eq!(roles.implementers.len(), 3);
2711        assert!(roles.judges.iter().all(|a| a.id == "solo"));
2712    }
2713
2714    #[test]
2715    fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
2716        // `implementers = 1` (a solo run) still resolves `implementers` down to
2717        // one slot, but `implementer_roster` must carry every agent in the
2718        // roster, in file order, for `graph::Runner`'s quota fallback to walk
2719        // forward through once that one slot's agent runs out of quota.
2720        let cfg = Config {
2721            agents: vec![spec("a"), spec("b"), spec("c")],
2722            graph: Graph {
2723                implementers: 1,
2724                ..Graph::default()
2725            },
2726            ..Config::default()
2727        };
2728        let roles = cfg.resolve_roles().unwrap();
2729        assert_eq!(roles.implementers.len(), 1);
2730        let roster: Vec<&str> = roles
2731            .implementer_roster
2732            .iter()
2733            .map(|a| a.id.as_str())
2734            .collect();
2735        assert_eq!(roster, ["a", "b", "c"]);
2736    }
2737
2738    #[test]
2739    fn implementer_roster_follows_explicit_ids_in_the_order_named() {
2740        let cfg = Config {
2741            agents: vec![spec("a"), spec("b"), spec("c")],
2742            roles: Roles {
2743                implementers: vec!["c".to_owned(), "a".to_owned()],
2744                ..Roles::default()
2745            },
2746            graph: Graph {
2747                implementers: 1,
2748                ..Graph::default()
2749            },
2750            ..Config::default()
2751        };
2752        let roles = cfg.resolve_roles().unwrap();
2753        // Unaffected by the new field: still just the first named id.
2754        assert_eq!(roles.implementers.len(), 1);
2755        assert_eq!(roles.implementers[0].id, "c");
2756        let roster: Vec<&str> = roles
2757            .implementer_roster
2758            .iter()
2759            .map(|a| a.id.as_str())
2760            .collect();
2761        assert_eq!(roster, ["c", "a"]);
2762    }
2763
2764    #[test]
2765    fn explicit_roles_win() {
2766        let cfg = Config {
2767            agents: vec![spec("a"), spec("b")],
2768            roles: Roles {
2769                implementers: vec!["b".to_owned()],
2770                judges: vec!["a".to_owned()],
2771                reviewers: Vec::new(),
2772                fixer: Some("a".into()),
2773                ..Roles::default()
2774            },
2775            ..Config::default()
2776        };
2777        let roles = cfg.resolve_roles().unwrap();
2778        assert!(roles.implementers.iter().all(|a| a.id == "b"));
2779        assert!(roles.judges.iter().all(|a| a.id == "a"));
2780        let fixer = roles.fixer.unwrap();
2781        assert_eq!(fixer.len(), 1);
2782        assert_eq!(fixer[0].id, "a");
2783        assert_eq!(roles.conductor.id, "a");
2784    }
2785
2786    #[test]
2787    fn fixer_takes_a_string_or_an_ordered_chain() {
2788        let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
2789        assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
2790        let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
2791        assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
2792
2793        let resolve = |fixer: Option<AgentChoice>| {
2794            Config {
2795                agents: vec![spec("a"), spec("b"), spec("c")],
2796                roles: Roles {
2797                    fixer,
2798                    ..Roles::default()
2799                },
2800                ..Config::default()
2801            }
2802            .resolve_roles()
2803        };
2804        let ids = |r: &ResolvedRoles| -> Vec<String> {
2805            r.fixer
2806                .as_ref()
2807                .unwrap()
2808                .iter()
2809                .map(|s| s.id.clone())
2810                .collect()
2811        };
2812        // The string form is a chain of one; unset stays unset (the winner's author).
2813        assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
2814        assert!(resolve(None).unwrap().fixer.is_none());
2815        // Order kept, an unknown id skipped, a duplicate keeps its first place.
2816        let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
2817        assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
2818        // Nothing resolving names the role.
2819        let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
2820        assert!(format!("{err:#}").contains("fixer"), "{err:#}");
2821    }
2822
2823    #[test]
2824    fn unknown_agent_id_is_an_error() {
2825        let cfg = Config {
2826            agents: vec![spec("a")],
2827            roles: Roles {
2828                judges: vec!["nope".to_owned()],
2829                ..Roles::default()
2830            },
2831            ..Config::default()
2832        };
2833        assert!(cfg.resolve_roles().is_err());
2834    }
2835
2836    #[test]
2837    fn conductor_role_is_resolved_validated_and_has_a_fallback() {
2838        let mut cfg = Config {
2839            agents: vec![spec("a"), spec("b")],
2840            ..Config::default()
2841        };
2842        assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
2843
2844        cfg.roles.conductor = Some("b".into());
2845        assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
2846
2847        cfg.roles.conductor = Some("missing".into());
2848        assert!(cfg.resolve_roles().is_err());
2849    }
2850
2851    #[test]
2852    fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
2853        let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
2854        assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
2855        assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
2856
2857        let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
2858        assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
2859        assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
2860
2861        for roles in [one, chain] {
2862            let text = toml::to_string(&roles).unwrap();
2863            let back: Roles = toml::from_str(&text).unwrap();
2864            assert_eq!(back.synthesizer, roles.synthesizer);
2865            assert_eq!(back.chatter, roles.chatter);
2866        }
2867        let text = toml::to_string(&Roles {
2868            conductor: Some("x".into()),
2869            ..Roles::default()
2870        })
2871        .unwrap();
2872        assert!(
2873            text.contains("conductor = \"x\""),
2874            "string stays a string: {text}"
2875        );
2876        assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
2877    }
2878
2879    #[test]
2880    fn an_empty_choice_counts_as_unset() {
2881        assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
2882        assert!(AgentChoice::One("  ".to_owned()).ids().is_empty());
2883        assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
2884    }
2885
2886    #[test]
2887    fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
2888        // Unlike `conductor`, `synthesizer` is never validated by
2889        // `resolve_roles` — it is looked up lazily by
2890        // `graph::Runner::synthesize_brief` the same way `[roles] chatter`
2891        // is looked up by `talk::begin`, so this exercises `agent::pick`
2892        // directly instead of going through `resolve_roles`.
2893        let mut cfg = Config {
2894            agents: vec![spec("a"), spec("b")],
2895            ..Config::default()
2896        };
2897        let want = primary(cfg.roles.synthesizer.as_ref());
2898        assert_eq!(
2899            crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
2900                .unwrap()
2901                .id,
2902            "a",
2903            "unset falls back to agent::pick's own default order"
2904        );
2905
2906        cfg.roles.synthesizer = Some("b".into());
2907        let want = primary(cfg.roles.synthesizer.as_ref());
2908        assert_eq!(
2909            crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
2910                .unwrap()
2911                .id,
2912            "b",
2913            "the named agent wins over the default order"
2914        );
2915    }
2916
2917    #[test]
2918    fn empty_roster_is_an_error() {
2919        assert!(Config::default().resolve_roles().is_err());
2920    }
2921
2922    #[test]
2923    fn advise_defaults_to_on_with_three_proposals() {
2924        let g = Graph::default();
2925        assert!(g.advise);
2926        assert!(g.graft_runner_up, "graft is on by default");
2927        assert_eq!(g.advisors, 3);
2928    }
2929
2930    #[test]
2931    fn unset_advisors_falls_back_to_the_judge_roster() {
2932        let cfg = Config {
2933            agents: vec![spec("a"), spec("b")],
2934            roles: Roles {
2935                judges: vec!["b".to_owned()],
2936                ..Roles::default()
2937            },
2938            graph: Graph {
2939                advisors: 2,
2940                ..Graph::default()
2941            },
2942            ..Config::default()
2943        };
2944        let advisors = cfg.advisors().expect("advisors resolve");
2945        assert_eq!(advisors.len(), 2);
2946        assert!(
2947            advisors.iter().all(|a| a.id == "b"),
2948            "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
2949        );
2950    }
2951
2952    #[test]
2953    fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
2954        let cfg = Config {
2955            agents: vec![spec("a"), spec("b")],
2956            roles: Roles {
2957                judges: vec!["b".to_owned()],
2958                advisors: vec!["a".to_owned()],
2959                ..Roles::default()
2960            },
2961            graph: Graph {
2962                advisors: 2,
2963                ..Graph::default()
2964            },
2965            ..Config::default()
2966        };
2967        let advisors = cfg.advisors().expect("advisors resolve");
2968        assert!(advisors.iter().all(|a| a.id == "a"));
2969    }
2970
2971    /// Neither `[roles] advisors` nor `[roles] judges` set: an unconfigured
2972    /// advisor roster must resolve to the exact same agents an unconfigured
2973    /// judge panel would get - same ids, same rotation offset - or the
2974    /// promise in [`Roles::advisors`]'s doc ("advisor diversity for free")
2975    /// does not actually hold.
2976    #[test]
2977    fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
2978        let cfg = Config {
2979            agents: vec![spec("a"), spec("b"), spec("c")],
2980            graph: Graph {
2981                advisors: 3,
2982                judges: 3,
2983                ..Graph::default()
2984            },
2985            ..Config::default()
2986        };
2987        let advisors = cfg.advisors().expect("advisors resolve");
2988        let judges = cfg.resolve_roles().expect("roles resolve").judges;
2989        let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
2990        let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
2991        assert_eq!(
2992            advisor_ids, judge_ids,
2993            "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
2994        );
2995    }
2996
2997    #[test]
2998    fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
2999        let cfg = Config {
3000            agents: vec![spec("a")],
3001            roles: Roles {
3002                advisors: vec!["nope".to_owned()],
3003                ..Roles::default()
3004            },
3005            graph: Graph {
3006                advisors: 1,
3007                ..Graph::default()
3008            },
3009            ..Config::default()
3010        };
3011        let err = cfg.advisors().expect_err("`nope` is not in the roster");
3012        assert!(format!("{err:#}").contains("nope"));
3013    }
3014
3015    #[test]
3016    fn repos_default_to_no_roots_and_a_day_of_trust() {
3017        assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3018        assert_eq!(Config::default().repos.scan_ttl, 86_400);
3019        assert_eq!(Config::default().repos.fetch_interval, 600);
3020    }
3021
3022    #[test]
3023    fn a_config_file_with_no_repos_table_still_loads() {
3024        let dir = tempfile::tempdir().unwrap();
3025        let path = dir.path().join("magi.toml");
3026        std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3027        let cfg = Config::load(&path).expect("must load without [repos]");
3028        assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3029        assert_eq!(cfg.repos.scan_ttl, 86_400);
3030    }
3031
3032    /// A fixture is the whole config under test.
3033    ///
3034    /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
3035    /// a machine where somebody had written `<config_dir>/magi/config.toml`
3036    /// the suite silently loaded it as the lowest layer. Adding `[repos]
3037    /// roots` there turned two web tests red - their fixtures declare
3038    /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
3039    /// array key spread across two layers. CI stayed green throughout,
3040    /// because a runner has no such file: the suite failed only where magi is
3041    /// actually used.
3042    ///
3043    /// So a test build has no machine layer unless it asks for one, and this
3044    /// is that promise. Written against a real file at the real location so
3045    /// it fails if `machine_layer` starts reading it again.
3046    #[test]
3047    fn a_test_build_does_not_read_the_operators_machine_config() {
3048        let repo = tempfile::tempdir().unwrap();
3049        std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3050
3051        let layers = Config::layers(repo.path());
3052        assert_eq!(
3053            layers,
3054            vec![repo.path().join("magi.toml")],
3055            "only the fixture's own file may be a layer"
3056        );
3057        if let Some(real) = dirs::config_dir() {
3058            let machine = real.join("magi").join("config.toml");
3059            assert!(
3060                !layers.contains(&machine),
3061                "the operator's {} must not be a layer in a test build",
3062                machine.display()
3063            );
3064        }
3065    }
3066
3067    #[test]
3068    fn starter_toml_loads_through_teravars() {
3069        let dir = tempfile::tempdir().unwrap();
3070        let path = dir.path().join("magi.toml");
3071        std::fs::write(&path, Config::starter_toml()).unwrap();
3072        let parsed = Config::load(&path).expect("starter config must load");
3073        assert_eq!(parsed.graph.implementers, 3);
3074        assert_eq!(parsed.merge.mode, MergeMode::None);
3075        assert_eq!(parsed.merge.style, MergeStyle::Merge);
3076        assert!(parsed.graph.sessions);
3077        assert!(parsed.graph.github_text_guard);
3078        assert_eq!(parsed.graph.timeout_review, 1200);
3079        assert_eq!(parsed.graph.verify_timeout(), 1200);
3080        assert_eq!(parsed.update.mode, UpdateMode::Notify);
3081    }
3082
3083    #[test]
3084    fn release_defaults_to_actions_and_the_starter_documents_it() {
3085        let dir = tempfile::tempdir().unwrap();
3086        let path = dir.path().join("magi.toml");
3087        std::fs::write(&path, Config::starter_toml()).unwrap();
3088        let r = Config::load(&path).unwrap().release;
3089        assert_eq!(r.mode, ReleaseMode::Actions);
3090        assert!(!r.is_local());
3091        assert!(r.commands.is_empty());
3092        assert_eq!(r.timeout_minutes, 30);
3093        assert!(Config::starter_toml().contains("# mode = \"actions\""));
3094    }
3095
3096    #[test]
3097    fn release_local_parses_and_unknown_keys_are_refused() {
3098        let dir = tempfile::tempdir().unwrap();
3099        let path = dir.path().join("magi.toml");
3100        std::fs::write(
3101            &path,
3102            "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3103        )
3104        .unwrap();
3105        let r = Config::load(&path).unwrap().release;
3106        assert!(r.is_local());
3107        assert_eq!(r.commands.len(), 2);
3108        assert_eq!(r.timeout_minutes, 5);
3109        std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3110        assert!(Config::load(&path).is_err());
3111        std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3112        assert!(Config::load(&path).is_err());
3113    }
3114
3115    #[test]
3116    fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3117        let dir = tempfile::tempdir().unwrap();
3118        let path = dir.path().join("magi.toml");
3119        std::fs::write(&path, Config::starter_toml()).unwrap();
3120        assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3121        assert!(Config::starter_toml().contains("# pre_gate = []"));
3122    }
3123
3124    #[test]
3125    fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3126        let starter = Config::starter_toml();
3127        assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3128        assert!(starter.contains("verification independent if timeout_review changes later"));
3129        assert!(starter.contains("# timeout_verify = 1200"));
3130    }
3131
3132    #[test]
3133    fn starter_toml_documents_chat_personas() {
3134        let starter = Config::starter_toml();
3135        assert!(starter.contains("# [[talk.personas]]"));
3136        assert!(starter.contains("tone only"));
3137    }
3138
3139    #[test]
3140    fn talk_personas_parse_and_are_validated() {
3141        let dir = tempfile::tempdir().unwrap();
3142        let path = dir.path().join("magi.toml");
3143        std::fs::write(
3144            &path,
3145            "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3146             [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3147        )
3148        .unwrap();
3149        let cfg = Config::load(&path).expect("loads");
3150        assert_eq!(cfg.talk.personas.len(), 2);
3151        let catalog = crate::persona::catalog(&cfg.talk.personas);
3152        let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3153        assert_eq!(
3154            (rei.name.as_str(), rei.prompt.as_str()),
3155            ("Quiet", "Be brief.")
3156        );
3157        assert_eq!(catalog.last().unwrap().id, "gendo");
3158
3159        for (body, needle) in [
3160            (
3161                "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3162                "empty `id`",
3163            ),
3164            (
3165                "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3166                "empty `prompt`",
3167            ),
3168            (
3169                "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3170                 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3171                "more than once",
3172            ),
3173            (
3174                "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3175                "cannot be redefined",
3176            ),
3177        ] {
3178            std::fs::write(&path, body).unwrap();
3179            let err = format!("{:#}", Config::load(&path).unwrap_err());
3180            assert!(err.contains(needle), "{needle}: {err}");
3181        }
3182    }
3183
3184    #[test]
3185    fn talk_operator_name_is_trimmed_and_validated() {
3186        let dir = tempfile::tempdir().unwrap();
3187        let path = dir.path().join("magi.toml");
3188        let load = |body: &str| {
3189            std::fs::write(&path, body).unwrap();
3190            Config::load(&path)
3191        };
3192        let ok = load("[talk]\noperator_name = \"  Commander \"\n").expect("ok");
3193        assert_eq!(ok.talk.operator_name(), Some("Commander"));
3194        let blank = load("[talk]\noperator_name = \"   \"\n").expect("blank");
3195        assert_eq!(blank.talk.operator_name(), None);
3196        assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3197        let long = "x".repeat(65);
3198        assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3199    }
3200
3201    #[test]
3202    fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3203        let dir = tempfile::tempdir().unwrap();
3204        let load = |body: &str| {
3205            let path = dir.path().join("c.toml");
3206            std::fs::write(&path, body).unwrap();
3207            Config::load(&path)
3208        };
3209        let ok = load(
3210            "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3211             [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3212        )
3213        .unwrap();
3214        let c = crate::persona::catalog(&ok.talk.personas);
3215        assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3216        assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3217        assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3218        let oversized = format!(
3219            "data:image/png;base64,{}",
3220            "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3221        );
3222        for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3223            for (id, fields) in [
3224                ("rei", ""),
3225                ("default", ""),
3226                ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3227            ] {
3228                let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3229                let cfg = load(&body).expect("bad icon must not invalidate config");
3230                let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3231                assert_eq!(persona.id, id);
3232                assert!(crate::persona_icon::load(bad).is_err());
3233            }
3234        }
3235        let doc = Config::starter_toml();
3236        assert!(doc.contains("# icon = "));
3237    }
3238
3239    #[test]
3240    fn talk_personas_in_two_layers_are_refused() {
3241        let dir = tempfile::tempdir().unwrap();
3242        let machine = dir.path().join("machine.toml");
3243        let repo = dir.path().join("repo.toml");
3244        let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3245        std::fs::write(&machine, one).unwrap();
3246        std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3247        let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3248        assert!(err.contains("talk.personas"), "{err}");
3249    }
3250
3251    #[test]
3252    fn starter_toml_documents_role_lists_as_backup_order() {
3253        let starter = Config::starter_toml();
3254        assert!(starter.contains("also an ordered backup list"));
3255        assert!(starter.contains("codex then sonnet are spares"));
3256    }
3257
3258    /// A repository whose ruleset forbids merge commits declares that once,
3259    /// here, rather than magi asking GitHub about it on every render (see
3260    /// [`MergeStyle`]'s own doc for why).
3261    #[test]
3262    fn a_repository_can_declare_a_linear_history_merge_style() {
3263        let dir = tempfile::tempdir().unwrap();
3264        let path = dir.path().join("magi.toml");
3265        std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3266        let parsed = Config::load(&path).expect("config must load");
3267        assert_eq!(parsed.merge.style, MergeStyle::Squash);
3268    }
3269
3270    #[test]
3271    fn later_layers_win_and_vars_render() {
3272        let dir = tempfile::tempdir().unwrap();
3273        let machine = dir.path().join("machine.toml");
3274        let project = dir.path().join("magi.toml");
3275        // The machine layer owns the roster...
3276        std::fs::write(
3277            &machine,
3278            "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3279             [graph]\ncandidates = 3\nmax_parallel = 8\n",
3280        )
3281        .unwrap();
3282        // ...and the project layer only states what is repo-specific, plus a
3283        // `[vars]` value interpolated into a command.
3284        std::fs::write(
3285            &project,
3286            "[vars]\ncache = \"/shared\"\n\n\
3287             [graph]\ncandidates = 2\n\n\
3288             [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3289        )
3290        .unwrap();
3291
3292        let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3293        assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3294        assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3295        assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3296        assert_eq!(
3297            cfg.verify.gate,
3298            ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3299        );
3300        // The rendered command is where the cache path is read back from.
3301        assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3302    }
3303
3304    #[test]
3305    fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3306        // An operator who writes no `[graph]` timeout keys at all must still
3307        // land on the hour, not on the five/fifteen minutes this turn used
3308        // to hardcode before it read from config.
3309        let g = Graph::default();
3310        assert_eq!(g.timeout_talk, 3600);
3311
3312        let dir = tempfile::tempdir().unwrap();
3313        let path = dir.path().join("magi.toml");
3314        std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3315        let cfg = Config::load(&path).expect("must load without timeout_talk set");
3316        assert_eq!(cfg.graph.timeout_talk, 3600);
3317    }
3318
3319    #[test]
3320    fn an_overridden_talk_timeout_reaches_the_loaded_config() {
3321        let dir = tempfile::tempdir().unwrap();
3322        let path = dir.path().join("magi.toml");
3323        std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
3324        let cfg = Config::load(&path).expect("must load");
3325        assert_eq!(cfg.graph.timeout_talk, 120);
3326    }
3327
3328    #[test]
3329    fn the_disk_defaults_are_the_measurements_made_up_front() {
3330        let cfg = Config::default();
3331        assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
3332        assert!(cfg.disk.auto_fold);
3333        assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
3334        assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
3335    }
3336
3337    #[test]
3338    fn an_unset_disk_section_is_the_safe_default() {
3339        let dir = tempfile::tempdir().unwrap();
3340        std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
3341        let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
3342        assert_eq!(cfg.disk, Disk::default());
3343    }
3344
3345    #[test]
3346    fn env_is_available_to_templates_with_a_default() {
3347        let dir = tempfile::tempdir().unwrap();
3348        let path = dir.path().join("magi.toml");
3349        // teravars ships no `env`; magi adds it, and the `default` filter has
3350        // to cover the unset case or every machine would need the variable.
3351        //
3352        // Deliberately no named variable: `env` is keyed by the exact spelling
3353        // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
3354        // test asserting `env.PATH` passes on one runner and fails on another.
3355        // The map's non-emptiness is the platform-neutral claim.
3356        std::fs::write(
3357            &path,
3358            "[verify]\n\
3359             gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
3360             \"populated={{ env | length > 0 }}\"]\n",
3361        )
3362        .unwrap();
3363        let cfg = Config::load(&path).expect("env lookup must render");
3364        assert_eq!(cfg.verify.gate[0], "cache=fallback");
3365        assert_eq!(cfg.verify.gate[1], "populated=true");
3366    }
3367
3368    #[test]
3369    fn a_broken_template_names_the_file() {
3370        let dir = tempfile::tempdir().unwrap();
3371        let path = dir.path().join("magi.toml");
3372        std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
3373        let err = Config::load(&path).expect_err("must not silently ignore");
3374        assert!(err.to_string().contains("teravars"), "{err}");
3375    }
3376
3377    #[test]
3378    fn tera_syntax_in_comments_is_inert() {
3379        // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
3380        // comment may quote template syntax without rendering. Before 0.2.2 this
3381        // load failed: the commented-out braces reached the template parser.
3382        let dir = tempfile::tempdir().unwrap();
3383        let path = dir.path().join("magi.toml");
3384        std::fs::write(
3385            &path,
3386            "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
3387             [graph]\ncandidates = 2\n",
3388        )
3389        .unwrap();
3390        let cfg = Config::load(&path).expect("comments must be inert, not rendered");
3391        assert_eq!(cfg.graph.implementers, 2);
3392    }
3393
3394    #[test]
3395    fn opencode_defaults_to_file_delivery() {
3396        let mut s = spec("oc");
3397        s.kind = AgentKind::Opencode;
3398        assert_eq!(s.delivery(), Delivery::File);
3399        s.prompt_delivery = Some(Delivery::Argv);
3400        assert_eq!(s.delivery(), Delivery::Argv);
3401    }
3402    #[test]
3403    fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
3404        // Both default on, and that pair is the safety property: `land` takes
3405        // over the watching an operator was doing by hand, `land_approval`
3406        // keeps the irreversible step a human decision. An unattended merge
3407        // needs BOTH flipped, which has to be chosen deliberately twice.
3408        let g = Graph::default();
3409        assert!(
3410            g.land,
3411            "stopping at an open PR left the watching to a human"
3412        );
3413        assert!(
3414            g.land_approval,
3415            "on-by-default land is only defensible while this is also on"
3416        );
3417        assert!(g.land_rounds > 0, "a loop with no budget never terminates");
3418        assert!(
3419            g.hold_contested_merge,
3420            "a contested hand-off must still reach a human when approvals are off"
3421        );
3422    }
3423    #[test]
3424    fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
3425        // teravars appends arrays. For an ordered list of seats, or an argv,
3426        // the concatenation is something neither file says - and the operator
3427        // pays for the extra seats by the token.
3428        let dir = tempfile::tempdir().unwrap();
3429        let machine = dir.path().join("machine.toml");
3430        let repo = dir.path().join("magi.toml");
3431        std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
3432        std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
3433
3434        let err = Config::load_layers(&[machine.clone(), repo.clone()])
3435            .expect_err("two layers naming one array must not merge silently")
3436            .to_string();
3437        assert!(err.contains("roles.implementers"), "{err}");
3438        // Both files are named: the fix is to delete one of them, and the
3439        // operator has to know which two to choose between.
3440        assert!(err.contains("machine.toml"), "{err}");
3441        assert!(err.contains("magi.toml"), "{err}");
3442    }
3443
3444    #[test]
3445    fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
3446        // The split the layering exists for: state a preference machine-wide,
3447        // let the repository own its own lists.
3448        let dir = tempfile::tempdir().unwrap();
3449        let machine = dir.path().join("machine.toml");
3450        let repo = dir.path().join("magi.toml");
3451        std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
3452        std::fs::write(
3453            &repo,
3454            "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
3455             [roles]\nimplementers = [\"oc\"]\n",
3456        )
3457        .unwrap();
3458
3459        let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
3460        assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
3461        assert_eq!(cfg.roles.implementers, ["oc"]);
3462        assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
3463    }
3464
3465    #[test]
3466    fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
3467        // The `editorconfig-checker` distribution problem: a shared layer
3468        // wants to add a gate command without erasing the repository's own.
3469        let dir = tempfile::tempdir().unwrap();
3470        let machine = dir.path().join("machine.toml");
3471        let repo = dir.path().join("magi.toml");
3472        std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
3473        std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3474
3475        let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3476        assert_eq!(
3477            cfg.verify.gate,
3478            [
3479                "editorconfig-checker".to_owned(),
3480                "cargo make check".to_owned()
3481            ],
3482            "low-priority (machine) command first, high-priority (repo) command after"
3483        );
3484    }
3485
3486    fn load_one(body: &str) -> Result<Config> {
3487        let dir = tempfile::tempdir().unwrap();
3488        let path = dir.path().join("magi.toml");
3489        std::fs::write(&path, body).unwrap();
3490        Config::load_layers(&[path])
3491    }
3492
3493    #[test]
3494    fn worktree_setup_defaults_to_empty_and_parses_steps() {
3495        assert!(Config::default().worktree.setup.is_empty());
3496        let cfg = load_one(
3497            "[worktree]\nsetup = [\n  { copy = \".env.example -> .env\" },\n  \
3498             { copy = \"x\", optional = true },\n  { run = \"true\", timeout_secs = 5 },\n]\n",
3499        )
3500        .unwrap();
3501        assert_eq!(cfg.worktree.setup.len(), 3);
3502        assert!(cfg.worktree.setup[1].optional);
3503        assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
3504    }
3505
3506    #[test]
3507    fn worktree_setup_rejects_malformed_steps() {
3508        for bad in [
3509            "{ copy = \"a\", run = \"b\" }",
3510            "{ optional = true }",
3511            "{ copy = \"a -> ../b\" }",
3512            "{ copy = \"a -> /abs\" }",
3513            "{ copy = \"a -> .git/config\" }",
3514            "{ run = \"b\", optional = true }",
3515            "{ copy = \"a\", timeout_secs = 3 }",
3516            "{ run = \"b\", bogus = 1 }",
3517        ] {
3518            let body = format!("[worktree]\nsetup = [{bad}]\n");
3519            assert!(load_one(&body).is_err(), "{bad}");
3520        }
3521    }
3522
3523    #[test]
3524    fn worktree_setup_in_two_layers_is_refused() {
3525        let dir = tempfile::tempdir().unwrap();
3526        let machine = dir.path().join("machine.toml");
3527        let repo = dir.path().join("magi.toml");
3528        std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
3529        std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
3530        assert!(Config::load_layers(&[machine, repo]).is_err());
3531    }
3532
3533    #[test]
3534    fn starter_toml_documents_worktree_setup() {
3535        let starter = Config::starter_toml();
3536        assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
3537        // The commented example must be valid once uncommented.
3538        let body = starter.replace("# [worktree]", "[worktree]");
3539        let mut out = String::new();
3540        let mut live = false;
3541        for line in body.lines() {
3542            if line == "[worktree]" {
3543                live = true;
3544            } else if live && !line.starts_with("# ") {
3545                live = false;
3546            }
3547            out.push_str(&if live {
3548                line.replacen("# ", "", 1)
3549            } else {
3550                line.to_owned()
3551            });
3552            out.push('\n');
3553        }
3554        let cfg = load_one(&out).expect("uncommented example loads");
3555        assert_eq!(cfg.worktree.setup.len(), 3);
3556    }
3557
3558    #[test]
3559    fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
3560        let dir = tempfile::tempdir().unwrap();
3561        let machine = dir.path().join("machine.toml");
3562        let repo = dir.path().join("magi.toml");
3563        std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
3564        std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
3565
3566        let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3567        assert_eq!(
3568            cfg.verify.e2e,
3569            ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
3570        );
3571    }
3572
3573    #[test]
3574    fn two_layers_declaring_repos_roots_are_both_scanned() {
3575        let dir = tempfile::tempdir().unwrap();
3576        let machine = dir.path().join("machine.toml");
3577        let repo = dir.path().join("magi.toml");
3578        std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
3579        std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
3580
3581        let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3582        assert_eq!(
3583            cfg.repos.roots,
3584            [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
3585        );
3586    }
3587
3588    #[test]
3589    fn duplicate_gate_commands_across_layers_both_run() {
3590        // Dropping the duplicate would be a silent surprise; the operator
3591        // sees a slower gate, never a missing one.
3592        let dir = tempfile::tempdir().unwrap();
3593        let machine = dir.path().join("machine.toml");
3594        let repo = dir.path().join("magi.toml");
3595        std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
3596        std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
3597
3598        let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3599        assert_eq!(
3600            cfg.verify.gate,
3601            ["same-command".to_owned(), "same-command".to_owned()]
3602        );
3603    }
3604
3605    #[test]
3606    fn notify_command_is_still_refused_across_two_layers() {
3607        // An argv, not a set: concatenating two of them is not a program.
3608        let dir = tempfile::tempdir().unwrap();
3609        let machine = dir.path().join("machine.toml");
3610        let repo = dir.path().join("magi.toml");
3611        std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
3612        std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
3613
3614        let err = Config::load_layers(&[machine.clone(), repo.clone()])
3615            .expect_err("an argv split across layers must not concatenate")
3616            .to_string();
3617        assert!(err.contains("notify.command"), "{err}");
3618        assert!(err.contains("machine.toml"), "{err}");
3619        assert!(err.contains("magi.toml"), "{err}");
3620    }
3621
3622    #[test]
3623    fn one_layer_declaring_verify_gate_runs_unchanged() {
3624        // The classification must not change behaviour for the configuration
3625        // this very repository has today: exactly one layer names the gate.
3626        let dir = tempfile::tempdir().unwrap();
3627        let path = dir.path().join("magi.toml");
3628        std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3629
3630        let cfg = Config::load(&path).expect("single layer must still load");
3631        assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
3632    }
3633
3634    #[test]
3635    fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
3636        let dir = tempfile::tempdir().unwrap();
3637        let machine = dir.path().join("machine.toml");
3638        let repo = dir.path().join("magi.toml");
3639        std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
3640        std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3641        let paths = vec![machine.clone(), repo.clone()];
3642
3643        let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
3644        let described =
3645            Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
3646        assert!(described.contains("editorconfig-checker && cargo make check"));
3647        assert!(
3648            described.contains(&machine.display().to_string()),
3649            "{described}"
3650        );
3651        assert!(
3652            described.contains(&repo.display().to_string()),
3653            "{described}"
3654        );
3655
3656        // A single contributing layer stays the plain one-line summary.
3657        let single = vec![repo.clone()];
3658        let solo_cfg = Config::load_layers(&single).expect("single layer loads");
3659        let solo_described =
3660            Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
3661        assert_eq!(solo_described, "cargo make check");
3662    }
3663
3664    mod remote_layers {
3665        use super::*;
3666
3667        fn git(dir: &Path, args: &[&str]) {
3668            use crate::proc::Quiet as _;
3669            let out = std::process::Command::new("git")
3670                .args(args)
3671                .quiet()
3672                .current_dir(dir)
3673                .output()
3674                .unwrap();
3675            assert!(out.status.success(), "git {args:?}: {out:?}");
3676        }
3677
3678        /// A checkout whose origin/main carries `remote` as magi.toml and whose
3679        /// working tree carries `disk`.
3680        fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
3681            let tmp = tempfile::tempdir().unwrap();
3682            let bare = tmp.path().join("o.git");
3683            git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
3684            let repo = tmp.path().join("repo");
3685            std::fs::create_dir_all(&repo).unwrap();
3686            git(&repo, &["init", "-b", "trunk"]);
3687            git(&repo, &["config", "user.name", "t"]);
3688            git(&repo, &["config", "user.email", "t@example.com"]);
3689            std::fs::write(repo.join("magi.toml"), remote).unwrap();
3690            git(&repo, &["add", "-A"]);
3691            git(&repo, &["commit", "-m", "x"]);
3692            git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
3693            git(&repo, &["push", "origin", "trunk"]);
3694            git(&repo, &["fetch", "origin"]);
3695            git(&repo, &["remote", "set-head", "origin", "trunk"]);
3696            std::fs::write(repo.join("magi.toml"), disk).unwrap();
3697            (tmp, repo)
3698        }
3699
3700        #[test]
3701        fn reads_the_remote_blob_not_the_working_tree() {
3702            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3703            let (cfg, _) = Config::discover(&repo, None).unwrap();
3704            assert_eq!(cfg.graph.implementers, 2);
3705        }
3706
3707        #[test]
3708        fn detached_head_still_reads_the_remote() {
3709            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3710            git(&repo, &["checkout", "--detach"]);
3711            let (cfg, _) = Config::discover(&repo, None).unwrap();
3712            assert_eq!(cfg.graph.implementers, 2);
3713        }
3714
3715        #[test]
3716        fn a_missing_ref_is_an_error_not_a_fallback() {
3717            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3718            git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
3719            let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
3720            assert!(err.contains("origin"), "{err}");
3721        }
3722
3723        #[test]
3724        fn merge_base_in_the_checkout_locates_the_ref() {
3725            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
3726            assert!(Config::discover(&repo, None).is_err());
3727        }
3728
3729        #[test]
3730        fn the_magi_dir_layer_is_read_too() {
3731            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3732            std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3733            std::fs::create_dir_all(repo.join(".magi")).unwrap();
3734            std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
3735            git(&repo, &["add", "-A"]);
3736            git(&repo, &["commit", "-m", "y"]);
3737            git(&repo, &["push", "origin", "trunk"]);
3738            git(&repo, &["fetch", "origin"]);
3739            let (cfg, layers) = Config::discover(&repo, None).unwrap();
3740            assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
3741            assert_eq!(layers.len(), 2);
3742        }
3743
3744        #[test]
3745        fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
3746            let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
3747            std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
3748            std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
3749            git(&repo, &["add", "-A"]);
3750            git(&repo, &["commit", "-m", "inc"]);
3751            git(&repo, &["push", "origin", "trunk"]);
3752            git(&repo, &["fetch", "origin"]);
3753            // The working tree's copy differs and must not be used.
3754            std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
3755            let (cfg, _) = Config::discover(&repo, None).unwrap();
3756            assert_eq!(cfg.graph.implementers, 2);
3757        }
3758
3759        #[test]
3760        fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
3761            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
3762            let m = t.path().join("machine.toml");
3763            std::fs::write(
3764                &m,
3765                "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
3766            )
3767            .unwrap();
3768            let (remote, base) = {
3769                let probe = probe_merge(&m, &repo).unwrap();
3770                (probe.remote, probe.base)
3771            };
3772            assert_eq!((remote, base), (None, Some("trunk".to_owned())));
3773        }
3774
3775        #[test]
3776        fn a_machine_layer_base_sees_the_checkouts_repo_name() {
3777            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3778            let m = t.path().join("machine.toml");
3779            std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
3780            let probe = probe_merge(&m, &repo).unwrap();
3781            assert_eq!(probe.base.as_deref(), Some("repo"));
3782        }
3783
3784        #[test]
3785        fn every_include_form_is_recognised() {
3786            assert!(declares_include("include = [\"a.toml\"]\n"));
3787            assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
3788            assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
3789            assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
3790            assert!(!declares_include("[graph]\ncandidates = 2\n"));
3791        }
3792
3793        #[test]
3794        fn an_explicit_config_is_read_as_named() {
3795            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3796            let own = t.path().join("own.toml");
3797            std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
3798            let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
3799            assert_eq!(cfg.graph.implementers, 4);
3800        }
3801
3802        #[test]
3803        fn discover_fetched_fails_when_the_fetch_does() {
3804            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3805            std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
3806            let rt = tokio::runtime::Builder::new_current_thread()
3807                .enable_all()
3808                .build()
3809                .unwrap();
3810            let err = rt
3811                .block_on(Config::discover_fetched(&repo, None))
3812                .unwrap_err();
3813            assert!(format!("{err:#}").contains("fetch"), "{err:#}");
3814        }
3815
3816        #[test]
3817        fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
3818            // Never-fetched remote + followRemoteHEAD=never: fetch creates
3819            // origin/trunk but not origin/HEAD, which discovery then re-reads.
3820            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3821            git(&repo, &["remote", "set-head", "origin", "-d"]);
3822            git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
3823            git(
3824                &repo,
3825                &["config", "remote.origin.followRemoteHEAD", "never"],
3826            );
3827            let rt = tokio::runtime::Builder::new_current_thread()
3828                .enable_all()
3829                .build()
3830                .unwrap();
3831            let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
3832            assert_eq!(cfg.graph.implementers, 2);
3833        }
3834
3835        #[test]
3836        fn a_non_git_directory_reads_its_files() {
3837            let dir = tempfile::tempdir().unwrap();
3838            std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
3839            let (cfg, _) = Config::discover(dir.path(), None).unwrap();
3840            assert_eq!(cfg.graph.implementers, 4);
3841        }
3842    }
3843}