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