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