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