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