Skip to main content

magi/
config.rs

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