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