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