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