Skip to main content

magi/
config.rs

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