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