Skip to main content

magi/
config.rs

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