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