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