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