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). Standard `files`-backend repositories resolve the remote-tracking
14//! ref directly from the common git directory without spawning `git`, then
15//! reuse a manifest-verified, content-addressed generation under the git common
16//! dir (`<common>/magi/config/<sha>-<hash of repo>-v2/`, user cache directory
17//! when that is not writable). On a cache miss, a single `git cat-file --batch`
18//! verifies the commit and reads both repository layers together before
19//! atomically publishing the generation. Reviewed branches may additionally
20//! enable literal owner-hold switches; these never weaken base policy or load
21//! other branch settings, includes or templates.
22//!
23//! `remote` and `base` are themselves in the file, so they are resolved in a
24//! fixed order, first hit wins:
25//!
26//! 1. `[merge] base` / `remote` of the machine layer, rendered as a real load
27//!    would (env templates, includes);
28//! 2. the same keys, read minimally (only `[merge]`, nothing deserialized into
29//!    `Config`) from the checkout's `magi.toml`, then `.magi/config.toml` -
30//!    only to *locate* the ref; an unreadable file is ignored;
31//! 3. `remote` defaults to `origin`, `base` to what
32//!    `refs/remotes/<remote>/HEAD` points at.
33//!
34//! [`Config::discover`] is synchronous and reads the remote-tracking ref as it
35//! is (`daemon::fetch_loop` keeps it fresh); [`Config::discover_fetched`] runs
36//! `git fetch` first and is what every path that starts work uses. A failed
37//! fetch, a missing ref or an unresolvable base is an **error**, never a
38//! silent fall back to the working tree or a local branch. Two cases are not
39//! that: an explicit `--config`, and a `repo` that is not a git working tree
40//! at all (no branch exists, so nothing can be stale).
41//!
42//! A repository layer that declares `include = [...]` gets the whole tree of
43//! that commit extracted, so relative includes resolve against the same
44//! commit. The directory is built beside its name and renamed in, so a
45//! concurrent `discover` never reads a half-written layer.
46use std::collections::BTreeMap;
47use std::path::{Path, PathBuf};
48
49use anyhow::{Context as _, Result, bail};
50use serde::{Deserialize, Serialize};
51
52/// Independently observed configuration failure boundary and its input target.
53/// Rendered error wording is diagnostic only, never a notification identity.
54#[derive(Debug, thiserror::Error)]
55#[error("{stage}: {target}")]
56pub(crate) struct ConfigFailure {
57    pub(crate) stage: &'static str,
58    pub(crate) target: String,
59}
60
61impl ConfigFailure {
62    fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
63        let stage = match error {
64            teravars::Error::Io(_) => "config-read",
65            teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
66            teravars::Error::Render(_) => "config-template",
67            teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
68                "config-include"
69            }
70            _ => "config-render",
71        };
72        Self::layers(stage, paths)
73    }
74
75    fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
76        let targets: Vec<_> = paths
77            .iter()
78            .map(|path| {
79                // Cache directories include a commit id. The input file, rather
80                // than its extraction location, identifies a loading failure.
81                path.ancestors()
82                    .find(|p| p.join(REPO_MARKER).is_file())
83                    .and_then(|root| path.strip_prefix(root).ok())
84                    .unwrap_or(path)
85                    .to_string_lossy()
86                    .into_owned()
87            })
88            .collect();
89        Self {
90            stage,
91            target: serde_json::to_string(&targets).expect("config paths"),
92        }
93    }
94}
95
96/// Which CLI drives an agent.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
98#[serde(rename_all = "lowercase")]
99pub enum AgentKind {
100    /// Anthropic Claude Code (`claude -p`).
101    Claude,
102    /// opencode (`opencode run`).
103    Opencode,
104    /// Antigravity CLI (`agy -p`). Gemini CLI is deliberately absent: Google
105    /// retired the standalone client for individual accounts in favour of this
106    /// one, so an adapter for it would be dead code on a live machine.
107    Antigravity,
108    /// OpenAI Codex CLI (`codex exec`). The one roster member with a real
109    /// read-only mode: `--sandbox read-only` is enforced by the CLI, not by
110    /// the prompt.
111    Codex,
112    /// oh-my-pi (`omp -p --mode=json`). Another CLI with no read-only mode of
113    /// its own - `--auto-approve` gates reads and writes together - so a
114    /// read-only seat rests on the prompt and on the worktree discipline the
115    /// other non-codex seats already rely on. It is also the roster member that
116    /// reaches DeepSeek, whose models ship in `omp`'s own catalog.
117    Omp,
118    /// Arbitrary command. The escape hatch, and what the test suite drives.
119    Command,
120}
121
122impl AgentKind {
123    /// Executable that must be on `PATH` for this kind, if any.
124    pub fn program(self) -> Option<&'static str> {
125        match self {
126            Self::Claude => Some("claude"),
127            Self::Opencode => Some("opencode"),
128            Self::Antigravity => Some("agy"),
129            Self::Codex => Some("codex"),
130            Self::Omp => Some("omp"),
131            Self::Command => None,
132        }
133    }
134
135    /// Lowercase name as written in the config file.
136    pub fn as_str(self) -> &'static str {
137        match self {
138            Self::Claude => "claude",
139            Self::Opencode => "opencode",
140            Self::Antigravity => "antigravity",
141            Self::Codex => "codex",
142            Self::Omp => "omp",
143            Self::Command => "command",
144        }
145    }
146
147    /// Every kind the roster can name, in display order.
148    ///
149    /// This is what `magi doctor` lists, and it has to be one list rather than
150    /// the same set typed out again wherever a kind is enumerated. The last
151    /// time it was typed out twice, `omp` was added as a roster member and the
152    /// doctor output went on saying the machine had four CLIs - which reads as
153    /// "that agent is not installed" to the person the command exists for.
154    pub const ALL: [Self; 6] = [
155        Self::Claude,
156        Self::Opencode,
157        Self::Antigravity,
158        Self::Codex,
159        Self::Omp,
160        Self::Command,
161    ];
162}
163
164/// How the prompt reaches the agent process.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
166#[serde(rename_all = "lowercase")]
167pub enum Delivery {
168    /// Piped on stdin.
169    Stdin,
170    /// Passed as a positional argument. Beware OS command-line limits.
171    Argv,
172    /// Written to a file; the agent is told to read it. No length limit.
173    File,
174}
175
176/// One addressable agent in the roster.
177#[derive(Debug, Clone, Deserialize, Serialize)]
178#[serde(deny_unknown_fields)]
179pub struct AgentSpec {
180    /// Stable identifier used by `[roles]` and by the stats tables.
181    pub id: String,
182    /// Which CLI to drive.
183    pub kind: AgentKind,
184    /// Model passed through to the CLI (`--model` / `-m`). CLI default if unset.
185    #[serde(default)]
186    pub model: Option<String>,
187    /// `kind = "command"` only: argv. Supports `{prompt_file}`, `{cwd}`,
188    /// `{label}`, `{session}` placeholders.
189    #[serde(default)]
190    pub command: Vec<String>,
191    /// Extra arguments appended to the built command line.
192    #[serde(default)]
193    pub extra_args: Vec<String>,
194    /// Extra environment variables for the child process.
195    #[serde(default)]
196    pub env: BTreeMap<String, String>,
197    /// Override the per-kind prompt delivery default.
198    #[serde(default)]
199    pub prompt_delivery: Option<Delivery>,
200    /// Optional per-invocation cap, in seconds, for this CLI. The caller's
201    /// remaining budget still wins when shorter; successors keep their budget.
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub max_turn_secs: Option<u64>,
204}
205
206impl AgentSpec {
207    /// Limit one CLI turn without extending the caller's remaining budget.
208    pub fn turn_timeout(&self, budget: std::time::Duration) -> std::time::Duration {
209        self.max_turn_secs.map_or(budget, |secs| {
210            budget.min(std::time::Duration::from_secs(secs))
211        })
212    }
213
214    /// Default prompt delivery for this agent.
215    ///
216    /// `opencode` and `agy` take the prompt as an argument, which on Windows
217    /// caps out around 32 KiB — well under a judging prompt carrying three
218    /// patches — so both get a file instead.
219    pub fn delivery(&self) -> Delivery {
220        self.prompt_delivery.unwrap_or(match self.kind {
221            AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
222            // `codex exec -` reads the prompt from stdin, so the whole
223            // instruction arrives without an argv length limit and without a
224            // tool round-trip to open a file.
225            AgentKind::Codex => Delivery::Stdin,
226            // `omp -p` reads the prompt from stdin too, and a judging prompt
227            // carrying three patches is well past the Windows argv cap, so this
228            // is the only delivery that works for every node.
229            AgentKind::Omp => Delivery::Stdin,
230            AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
231        })
232    }
233
234    /// Human-facing label, e.g. `opus (claude:opus)`.
235    pub fn display(&self) -> String {
236        match &self.model {
237            Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
238            None => format!("{} ({})", self.id, self.kind.as_str()),
239        }
240    }
241}
242
243/// A standalone seat's agent: one roster id, or an ordered fallback chain.
244///
245/// The string form is what every existing config uses and serializes back as
246/// a string; the array form tries each id at most once, in order, moving on
247/// when a call ends in quota or fails (see [`crate::agent::pick_chain`]).
248/// An empty string or array is the same as unset.
249#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
250#[serde(untagged)]
251pub enum AgentChoice {
252    /// One agent id.
253    One(String),
254    /// Ordered fallback chain of agent ids.
255    Chain(Vec<String>),
256}
257
258impl AgentChoice {
259    /// The ids named, in order, with blanks dropped. Empty means unset.
260    pub fn ids(&self) -> Vec<&str> {
261        let all: Vec<&str> = match self {
262            Self::One(id) => vec![id.as_str()],
263            Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
264        };
265        all.into_iter()
266            .map(str::trim)
267            .filter(|id| !id.is_empty())
268            .collect()
269    }
270
271    /// The first id named, if any.
272    pub fn primary(&self) -> Option<&str> {
273        self.ids().into_iter().next()
274    }
275}
276
277impl From<&str> for AgentChoice {
278    fn from(id: &str) -> Self {
279        Self::One(id.to_owned())
280    }
281}
282
283/// The first id of an optional choice: what a single-seat caller resolves.
284pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
285    choice.and_then(AgentChoice::primary)
286}
287
288/// Explicit role assignment. Empty lists are filled in by
289/// [`Config::resolve_roles`] by rotating the roster.
290#[derive(Debug, Clone, Default, Deserialize, Serialize)]
291#[serde(deny_unknown_fields, default)]
292pub struct Roles {
293    /// Agents that implement the task, one worktree each.
294    pub implementers: Vec<String>,
295    /// Agents that rank the candidates blind.
296    pub judges: Vec<String>,
297    /// Agents that review the winning patch.
298    pub reviewers: Vec<String>,
299    /// Agent that applies review findings. Defaults to the winner's author.
300    ///
301    /// Accepts one id or an ordered array of ids: a fallback chain, see
302    /// [`AgentChoice`]. The review loop, the gate-fix round, `land`'s fix
303    /// rounds and the rebase conflict round move to the next id when one
304    /// errors, hits its quota or answers nothing usable; each id is tried at
305    /// most once per call, and once a fallback answered, the rest of the run
306    /// starts from it (see `crate::fixer`). Unset keeps the winner's author.
307    pub fixer: Option<AgentChoice>,
308    /// Agent that answers the standing chat's turns (`src/talk.rs`).
309    ///
310    /// Unset picks a `claude` seat, else the first runnable agent in roster
311    /// order (see [`crate::agent::pick`]) - which is roster *order*, not a
312    /// judgement about who converses well. Naming one here matters once an
313    /// agent is also sitting as a judge: the chat is opened far more often
314    /// than any single competition, and every open competes with that judge
315    /// seat for the same account's concurrency. A timeout on an ordinary chat
316    /// turn traced to exactly this - `opus` triple-booked as chatter and judge
317    /// - is what this field exists to let an operator break apart.
318    ///
319    /// Accepts one id or an ordered array of ids: a fallback chain, see
320    /// [`AgentChoice`].
321    pub chatter: Option<AgentChoice>,
322    /// Agent that judges duplicate-work claims in [`crate::dupes`].
323    /// Unset inherits [`Self::chatter`], including its default agent selection.
324    /// Accepts a string or an ordered fallback chain, like [`Self::chatter`].
325    pub dupes_judge: Option<AgentChoice>,
326    /// Agent that arranges the queue between polls: `crate::conduct`'s single
327    /// seat, called once per cycle to decide a runnable task's `blocked_by`
328    /// and how a stalled or finished task recovers.
329    ///
330    /// The same precedent as [`Self::chatter`] for a seat that stands alone
331    /// rather than rotating through the roster - resolved through
332    /// [`crate::agent::pick`], so unset falls back to its own default order
333    /// (a claude seat, else the first runnable agent) rather than reusing a
334    /// judge or reviewer seat that the conductor's own poll-cycle cadence
335    /// would otherwise compete with for the same account's concurrency.
336    ///
337    /// Accepts a string or a fallback chain, like [`Self::chatter`].
338    pub conductor: Option<AgentChoice>,
339    /// Seats for the design-deliberation stage `graph::Runner::advise` runs
340    /// before `implement`: independent, read-only design proposals gathered
341    /// once a run has a settled task instruction and before any implementer
342    /// touches the repository.
343    ///
344    /// Empty falls back to `judges` rather than to the whole roster: a panel
345    /// trusted to rank patches independently is exactly the panel worth
346    /// asking to sketch a design independently, and an operator who has
347    /// already thought about judge diversity gets advisor diversity for free
348    /// instead of a fourth roster to maintain.
349    pub advisors: Vec<String>,
350    /// Agent that blends [`Self::advisors`]' proposals into the one design
351    /// brief `graph::Runner::synthesize_brief` carries into every
352    /// implementer's prompt.
353    ///
354    /// The same precedent as [`Self::chatter`] and [`Self::conductor`] for a
355    /// seat that stands alone rather than rotating through the roster -
356    /// resolved through [`crate::agent::pick`], so unset falls back to its
357    /// own default order (a claude seat, else the first runnable agent in
358    /// roster order) - exactly today's behavior, unchanged by leaving this
359    /// field out.
360    ///
361    /// Accepts a string or a fallback chain, like [`Self::chatter`].
362    pub synthesizer: Option<AgentChoice>,
363    /// Agent (normally a `kind = "command"` wrapper around Jev) that decides
364    /// whether a pull request title and prose are English, for
365    /// [`crate::github_text`]'s posting gate.
366    ///
367    /// Unset spawns nothing: the gate keeps its built-in heuristics. Set, a
368    /// failed, timed-out or unparsable call also falls back to them, so the
369    /// gate never depends on this seat being reachable. Accepts a string or a
370    /// fallback chain, like [`Self::chatter`].
371    pub language_judge: Option<AgentChoice>,
372}
373
374/// Graph shape and limits.
375#[derive(Debug, Clone, Deserialize, Serialize)]
376#[serde(deny_unknown_fields, default)]
377pub struct Graph {
378    /// Retired `editing_network` (codex editing seats run unsandboxed since
379    /// v0.208.0). Run records written by v0.205-v0.207 snapshot it in their
380    /// config, so the key is still accepted and ignored; never written.
381    #[serde(rename = "editing_network", skip_serializing)]
382    pub retired_editing_network: Option<serde::de::IgnoredAny>,
383    /// Gate GitHub prose before posting. Secret redaction remains mandatory when disabled.
384    pub github_text_guard: bool,
385    /// Language of pull request / issue titles, bodies and GitHub comments
386    /// (`en` / `ja` / any language name). Default `en`. Anything but English
387    /// switches off the posting gate's English-only language check for those
388    /// texts (secret redaction stays); commit messages are always English.
389    /// Independent of [`Self::language`], which is for the operator.
390    pub github_language: String,
391    /// Parallel implementations of the same task (the number of implementer
392    /// seats; pairs with [`Roles::implementers`]). **One by default.**
393    ///
394    /// Formerly `candidates`, still read as a deprecated alias.
395    ///
396    /// Competition is the thing magi is for, and it is still here - it is just
397    /// no longer what every task buys without being asked. Three days and 13
398    /// runs on this repository, which is the workload these numbers are drawn
399    /// from:
400    ///
401    /// - **0 of 13** competed runs reached a merge. Everything that landed in
402    ///   that window went through `magi review` - the cheap half, no
403    ///   competition - and passed on the first try.
404    /// - The judges' first choices **split 73% of the time** (8 of 11
405    ///   tallies). Candidates that close together make the ranking a weak
406    ///   signal for what it costs to produce.
407    /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
408    ///   review 28min, **verify 5min** - and verify is the node that caught a
409    ///   defect every reviewer had passed as clean. The cheapest step is the
410    ///   one that earns its place every time.
411    ///
412    /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
413    /// single-seat default would have shipped the worse implementation in
414    /// roughly a quarter of them. That is exactly why this is a *default* and
415    /// not a removal - `magi run --candidates N` and a per-task seat count are
416    /// how a task that deserves a competition gets one.
417    ///
418    /// A single-candidate run needs no special case: `Runner::review`'s doc
419    /// records that `execute` already degrades to implement -> review -> gate
420    /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
421    /// no two first choices to reconcile and `vote` returns early.
422    #[serde(alias = "candidates")]
423    pub implementers: usize,
424    /// Durable owner selection for a replacement implementation. No fallback.
425    #[serde(default)]
426    pub selected_implementer: Option<String>,
427    /// Independent judges.
428    pub judges: usize,
429    /// Deliberation rounds when the judges' first choices disagree.
430    pub deliberate_rounds: usize,
431    /// Reviewers per review round. **Three by default** - the smallest panel
432    /// a lens cycle (see [`crate::prompt::Lens`]) covers exactly once, so the
433    /// default panel reads the patch for spec compliance, regressions, and
434    /// simplicity without repeating an angle. Review is also the one stage
435    /// [`Self::implementers`]'s doc describes as running on every task
436    /// regardless of competition, which is what makes a panel worth its cost
437    /// here even though `implementers` itself defaults to one.
438    pub reviewers: usize,
439    /// Maximum review+fix rounds before the run is declared blocked.
440    pub review_rounds: usize,
441    /// Fix rounds a failing `verify.gate` gets before the run is blocked. The
442    /// fixer is handed the gate's own output; `0` keeps the old behaviour of
443    /// blocking on the first red gate. Independent of [`Self::review_rounds`]
444    /// so a run that spent its review budget can still repair a one-line gate
445    /// failure.
446    pub gate_fix_rounds: usize,
447    /// Maximum agent processes running at once.
448    pub max_parallel: usize,
449    /// Language for the prose the agents write (`en` / `ja` / any language name).
450    pub language: String,
451    /// Keep one CLI conversation per seat, so a judge remembers its own
452    /// argument across deliberation rounds and the fixer remembers its own
453    /// implementation across review rounds.
454    ///
455    /// Sessions are scoped to a *seat*, never to an agent id: the same model
456    /// sitting as implementer and as judge gets two unrelated conversations,
457    /// which is what keeps blind judging blind.
458    pub sessions: bool,
459    /// Per-node timeouts, seconds.
460    pub timeout_implement: u64,
461    /// Per-node timeouts, seconds.
462    pub timeout_judge: u64,
463    /// Per-node timeouts, seconds.
464    pub timeout_review: u64,
465    /// Timeout for `verify.e2e` and `verify.gate`, seconds. Separate from
466    /// [`Self::timeout_review`] so shrinking a reviewer's budget cannot
467    /// silently shrink a real-machine command's budget too — the two used to
468    /// share `timeout_review`, and turning a slow reviewer down cut the
469    /// timeout `cargo test --all-targets` runs under along with it. When
470    /// omitted, preserves legacy configurations by using
471    /// [`Self::timeout_review`]. Set an explicit value to make verification
472    /// independent of later review-seat budget changes.
473    pub timeout_verify: Option<u64>,
474    /// Per-node timeouts, seconds.
475    pub timeout_fix: u64,
476    /// Wall-clock limit for one turn of [`crate::talk`]'s standing
477    /// conversation, seconds.
478    ///
479    /// An hour: the operator is not watching this turn resolve in real time,
480    /// so the budget can match what the work - reading files, running
481    /// commands, checking their output - actually needs rather than what a
482    /// person waiting on a phone can tolerate.
483    pub timeout_talk: u64,
484    /// Longest an agent seat or verification batch may wait for the shared
485    /// build cache's lease before starting, seconds.
486    ///
487    /// A separate clock from every `timeout_*` above: those start when the CLI
488    /// or verification command is spawned and never include this wait.
489    /// Expiry is a resource block (a
490    /// resumable hold that spends no attempt and rotates no agent), not an
491    /// agent timeout.
492    pub timeout_resource_wait: u64,
493    /// Retries for an agent invocation that fails or returns nothing usable.
494    pub retries: usize,
495    /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
496    pub worktree_root: Option<PathBuf>,
497    /// After the pull request is open, keep going: watch its checks and
498    /// reviews, run a fix round when they are unhappy, and ask to merge.
499    ///
500    /// On, because stopping at an open pull request left the operator doing
501    /// the watching by hand - six times in the session this was built in - and
502    /// that is the work the loop exists to take. It only engages for
503    /// `merge = "pr"`; every other merge mode ends the run as before.
504    ///
505    /// Turning this on does **not** hand magi the merge button:
506    /// [`Graph::land_approval`] is on too, and nothing merges without an
507    /// explicit answer. Setting both to their non-defaults is the only way to
508    /// get an unattended merge, and it has to be chosen twice.
509    pub land: bool,
510    /// Land rounds - watch, fix, push - before the run is left for a human.
511    pub land_rounds: usize,
512    /// When `land` sees a required check fail on the head it is bound to, rerun
513    /// that check's workflow run once (`gh run rerun <id> --failed`) before
514    /// spending a fix round on it. A run id is rerun at most once, recorded
515    /// before the call, and forgotten when the head moves; the rerun costs no
516    /// fix round and no attempt. A failure with no workflow run (an external
517    /// status) goes straight to the fixer. On; off sends every red check to
518    /// the fixer at once.
519    pub rerun_flaky_checks: bool,
520    /// Ask the owner before merging, showing what is about to land.
521    ///
522    /// On, and it is what makes `land` safe to have on: the question carries a
523    /// rendered panel - the diffstat, the patch, the checks, the review
524    /// comments that were addressed, and the subject the squash will use - so
525    /// the decision is made on evidence rather than on trust, from wherever
526    /// the operator happens to be.
527    ///
528    /// Silence is a hold. An unanswered approval never merges, and neither
529    /// does any answer other than the word `merge`.
530    pub land_approval: bool,
531    /// Ask the owner when open Major-or-above internal findings OR a final
532    /// rejecting reviewer vote remain. Final votes use reconsideration when
533    /// answered, otherwise the initial vote. On by default; even a reject with
534    /// zero Major findings requires approval when this control is enabled.
535    ///
536    /// `land_approval` independently asks about every merge. With both controls
537    /// off, new ordinary approvals are skipped. Neither control bypasses an
538    /// existing question or owner decision, nor the fresh approval required
539    /// after merge repair (including repair that leaves the head unchanged).
540    /// The pull request is opened either way; only the merge waits.
541    pub hold_contested_merge: bool,
542    /// Retired setting accepted for saved config compatibility only. Task
543    /// inquiries always route to chat; this value never selects a workflow.
544    pub question_routing: bool,
545    /// After a run's pull request merges, file the findings its last review
546    /// round left open as follow-up tasks (`crate::followup`) instead of
547    /// letting them vanish with the merge: every Major-or-above finding, and
548    /// every finding of a seat whose final vote was reject. Other Minor/Nit
549    /// findings are only listed in the pull-request comment. Does not affect
550    /// whether the merge happens. On; best-effort, a failure is a run event.
551    pub file_followups: bool,
552    /// After a run's pull request merges, release the follow-up tasks the
553    /// merge approval's deputy filed held for that pull request
554    /// (`crate::followup::settle_deputy_tasks`): only a task the deputy filed
555    /// for this run whose hold reason names this pull request, exactly once,
556    /// and never one that duplicates an automatic follow-up (that one is left
557    /// held with the reason). The generation cap applies. Independent of
558    /// `file_followups`. On; off leaves them held until `magi task release`.
559    pub release_deputy_followups: bool,
560    /// How long to wait for an owner to answer a question before the run is
561    /// abandoned, seconds. A parked run costs nothing, so this is generous;
562    /// it exists so a forgotten question cannot pin a worktree forever.
563    pub answer_timeout: u64,
564    /// What a round does when one or more reviewer seats never answered
565    /// (timeout, crash, unparsable output).
566    pub incomplete_review: IncompleteReviewPolicy,
567    /// Run `verify.e2e` on every round, even one that already has blocking
568    /// findings and another round left to try.
569    ///
570    /// Off by default: a round with a blocking finding and rounds still left
571    /// is going back to the fixer regardless of what `verify.e2e` says, so
572    /// running it first only spends the round's slowest step (minutes, on a
573    /// Rust repo's `cargo test --all-targets`) on a head about to be
574    /// rewritten anyway. `verify.e2e` still runs once a round has no
575    /// blocking findings left (a round cannot go `clean` without it) and the
576    /// final `verify.gate` always runs on the actual tree that would land —
577    /// deferring is about *when* e2e runs mid-loop, never about skipping it.
578    ///
579    /// Set this to restore the old every-round diagnostic behaviour: e2e
580    /// output from a round that still has blocking findings is occasionally
581    /// useful on its own (a runtime failure a reviewer's panel would not
582    /// have caught by reading), and this is the way back to seeing it every
583    /// round instead of only once the panel has nothing left to flag.
584    pub e2e_every_round: bool,
585    /// When `verify.e2e` fails with an ordinary test result (not a build/link
586    /// failure, timeout or resource block), run the failed command once more
587    /// on the same commit, in the same worktree and under the same cache
588    /// lease, before anything is decided from it. A second run that passes
589    /// verifies the head, but the first failure is recorded as a flake
590    /// (`RunState::verify_flakes`, a `verify` event, `magi show`, the web run
591    /// page) and filed once as a queue task asking for the root cause
592    /// (`crate::flake`). A second failure stands exactly as before, with the
593    /// second run's output handed to the fixer. The rerun gets its own full
594    /// `timeout_verify` and spends no review round, fix round or task attempt.
595    /// On; off decides on the first result, as before this existed.
596    pub rerun_failed_e2e: bool,
597    /// Run the design-deliberation stage before `implement`: independent
598    /// advisor seats each sketch a design, and (when at least one produced a
599    /// usable proposal) a synthesis blends them into a brief carried in the
600    /// implementer's prompt. See `graph::Runner::advise`.
601    ///
602    /// On by default. A design sketch is a few paragraphs an agent can write
603    /// without touching the repository, where a full implementation is a
604    /// tool loop that re-reads the codebase on every turn - so three
605    /// sketches, gathered once before `implement` starts, cost a fraction of
606    /// a fourth candidate and buy back a form of the same disagreement
607    /// [`Self::implementers`]'s doc describes moving away from being the
608    /// default, on every run rather than only the ones an operator remembers
609    /// to ask for with `--implementers`.
610    pub advise: bool,
611    /// How many independent design proposals the deliberation stage gathers.
612    /// **Three by default** - the same number [`Self::implementers`]'s doc
613    /// names as the point where a fourth judge's first choice stopped
614    /// changing the tally.
615    pub advisors: usize,
616    /// After the tally picks a winner and before the review loop, a fixer
617    /// round ports the strengths the judges explicitly attributed to the
618    /// losing candidates onto the winner (`graph::Runner::graft`). Skipped
619    /// for a single candidate, a run with no winner or no quorum, and when
620    /// no judge recorded a strength for a loser. Best-effort: a failure, a
621    /// quota hit or no change restores the winner's pre-graft commit and the
622    /// run carries on as if this were off.
623    /// On by default.
624    pub graft_runner_up: bool,
625}
626
627impl Default for Graph {
628    fn default() -> Self {
629        Self {
630            github_text_guard: true,
631            github_language: "en".into(),
632            implementers: 1,
633            selected_implementer: None,
634            retired_editing_network: None,
635            judges: 3,
636            deliberate_rounds: 1,
637            reviewers: 3,
638            review_rounds: 6,
639            gate_fix_rounds: 1,
640            max_parallel: 4,
641            language: "en".to_owned(),
642            sessions: true,
643            timeout_implement: 3600,
644            timeout_judge: 1200,
645            timeout_review: 1200,
646            timeout_verify: None,
647            timeout_fix: 1800,
648            timeout_talk: 3600,
649            timeout_resource_wait: 1800,
650            retries: 1,
651            worktree_root: None,
652            land: true,
653            land_rounds: 4,
654            rerun_flaky_checks: true,
655            land_approval: true,
656            hold_contested_merge: true,
657            question_routing: true,
658            file_followups: true,
659            release_deputy_followups: true,
660            answer_timeout: 86_400,
661            incomplete_review: IncompleteReviewPolicy::Block,
662            e2e_every_round: false,
663            rerun_failed_e2e: true,
664            advise: true,
665            advisors: 3,
666            graft_runner_up: true,
667        }
668    }
669}
670
671impl Graph {
672    /// Effective machine-command budget. Older configuration files had only
673    /// `timeout_review`, which also governed verification, so absence is a
674    /// compatibility fallback rather than a new 1200-second default.
675    pub fn verify_timeout(&self) -> u64 {
676        self.timeout_verify.unwrap_or(self.timeout_review)
677    }
678
679    /// Does the posting gate enforce English on GitHub text? The one place
680    /// that decides it: the guard is on *and* `github_language` is English.
681    pub fn language_gate(&self) -> bool {
682        self.github_text_guard && self.github_english()
683    }
684
685    /// Is GitHub text English (the default), whether or not the gate is on?
686    pub fn github_english(&self) -> bool {
687        crate::lang::is_english(&self.github_language)
688    }
689}
690
691/// What a review round does when a reviewer seat never answered.
692///
693/// A round where half the panel timed out is not evidence of a clean patch —
694/// it is evidence of nothing. The default refuses to call that clean; `warn`
695/// exists for an operator who would rather keep a flaky seat from stalling
696/// every run, and accepts that the gap is on them to read in the report.
697#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
698#[serde(rename_all = "lowercase")]
699pub enum IncompleteReviewPolicy {
700    /// A round with a missing seat is never `clean`: with nothing raised to
701    /// fix, the round is re-reviewed instead of gating; with the max rounds
702    /// exhausted, the run is left `Blocked` rather than declared ready.
703    Block,
704    /// A round with a missing seat can still gate as clean, once every seat
705    /// that *did* answer raised nothing blocking and verification is green.
706    /// The record keeps the gap visible (`magi show`, `magi stats`) even
707    /// though the run does not wait on it.
708    Warn,
709}
710
711/// What to do when vendor-identifying text is found in material shown to judges.
712#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
713#[serde(rename_all = "lowercase")]
714pub enum LeakPolicy {
715    /// Record the leak, show the patch unmodified.
716    Warn,
717    /// Replace the token with `[REDACTED]` in the presented patch.
718    Redact,
719    /// Abort the run.
720    Fail,
721}
722
723/// Blindness policy.
724///
725/// Commit messages and candidate summaries are *always* stripped of
726/// attribution trailers and redacted — that is where signatures actually
727/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
728/// redaction would corrupt the artifact under judgement.
729#[derive(Debug, Clone, Deserialize, Serialize)]
730#[serde(deny_unknown_fields, default)]
731pub struct Blind {
732    /// Install a per-worktree `commit-msg` hook that deletes attribution
733    /// trailers before they can land in a candidate's history.
734    pub commit_msg_hook: bool,
735    /// Literal, case-insensitive substrings. A line containing any of them is
736    /// dropped from commit messages and summaries; the `commit-msg` hook is
737    /// generated from the same list.
738    pub strip_lines: Vec<String>,
739    /// Case-insensitive substrings that identify a vendor or model.
740    pub vendor_tokens: Vec<String>,
741    /// Policy for vendor tokens found in the patch body.
742    pub on_leak: LeakPolicy,
743    /// Seed for label assignment and per-judge presentation order. Derived from
744    /// the run id when unset; set it to make a run reproducible.
745    pub seed: Option<u64>,
746}
747
748impl Default for Blind {
749    fn default() -> Self {
750        Self {
751            commit_msg_hook: true,
752            strip_lines: [
753                "Co-Authored-By:",
754                "Signed-off-by:",
755                "Assisted-by:",
756                "Generated-by:",
757                "Generated with",
758                "\u{1f916}",
759            ]
760            .iter()
761            .map(|s| (*s).to_owned())
762            .collect(),
763            vendor_tokens: [
764                "claude",
765                "anthropic",
766                "codex",
767                "openai",
768                "chatgpt",
769                "gemini",
770                "grok",
771                "xai",
772                "copilot",
773                "opencode",
774                "qoder",
775                "cursor",
776                "\u{1f916}",
777            ]
778            .iter()
779            .map(|s| (*s).to_owned())
780            .collect(),
781            on_leak: LeakPolicy::Warn,
782            seed: None,
783        }
784    }
785}
786
787/// Where managed Cargo build outputs are stored.
788#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, clap::ValueEnum)]
789#[serde(rename_all = "snake_case")]
790pub enum BuildCache {
791    /// Use the shared cache configured by the repository, if any.
792    #[default]
793    Shared,
794    /// Keep build outputs isolated from other runs and worktrees.
795    Isolated,
796}
797
798impl std::fmt::Display for BuildCache {
799    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
800        f.write_str(match self {
801            Self::Shared => "shared",
802            Self::Isolated => "isolated",
803        })
804    }
805}
806
807/// Shell commands that gate the winner.
808#[derive(Debug, Clone, Default, Deserialize, Serialize)]
809#[serde(deny_unknown_fields, default)]
810pub struct Verify {
811    /// Build output policy for new runs.
812    pub build_cache: BuildCache,
813    /// Run in the winner's worktree once per review round. Its output is fed
814    /// back to the fixer. This is the "real machine" leg of the review.
815    pub e2e: Vec<String>,
816    /// Final gate. Must all exit 0 before a merge is attempted.
817    pub gate: Vec<String>,
818    /// Mechanical fixers (formatters) run in the winner's worktree before
819    /// `e2e` and again just before `gate`. Anything they change is committed
820    /// as one neutral-identity commit, so e2e, the gate and the PR all see the
821    /// same tree and e2e is not owed a second time for a formatter's diff. A
822    /// command that fails or times out is a warning, never a failed run: the
823    /// gate stays the single arbiter. Empty (the default) turns the feature
824    /// off. Runs under `graph.verify_timeout()` per command, like the gate.
825    /// Meant for light tools: it is not scanned for `CARGO_TARGET_DIR`, and it
826    /// must be idempotent, since it runs more than once per run and a command
827    /// that changes the tree every time makes a commit every time.
828    #[serde(default)]
829    pub pre_gate: Vec<String>,
830    /// Shell used to run the commands above. Defaults to `sh -c`, or
831    /// `cmd /C` when `sh` is not on `PATH`.
832    pub shell: Option<Vec<String>>,
833}
834
835impl Verify {
836    /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
837    /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
838    /// this reads back. One rendering is enough - they all set the same
839    /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
840    /// command is checked before the gate because the e2e rebuilds the crate.
841    pub fn cache_dir(&self) -> Option<PathBuf> {
842        self.e2e
843            .iter()
844            .chain(self.gate.iter())
845            .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
846    }
847
848    /// Every `--manifest-path` the e2e and gate commands pass to cargo, for the
849    /// shared cache's freshness check in repositories with no root manifest.
850    pub fn cargo_manifests(&self) -> Vec<PathBuf> {
851        let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
852        crate::cache::extract_manifest_paths(&all)
853    }
854}
855
856/// Per-repository worktree preparation, run right after magi creates a worktree.
857#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
858#[serde(deny_unknown_fields, default)]
859pub struct Worktree {
860    /// Ordered steps. Declare in one layer only. Empty (the default) changes
861    /// nothing. See [`crate::worktree_setup`].
862    pub setup: Vec<SetupStep>,
863    /// Ordered, repeatable commands before owned destructive worktree cleaning.
864    pub pre_clean: Vec<PreCleanStep>,
865}
866
867/// A required shell command; unknown keys and missing commands are errors.
868#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
869#[serde(deny_unknown_fields)]
870pub struct PreCleanStep {
871    /// Shell command executed in the target worktree after reset.
872    pub run: String,
873    /// Defaults to the verification timeout.
874    pub timeout_secs: Option<u64>,
875}
876
877/// One setup step: exactly one of `copy` / `run`.
878#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
879#[serde(deny_unknown_fields, default)]
880pub struct SetupStep {
881    /// `"src -> dst"` (or just `"path"`): copy from the primary checkout (an
882    /// absolute source is allowed) into the worktree. Never overwrites.
883    pub copy: Option<String>,
884    /// With `copy`: a missing source is skipped instead of an error.
885    pub optional: bool,
886    /// Shell command, run with the worktree as cwd.
887    pub run: Option<String>,
888    /// With `run`: seconds before the command is killed. Defaults to
889    /// `graph.verify_timeout()`.
890    pub timeout_secs: Option<u64>,
891}
892
893impl Worktree {
894    /// Refuse a malformed step at load time rather than in the middle of a run.
895    pub fn validate(&self) -> Result<()> {
896        for (i, step) in self.pre_clean.iter().enumerate() {
897            if step.run.trim().is_empty() || step.timeout_secs == Some(0) {
898                bail!(
899                    "[worktree] pre_clean step {} requires a nonempty run and positive timeout",
900                    i + 1
901                );
902            }
903        }
904        for (i, step) in self.setup.iter().enumerate() {
905            let n = i + 1;
906            match (&step.copy, &step.run) {
907                (Some(c), None) => {
908                    if step.timeout_secs.is_some() {
909                        bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
910                    }
911                    crate::worktree_setup::validate_copy(c)
912                        .with_context(|| format!("[worktree] setup step {n}"))?;
913                }
914                (None, Some(r)) => {
915                    if r.trim().is_empty() {
916                        bail!("[worktree] setup step {n}: `run` is empty");
917                    }
918                    if step.optional {
919                        bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
920                    }
921                }
922                _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
923            }
924        }
925        Ok(())
926    }
927}
928
929/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
930///
931/// The numbers below come from one incident, not from theory: a machine with
932/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
933/// Three multi-gigabyte classes of junk accumulated side by side - per-run
934/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
935/// each verify round and each implementation wave recompiles the derived
936/// section of the project into, and the outputs of runs that were removed but
937/// whose folders nobody deleted.
938#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
939#[serde(deny_unknown_fields, default)]
940pub struct Disk {
941    /// Free space, in bytes, below which no new run may start: the daemon and
942    /// the `magi run` gate answer with "the disk is full" instead of letting
943    /// the graph fill it the rest of the way. `0` turns the gate off.
944    ///
945    /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
946    /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
947    /// competition triggers and small enough that a 1 TB disk with 100 GB free
948    /// is nowhere near the threshold.
949    pub min_free_bytes: u64,
950    /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
951    /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
952    /// worktrees removed. `0` turns the janitor off.
953    ///
954    /// Default true.
955    pub auto_fold: bool,
956    /// How old a finished run must be before the janitor folds it, seconds.
957    ///
958    /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
959    /// run that `Ready` a week ago is worktrees holding a compile each. Six
960    /// hours is long enough that nobody loses an answer in the gap between
961    /// reading the report and starting from it, and short enough that a backlog
962    /// cannot pile up across two nights.
963    pub fold_grace_secs: u64,
964    /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
965    /// verify commands), in bytes. When the janitor runs and the cache is over
966    /// it, files are dropped oldest-first until it is not. `0` turns pruning
967    /// off - the cache then only ever grows, which is the operator's call.
968    ///
969    /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
970    /// shared cache on top of ~16 GB in the primary target directory and 6.7-
971    /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
972    /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
973    /// pruning only costs the rebuild of the dropped files, not of the world)
974    /// without letting one addled cache swallow the machine.
975    pub cache_limit_bytes: u64,
976    /// Aggregate retained worktree Cargo output cap; 0 disables reclamation.
977    pub worktree_limit_bytes: u64,
978    /// Declared artifact byte budget per pass; 0 disables reclamation.
979    /// The first deletion target may exceed a positive budget to ensure progress,
980    /// increasing deletion volume and pass duration; no later target may exceed it.
981    pub worktree_reclaim_bytes: u64,
982    /// Maximum unretired attempts of one task before another run may be
983    /// created. Resumes do not create worktrees and remain allowed. Automatic
984    /// releases and upstream changes never reset this bound; 0 disables it.
985    pub retained_attempt_limit: usize,
986}
987
988impl Default for Disk {
989    fn default() -> Self {
990        Self {
991            min_free_bytes: 8 * 1024 * 1024 * 1024,
992            auto_fold: true,
993            fold_grace_secs: 6 * 60 * 60,
994            cache_limit_bytes: 10 * 1024 * 1024 * 1024,
995            worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
996            worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
997            retained_attempt_limit: 8,
998        }
999    }
1000}
1001
1002/// What to do with the winning branch.
1003#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1004#[serde(rename_all = "lowercase")]
1005pub enum MergeMode {
1006    /// Leave the branch alone and print the merge command matching
1007    /// [`Merge::style`].
1008    None,
1009    /// Merge into the base branch in the primary worktree, using
1010    /// [`Merge::style`].
1011    Local,
1012    /// Push the branch and open a PR with `gh pr create`. Landing this PR
1013    /// (`[graph] land`) always squashes — see `land`'s module doc — so
1014    /// [`Merge::style`] does not apply here.
1015    Pr,
1016}
1017
1018/// How the winning branch is attached to the base branch: what
1019/// `mode = "local"` runs, and what `mode = "none"`'s printed guidance tells
1020/// the operator to run by hand.
1021///
1022/// Read from configuration rather than asked of the repository at run time
1023/// (e.g. `gh api repos/{owner}/{repo}/rulesets`) for two reasons: it keeps
1024/// `mode = "none"`'s guidance a pure function of `RunState`, assertable in a
1025/// unit test the same way `land::decide` is kept pure (see that module's
1026/// doc), and it works for a base branch that is not hosted on GitHub, or not
1027/// reachable at all, at the moment the report is rendered. An operator whose
1028/// base branch enforces a ruleset already knows what it allows; declaring it
1029/// once here is cheaper than magi re-discovering it, with a network call, on
1030/// every render.
1031#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
1032#[serde(rename_all = "lowercase")]
1033pub enum MergeStyle {
1034    /// `git merge --no-ff`: every candidate commit lands, plus a merge
1035    /// commit that records the merge as its own event in history. Rejected
1036    /// by a base branch whose ruleset requires linear history or forbids
1037    /// merge commits outright.
1038    #[default]
1039    Merge,
1040    /// `git merge --squash` followed by a commit under an explicit message:
1041    /// every candidate commit folds into one, and none of the candidate's
1042    /// own placeholder subjects (`magi: candidate A (uncommitted work)`)
1043    /// reach the base branch. No merge commit, so this satisfies a linear-
1044    /// history ruleset.
1045    Squash,
1046    /// A fast-forward-only merge: every candidate commit lands verbatim, in
1047    /// order, with no merge commit. Only succeeds because the winner was
1048    /// already rebased onto the tracked base tip before this runs (see
1049    /// `Runner::sync_to_base`) — equivalent to GitHub's "rebase and merge"
1050    /// once that has happened.
1051    Rebase,
1052}
1053
1054/// Whether pull request landing requires readable CI results.
1055#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1056#[serde(rename_all = "lowercase")]
1057pub enum MergeCi {
1058    /// Wait for readable check results before landing (the default).
1059    #[default]
1060    Expected,
1061    /// Ignore the rollup; repository verification and approval still apply.
1062    None,
1063}
1064
1065impl MergeCi {
1066    /// Translate configuration into the landing decision policy.
1067    pub fn expectation(self) -> crate::land::CiExpectation {
1068        match self {
1069            Self::Expected => crate::land::CiExpectation::Expected,
1070            Self::None => crate::land::CiExpectation::Absent,
1071        }
1072    }
1073}
1074
1075/// Merge policy.
1076#[derive(Debug, Clone, Deserialize, Serialize)]
1077#[serde(deny_unknown_fields, default)]
1078pub struct Merge {
1079    /// Default is [`MergeMode::None`]: magi never touches your base branch
1080    /// unless you ask it to.
1081    pub mode: MergeMode,
1082    /// CI expectation for landing. Opt out only in repositories without CI.
1083    pub ci: MergeCi,
1084    /// Base branch. Defaults to the branch checked out when the run started.
1085    pub base: Option<String>,
1086    /// How the winner is attached to `base`; see [`MergeStyle`]. Ignored by
1087    /// `mode = "pr"`.
1088    pub style: MergeStyle,
1089    /// Remote for `mode = "pr"`.
1090    pub remote: String,
1091    /// After a `mode = "pr"` run lands, open a `chore/release-vX.Y.Z` pull
1092    /// request sized to the change by an agent's own judgement, so a version
1093    /// bump does not depend on a human remembering to cut one.
1094    ///
1095    /// Only acts on Rust repositories (a `Cargo.toml` at the root of the base
1096    /// branch); on any other repository it is a no-op that records one event.
1097    ///
1098    /// On by default. **Turning this off means a merge landed from the phone
1099    /// never becomes a release**, so `POST /api/upgrade` keeps reporting
1100    /// "already on the newest release" against a `main` that has moved past
1101    /// it - the same gap this feature exists to close. Only for a repository
1102    /// that wants to keep cutting releases by hand.
1103    pub release_bump: bool,
1104}
1105
1106impl Default for Merge {
1107    fn default() -> Self {
1108        Self {
1109            mode: MergeMode::None,
1110            ci: MergeCi::Expected,
1111            base: None,
1112            style: MergeStyle::default(),
1113            remote: "origin".to_owned(),
1114            release_bump: true,
1115        }
1116    }
1117}
1118
1119/// How magi keeps itself current.
1120#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1121#[serde(rename_all = "lowercase")]
1122pub enum UpdateMode {
1123    /// Never check.
1124    Off,
1125    /// Check in the background and print a one-line banner when a newer
1126    /// release exists.
1127    Notify,
1128    /// Check and install silently.
1129    Install,
1130}
1131
1132/// Self-update policy.
1133#[derive(Debug, Clone, Deserialize, Serialize)]
1134#[serde(deny_unknown_fields, default)]
1135pub struct Update {
1136    /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
1137    pub mode: UpdateMode,
1138    /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
1139    pub interval: Option<String>,
1140    /// Opt in to automatic update and restart in `magi web`.
1141    pub auto_restart: bool,
1142}
1143
1144impl Default for Update {
1145    fn default() -> Self {
1146        Self {
1147            mode: UpdateMode::Notify,
1148            interval: None,
1149            auto_restart: false,
1150        }
1151    }
1152}
1153
1154/// Who performs the release after a `chore/release-vX.Y.Z` pull request merges.
1155#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1156#[serde(rename_all = "lowercase")]
1157pub enum ReleaseMode {
1158    /// The repository's own workflows do (`auto-tag.yml` then `release.yml`),
1159    /// and the release pull request merges on its checks.
1160    #[default]
1161    Actions,
1162    /// magi does, from this machine: no CI is awaited, the owner approves the
1163    /// merge, and magi then tags and runs [`Release::commands`]. See
1164    /// [`crate::release_local`]. For ordinary pull requests without CI, also set
1165    /// `[merge] ci = "none"` in the repository config.
1166    Local,
1167}
1168
1169/// `[release]`: releasing without GitHub Actions. Opt-in per repository.
1170#[derive(Debug, Clone, Deserialize, Serialize)]
1171#[serde(deny_unknown_fields, default)]
1172pub struct Release {
1173    /// [`ReleaseMode::Actions`] (default: nothing changes) or
1174    /// [`ReleaseMode::Local`].
1175    pub mode: ReleaseMode,
1176    /// Shell commands run in order, from a clean checkout of the merge commit,
1177    /// once the tag is pushed. The first failure stops the list. They see
1178    /// `MAGI_RELEASE_VERSION`, `MAGI_RELEASE_TAG`, `MAGI_RELEASE_COMMIT` and
1179    /// `MAGI_RELEASE_PR` in the environment; `{{ ... }}` cannot carry the
1180    /// version because teravars renders the whole file before any release
1181    /// exists. Only read when `mode = "local"`.
1182    pub commands: Vec<String>,
1183    /// Minutes each command may run before it is killed and counted as failed.
1184    pub timeout_minutes: u64,
1185    /// Files whose version a release bump rewrites, for repositories whose
1186    /// manifest is not a root `Cargo.toml` (a Tauri app keeps it under
1187    /// `src-tauri/`, with the app version repeated in `package.json` and
1188    /// `tauri.conf.json`). Empty (default) means the root `Cargo.toml` and
1189    /// nothing else. The first entry is the version of record - the file the
1190    /// repository's own `auto-tag.yml` reads - and must be `kind = "cargo"`.
1191    /// Never detected: see [`crate::release_manifest`].
1192    pub version_files: Vec<VersionFile>,
1193}
1194
1195/// How a [`VersionFile`] is read and rewritten.
1196#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1197#[serde(rename_all = "lowercase")]
1198pub enum VersionKind {
1199    /// A `Cargo.toml` (`[package]` or `[workspace.package]` `version`).
1200    Cargo,
1201    /// A JSON file with a top-level `"version"` string.
1202    Json,
1203}
1204
1205/// One entry of [`Release::version_files`].
1206#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1207#[serde(deny_unknown_fields)]
1208pub struct VersionFile {
1209    /// Path relative to the repository root, `/`-separated.
1210    pub path: String,
1211    /// How to read and rewrite it.
1212    pub kind: VersionKind,
1213}
1214
1215impl Default for Release {
1216    fn default() -> Self {
1217        Self {
1218            mode: ReleaseMode::Actions,
1219            commands: Vec::new(),
1220            timeout_minutes: 30,
1221            version_files: Vec::new(),
1222        }
1223    }
1224}
1225
1226impl Release {
1227    /// Refuse a malformed `version_files` at load time.
1228    pub fn validate(&self) -> Result<()> {
1229        crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1230    }
1231
1232    /// Is this repository released by magi rather than by its workflows?
1233    pub fn is_local(&self) -> bool {
1234        self.mode == ReleaseMode::Local
1235    }
1236}
1237
1238/// Optional contract with an external repository updater.
1239#[derive(Debug, Clone, Deserialize, Serialize)]
1240#[serde(try_from = "CoordinationFields")]
1241pub struct Coordination {
1242    /// Contract file name inside the Git common directory.
1243    pub contract_file: String,
1244    /// Accepted trimmed contract contents.
1245    pub contract_token: String,
1246    /// Shared OS lock file name inside the Git common directory.
1247    pub lock_file: String,
1248}
1249
1250#[derive(Deserialize, Default)]
1251#[serde(deny_unknown_fields, default)]
1252struct CoordinationFields {
1253    contract_file: String,
1254    contract_token: String,
1255    lock_file: String,
1256}
1257
1258impl TryFrom<CoordinationFields> for Coordination {
1259    type Error = anyhow::Error;
1260
1261    fn try_from(fields: CoordinationFields) -> Result<Self> {
1262        for (key, name) in [
1263            ("coordination.contract_file", &fields.contract_file),
1264            ("coordination.lock_file", &fields.lock_file),
1265        ] {
1266            if name.trim().is_empty()
1267                || name != name.trim()
1268                || name == "."
1269                || name.contains("..")
1270                || name.contains(['/', '\\', ':', '\0'])
1271            {
1272                bail!(
1273                    "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1274                );
1275            }
1276        }
1277        let token = &fields.contract_token;
1278        if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1279            bail!(
1280                "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1281            );
1282        }
1283        Ok(Self {
1284            contract_file: fields.contract_file,
1285            contract_token: fields.contract_token,
1286            lock_file: fields.lock_file,
1287        })
1288    }
1289}
1290
1291#[cfg(test)]
1292pub(crate) fn test_coordination() -> Option<Coordination> {
1293    Some(Coordination {
1294        contract_file: "updater.contract".into(),
1295        contract_token: "test-protocol-v1".into(),
1296        lock_file: "updater.lock".into(),
1297    })
1298}
1299
1300/// Top-level configuration.
1301#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1302#[serde(deny_unknown_fields, default)]
1303pub struct Config {
1304    /// External repository coordination; absent means disabled.
1305    pub coordination: Option<Coordination>,
1306    /// Agent roster.
1307    pub agents: Vec<AgentSpec>,
1308    /// Role assignment.
1309    pub roles: Roles,
1310    /// Graph shape.
1311    pub graph: Graph,
1312    /// Blindness policy.
1313    pub blind: Blind,
1314    /// Verification commands.
1315    pub verify: Verify,
1316    /// Worktree preparation.
1317    pub worktree: Worktree,
1318    /// Disk hygiene.
1319    pub disk: Disk,
1320    /// Merge policy.
1321    pub merge: Merge,
1322    /// Self-update policy.
1323    pub update: Update,
1324    /// Project-specific text appended to the node prompts.
1325    pub prompts: Prompts,
1326    /// How the operator is told a run is waiting on them.
1327    pub notify: Notify,
1328    /// Local repositories the plan surface can start or derive a conversation
1329    /// against.
1330    pub repos: Repos,
1331    /// Policy for the standing conversation ([`crate::talk`]).
1332    pub talk: Talk,
1333    /// How many runs `magi serve`'s own loop drives at once.
1334    pub daemon: Daemon,
1335    /// Who tags and publishes after a release pull request merges.
1336    pub release: Release,
1337    /// Context-window sizes in tokens, keyed by model name, merged over
1338    /// [`BUILTIN_CONTEXT_WINDOWS`]. See [`Config::context_window`].
1339    pub context_windows: BTreeMap<String, u64>,
1340}
1341
1342/// Context windows of models magi commonly drives, in tokens.
1343///
1344/// A convenience, not a source of truth: vendors resize windows and ship new
1345/// models faster than this table is edited, so an entry that is stale or
1346/// missing is fixed by `[context_windows]` in `magi.toml`, which wins. Matched
1347/// by [`Config::context_window`]: exact name first, then the longest key that
1348/// prefixes the model name (so a dated or suffixed id such as
1349/// `claude-sonnet-4-5-20250929` finds `claude-sonnet-4-5`). A model matching
1350/// nothing has no percentage - the UI shows the raw count.
1351const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1352    ("claude-opus-4", 200_000),
1353    ("claude-sonnet-4", 200_000),
1354    ("claude-haiku-4", 200_000),
1355    ("claude-3", 200_000),
1356    ("opus", 200_000),
1357    ("sonnet", 200_000),
1358    ("haiku", 200_000),
1359    ("gpt-5", 400_000),
1360    ("gpt-4.1", 1_000_000),
1361    ("gpt-4o", 128_000),
1362    ("o3", 200_000),
1363    ("o4-mini", 200_000),
1364    ("gemini-2.5", 1_000_000),
1365    ("deepseek", 128_000),
1366];
1367
1368impl Config {
1369    /// Context window in tokens for `model`: `[context_windows]` first, then
1370    /// the built-in table; within each, an exact name beats the longest
1371    /// prefix. `None` for an unknown model, which is a deliberate answer -
1372    /// guessing a denominator would print a confident wrong percentage.
1373    pub fn context_window(&self, model: &str) -> Option<u64> {
1374        fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1375            let mut best: Option<(usize, u64)> = None;
1376            for (key, window) in entries {
1377                if key == model {
1378                    return Some(window);
1379                }
1380                if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1381                    best = Some((key.len(), window));
1382                }
1383            }
1384            best.map(|(_, w)| w)
1385        }
1386        lookup(
1387            model,
1388            self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1389        )
1390        .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1391    }
1392}
1393
1394/// How the daemon loop itself behaves, as opposed to what one run does.
1395///
1396/// Machine-layer material in the same sense [`Repos::roots`] is: how many
1397/// competitions this machine's own loop is willing to babysit at once is a
1398/// fact about the machine running `magi serve`, not about any one
1399/// repository's task, so it belongs in `<config_dir>/magi/config.toml`
1400/// rather than a repository's own `magi.toml` - though, like `Repos::roots`,
1401/// nothing stops a repository from setting it too, since a scalar field
1402/// takes whichever layer has the highest precedence.
1403#[derive(Debug, Clone, Deserialize, Serialize)]
1404#[serde(deny_unknown_fields, default)]
1405pub struct Daemon {
1406    /// How many runs `magi serve` may have actively in flight at once.
1407    /// **One by default** - today's behaviour, one run at a time.
1408    ///
1409    /// This is a different knob from [`Graph::max_parallel`], and the two
1410    /// must not be confused: `max_parallel` bounds how many agent *processes*
1411    /// one run starts inside itself (implementers, judges, reviewers -
1412    /// candidates competing on a single task); this field bounds how many
1413    /// *runs* - whole competitions, each with its own `max_parallel` budget -
1414    /// the loop drives side by side, possibly across different tasks and
1415    /// different repositories. Raising `max_parallel` buys a bigger panel for
1416    /// one task; raising this buys more tasks worked at once. A config file
1417    /// that meant one and wrote the other would either starve a competition
1418    /// of judges or leave the rest of the backlog waiting for no reason.
1419    ///
1420    /// A run parked waiting on the operator's land-merge approval - see
1421    /// [`crate::land`] - does not hold one of these slots while it waits: the
1422    /// whole point of parking there is to let the loop spend the slot on
1423    /// something runnable instead of sitting on a decision only a human can
1424    /// make. So even at the default of `1`, an approval that comes back does
1425    /// not queue behind whatever else the loop happens to be running.
1426    pub max_concurrent_runs: usize,
1427    /// Let a task marked [`crate::queue::Task::interrupt`] (`magi task
1428    /// interrupt`) cut ahead of whatever `magi serve` already has in flight,
1429    /// instead of waiting for it to finish.
1430    ///
1431    /// **Off by default.** When enabled, a run that is in flight and is not
1432    /// itself the interrupt candidate may be paused at its next safe node
1433    /// boundary - see [`crate::graph::Runner::park_here`] - so the marked
1434    /// task can run alone; the paused run resumes automatically, through the
1435    /// same path any other parked run does, the moment the interrupting
1436    /// task's own run reaches a terminal status. This is opt-in because it
1437    /// bends the loop's own "one run at a time" principle (see this repository's
1438    /// `magi serve` help) for a specific, explicit operator request, and a
1439    /// repository that never files an interrupt task pays nothing for having
1440    /// it on - but an operator who does not want any run of theirs preempted,
1441    /// ever, should leave this `false`.
1442    pub pause_for_interrupts: bool,
1443    /// How many deputies `magi serve` runs at once. A deputy is the short-lived
1444    /// seat that waits on one open conductor question (see [`crate::deputy`]);
1445    /// each is a live agent conversation, so this is bounded - **two by
1446    /// default**, because the agent CLIs' quota is the scarce resource. A
1447    /// question over the limit keeps its place and starts when a deputy
1448    /// finishes; `0` runs none.
1449    pub max_deputies: usize,
1450    /// Minutes a release-bump pull request may make no progress before
1451    /// `magi serve` raises a notice and asks the owner (see
1452    /// [`crate::release_watch`]). Progress is a change of head commit or of any
1453    /// check's verdict. A required check that stays red after the one rerun the
1454    /// watcher is allowed escalates at once, whatever this says. **Sixty by
1455    /// default**; `0` turns the watcher off.
1456    pub release_stall_minutes: u64,
1457}
1458
1459impl Default for Daemon {
1460    fn default() -> Self {
1461        Self {
1462            max_concurrent_runs: 1,
1463            pause_for_interrupts: false,
1464            max_deputies: 2,
1465            release_stall_minutes: 60,
1466        }
1467    }
1468}
1469
1470/// Where `magi repos` and `GET /api/repos` look for local checkouts.
1471///
1472/// `roots` is one of the array keys [`array_merge_policy`] marks as
1473/// append-across-layers: which checkouts exist in general is a *machine*
1474/// fact in the same way the agent roster is - a repository's own `magi.toml`
1475/// cannot state where its siblings live before magi has resolved which
1476/// repository to read that file from in the first place - but a repository
1477/// that genuinely has an extra root worth scanning is not forced to choose
1478/// between an error and losing the machine's roots outright. Both layers'
1479/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
1480/// are still refused.
1481#[derive(Debug, Clone, Deserialize, Serialize)]
1482#[serde(deny_unknown_fields, default)]
1483pub struct Repos {
1484    /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
1485    /// with a `.git` directory. Empty by default - nothing is scanned unless
1486    /// asked to be.
1487    pub roots: Vec<PathBuf>,
1488    /// Allow explicit owner/repo misses to be confirmed with gh and cloned.
1489    pub auto_clone: bool,
1490    /// Literal argv template; {repo}, {owner}, {name}, {dest} are substituted.
1491    /// Defaults to `gh repo clone https://github.com/{repo}.git {dest}`.
1492    /// Declare in a single layer.
1493    pub clone_command: Option<Vec<String>>,
1494    /// How long a scan is trusted before the next request re-scans it,
1495    /// seconds. `0` means never trust it: scan on every request. Defaults to
1496    /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
1497    /// the same reason - a checkout does not usually appear or vanish inside
1498    /// a session, so there is little to gain from scanning more often than
1499    /// that, and an explicit refresh exists for the moment one does.
1500    pub scan_ttl: u64,
1501    /// How often `magi serve` runs `git fetch origin` in every checkout under
1502    /// `roots`, seconds, so `origin/main` stays fresh whatever state the
1503    /// working tree is in. Fetch only: no branch, HEAD or working tree is
1504    /// touched. `0` disables it.
1505    pub fetch_interval: u64,
1506}
1507
1508impl Default for Repos {
1509    fn default() -> Self {
1510        Self {
1511            roots: Vec::new(),
1512            auto_clone: false,
1513            clone_command: None,
1514            scan_ttl: 86_400,
1515            fetch_interval: 600,
1516        }
1517    }
1518}
1519
1520/// Project-specific text appended to each node's prompt.
1521///
1522/// **Additive by construction.** These fields cannot replace magi's prompts,
1523/// only extend them, and that restriction is the whole design. The built-in
1524/// prompts carry the invariants the competition rests on: a judging prompt
1525/// names no authors, every structured answer must arrive as one fenced `json`
1526/// block, and a judge is told not to speculate about who wrote what. A config
1527/// that could overwrite them would let a typo silently un-blind the panel or
1528/// break the parser, and the symptom would be "the judges got worse" rather
1529/// than an error.
1530///
1531/// Repository-wide context belongs in `AGENTS.md`, which every agent already
1532/// reads from the checkout. Use these fields for the things a *magi node*
1533/// needs to know and a repository file cannot say - for instance that
1534/// reviewers here should ignore formatting because a hook owns it.
1535#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1536#[serde(deny_unknown_fields, default)]
1537pub struct Prompts {
1538    /// Appended to every node's prompt.
1539    pub all: String,
1540    /// Appended for implementers.
1541    pub implement: String,
1542    /// Appended for judges, both ranking and voting.
1543    pub judge: String,
1544    /// Appended for reviewers.
1545    pub review: String,
1546    /// Appended for the fixer.
1547    pub fix: String,
1548}
1549
1550impl Prompts {
1551    /// The overlay for one node, or `None` when nothing is configured.
1552    ///
1553    /// `node` is the graph's own node name, so a new node gets no overlay
1554    /// rather than the wrong one.
1555    pub fn overlay(&self, node: &str) -> Option<String> {
1556        let specific = match node {
1557            "implement" => &self.implement,
1558            "judge" | "vote" | "deliberate" => &self.judge,
1559            "review" => &self.review,
1560            "fix" => &self.fix,
1561            _ => "",
1562        };
1563        let mut parts: Vec<&str> = Vec::new();
1564        for p in [self.all.trim(), specific.trim()] {
1565            if !p.is_empty() {
1566                parts.push(p);
1567            }
1568        }
1569        if parts.is_empty() {
1570            return None;
1571        }
1572        Some(parts.join("\n\n"))
1573    }
1574}
1575
1576/// How the operator is told that a run is waiting on them.
1577///
1578/// A command rather than a built-in integration: magi is one binary with no
1579/// network dependencies, and every operator's notification path is different -
1580/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
1581/// Shelling out keeps all of them possible and none of them magi's problem.
1582#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1583#[serde(deny_unknown_fields, default)]
1584pub struct Notify {
1585    /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
1586    /// Empty means no notification - the web UI is then the only surface.
1587    pub command: Vec<String>,
1588}
1589
1590/// Policy for [`crate::talk`], the standing conversation.
1591#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1592#[serde(deny_unknown_fields, default)]
1593pub struct Talk {
1594    /// Let the conversation's agent edit files in the repository instead of
1595    /// filing a task for one. **Off by default** - see
1596    /// [`crate::talk`]'s module doc for why an edit made mid-conversation is
1597    /// an edit no run and no review can be attributed to, which is exactly
1598    /// the property a repository entered in a competition depends on. A
1599    /// repository that is never judged - dotfiles, a personal config
1600    /// checkout - has nothing to lose by turning this on in its own
1601    /// `magi.toml`, and a one-line fix stops costing a queued task to get.
1602    pub allow_write: bool,
1603    /// Allow bounded recovery on automatic chat turns; only the machine layer can set it.
1604    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1605    pub standing_authorization: bool,
1606    /// Extra chat personas, `[[talk.personas]]`. They add to the built-ins in
1607    /// [`crate::persona`]; an entry with a built-in's id replaces it. Like every
1608    /// array outside [`array_merge_policy`]'s append list, declaring it in two
1609    /// layers is refused.
1610    pub personas: Vec<PersonaSpec>,
1611    /// What the chat calls the operator: the persona addresses them by this
1612    /// name and the web Chat labels their turns with it instead of `YOU`.
1613    /// Blank is unset; at most [`OPERATOR_NAME_MAX`] characters, one line.
1614    pub operator_name: Option<String>,
1615}
1616
1617/// Longest accepted `[talk] operator_name`, in characters.
1618pub const OPERATOR_NAME_MAX: usize = 64;
1619
1620impl Talk {
1621    /// The trimmed operator name, `None` when unset or blank.
1622    pub fn operator_name(&self) -> Option<&str> {
1623        self.operator_name
1624            .as_deref()
1625            .map(str::trim)
1626            .filter(|n| !n.is_empty())
1627    }
1628}
1629
1630/// One `[[talk.personas]]` entry: a tone for the standing chat, nothing more.
1631#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1632#[serde(deny_unknown_fields)]
1633pub struct PersonaSpec {
1634    /// Stable id the conversation stores. Not `default`.
1635    pub id: String,
1636    /// What the selector shows. May be omitted when `id` is a built-in's: the
1637    /// built-in's name is kept.
1638    #[serde(default)]
1639    pub name: String,
1640    /// The voice instruction appended to the chat's system prompt. May be
1641    /// omitted when `id` is a built-in's.
1642    #[serde(default)]
1643    pub prompt: String,
1644    /// Optional avatar, display only: a `data:image/(png|jpeg|gif|webp);base64,`
1645    /// URI or an absolute (or `~/`) path to a raster image. See
1646    /// [`crate::persona_icon`]. Never part of the briefing.
1647    #[serde(default, skip_serializing_if = "Option::is_none")]
1648    pub icon: Option<String>,
1649}
1650
1651/// Roles resolved to concrete agent specs for one run.
1652#[derive(Debug, Clone)]
1653pub struct ResolvedRoles {
1654    /// One per candidate.
1655    pub implementers: Vec<AgentSpec>,
1656    /// One per judge.
1657    pub judges: Vec<AgentSpec>,
1658    /// One per reviewer slot.
1659    pub reviewers: Vec<AgentSpec>,
1660    /// The configured fixer chain in order, if `[roles] fixer` is set
1661    /// (resolved like [`crate::agent::pick_chain`]: unknown or uninstalled ids
1662    /// skipped, duplicates keep their first place). `None` means the winner's
1663    /// own author.
1664    pub fixer: Option<Vec<AgentSpec>>,
1665    /// Queue conductor, explicitly selected or resolved by the standalone-seat fallback.
1666    pub conductor: AgentSpec,
1667    /// The full ordered implementer roster, in [`Roles::implementers`]'s own
1668    /// order — or `[[agents]]` in file order, when that list is empty. Unlike
1669    /// [`Self::implementers`], never truncated to `graph.implementers` and
1670    /// never `rotate`d/wrapped: a solo run (`implementers = 1`) resolves
1671    /// `implementers` down to a single slot, but `graph::Runner`'s per-seat
1672    /// quota fallback needs the *whole* list to walk forward through when
1673    /// that one slot's agent runs out of quota mid-run.
1674    pub implementer_roster: Vec<AgentSpec>,
1675    /// [`Self::implementer_roster`]'s counterpart for judge seats: the whole
1676    /// `[roles] judges` list (or every agent), untruncated and unrotated, for
1677    /// the per-seat handover when a judge's agent fails.
1678    pub judge_roster: Vec<AgentSpec>,
1679    /// Likewise for reviewer seats.
1680    pub reviewer_roster: Vec<AgentSpec>,
1681}
1682
1683/// Every array-valued key in a config table, as a dotted path.
1684///
1685/// Dotted so the error names `roles.implementers` rather than `implementers`:
1686/// an operator with three config files needs to know which key, not just that
1687/// there was one. `vars` is skipped because it is teravars' own input, merged
1688/// on purpose and never deserialised into `Config`.
1689fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1690    let mut out = Vec::new();
1691    for (k, v) in table {
1692        if prefix.is_empty() && k == "vars" {
1693            continue;
1694        }
1695        let path = if prefix.is_empty() {
1696            k.clone()
1697        } else {
1698            format!("{prefix}.{k}")
1699        };
1700        match v {
1701            toml::Value::Array(_) => out.push(path),
1702            toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1703            _ => {}
1704        }
1705    }
1706    out
1707}
1708
1709/// How an array key behaves when two config layers both declare it.
1710#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1711enum ArrayMerge {
1712    /// Two layers may both declare it; the composed value is the
1713    /// low-to-high-priority concatenation teravars already produces (see
1714    /// [`Config::load_layers`]'s doc for why that order and no dedup).
1715    Append,
1716    /// Two layers declaring it is refused; see
1717    /// [`Config::refuse_split_arrays`].
1718    Replace,
1719}
1720
1721/// The single place that decides, for a dotted array key (as returned by
1722/// [`array_keys`]), whether declaring it in two config layers is a
1723/// concatenation the operator asked for or a silent accident.
1724///
1725/// Kept as one match so the whole policy is visible in one place - the same
1726/// reason `claude_quota` and `dropped_stream` close their own classification
1727/// in one spot elsewhere in this codebase. Anything not listed defaults to
1728/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
1729/// reasoned about yet, and a new array key added later has to be added here
1730/// deliberately to become appendable.
1731///
1732/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
1733///   gate. Concatenating two of them is exactly the checks both layers
1734///   wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
1735///   live in a shared layer while a repository's own layer adds its own
1736///   command, instead of every repository copying the shared command into
1737///   its own file.
1738/// - `repos.roots` — a set of directories to scan for checkouts. A
1739///   repository adding its own root on top of the machine's is additive by
1740///   nature, not a replacement of where the machine looks; see
1741///   [`Repos::roots`].
1742///
1743/// Left on the refuse side, and why:
1744/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
1745///   list of *seats*, not a set. A machine's two implementers plus a
1746///   repository's one is three seats nobody asked for and nobody is paying
1747///   for on purpose.
1748/// - `notify.command` — an argv. Concatenating two argvs does not produce a
1749///   program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
1750/// - `blind.strip_lines` — technically safe to concatenate (each entry is
1751///   matched as an independent substring, so a longer list only strips
1752///   *more*), but left on the refuse side anyway: the same list also drives
1753///   `commit_msg_hook`'s generated `sed` addresses, where position matters,
1754///   and a silent three-layer merge is exactly the kind of surprise
1755///   `refuse_split_arrays` exists to catch rather than to reason about
1756///   case-by-case. A repository that wants one more stripped phrase restates
1757///   the whole list; that restatement is visible in review, an accidental
1758///   concatenation would not be.
1759fn array_merge_policy(key: &str) -> ArrayMerge {
1760    match key {
1761        "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1762        _ => ArrayMerge::Replace,
1763    }
1764}
1765
1766impl Config {
1767    /// Load one file through teravars: Tera rendering, `[vars]` resolution,
1768    /// and the `include = [...]` directive.
1769    pub fn load(path: &Path) -> Result<Self> {
1770        Self::load_layers(&[path.to_path_buf()])
1771    }
1772
1773    /// The Tera render context shared by every layer: `system.*` (from
1774    /// teravars), `env` (magi's own addition - a config that names a shared
1775    /// build-cache directory or a machine-specific path needs
1776    /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
1777    /// derived from the last (highest-priority) path's parent directory.
1778    ///
1779    /// Factored out so [`Config::array_provenance`] can re-render a single
1780    /// layer under the exact same context [`Config::load_layers`] uses for
1781    /// the joint render, rather than drifting from it by accident.
1782    fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1783        let mut ctx = teravars::system_context();
1784        let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1785        ctx.insert("env", &env);
1786        if let Some(last) = paths.last()
1787            && let Some(dir) = last.parent()
1788        {
1789            // A layer extracted from `<remote>/<base>` records the checkout it
1790            // stands for beside itself; its own directory is a cache path.
1791            let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1792                .map(|s| PathBuf::from(s.trim()))
1793                .unwrap_or_else(|_| dir.to_path_buf());
1794            ctx.insert("repo", &dir.to_string_lossy());
1795            ctx.insert(
1796                "repo_name",
1797                &dir.file_name().unwrap_or_default().to_string_lossy(),
1798            );
1799        }
1800        ctx
1801    }
1802
1803    /// Load and deep-merge a stack of config files, later files winning.
1804    ///
1805    /// This is why the config is TOML-through-teravars rather than plain serde:
1806    /// the roster is a *machine* fact (which CLIs and plans you pay for) while
1807    /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
1808    /// there). Picking one file and ignoring the other would force every repo
1809    /// to restate the roster.
1810    pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1811        Self::load_layers_with_machine(paths, Self::machine_layer())
1812    }
1813
1814    fn load_layers_with_machine(paths: &[PathBuf], machine: Option<PathBuf>) -> Result<Self> {
1815        let mut engine = teravars::Engine::default();
1816        let ctx = Self::render_ctx(paths);
1817        if paths.len() > 1 {
1818            Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1819                if error.downcast_ref::<ConfigFailure>().is_some() {
1820                    error
1821                } else {
1822                    // Keep the actionable refusal visible to plain Display
1823                    // callers while retaining the structured failure identity.
1824                    let message = error.to_string();
1825                    error
1826                        .context(ConfigFailure::layers("config-merge", paths))
1827                        .context(message)
1828                }
1829            })?;
1830        }
1831        let merged = teravars::load_merged(paths, &mut engine, &ctx)
1832            .map_err(|error| {
1833                let cause = ConfigFailure::render(&error, paths);
1834                anyhow::Error::new(error).context(cause)
1835            })
1836            .with_context(|| {
1837                format!(
1838                    "rendering config via teravars: {}",
1839                    paths
1840                        .iter()
1841                        .map(|p| p.display().to_string())
1842                        .collect::<Vec<_>>()
1843                        .join(", ")
1844                )
1845            })?;
1846        let mut table = merged.config;
1847        Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1848        // Repository templates and explicit execution config cannot supply or
1849        // override this authority, including through includes or rendered vars.
1850        let standing = table
1851            .get_mut("talk")
1852            .and_then(toml::Value::as_table_mut)
1853            .and_then(|talk| talk.remove("standing_authorization"));
1854        let standing = if standing.is_some()
1855            && let Some(machine) = machine.filter(|machine| paths.contains(machine))
1856        {
1857            let machine_paths = [machine];
1858            let mut engine = teravars::Engine::default();
1859            let layer = teravars::load_merged(
1860                &machine_paths,
1861                &mut engine,
1862                &Self::render_ctx(&machine_paths),
1863            )
1864            .context("read machine standing authorization")?;
1865            layer
1866                .config
1867                .get("talk")
1868                .and_then(|talk| talk.get("standing_authorization"))
1869                .map(|value| {
1870                    value.as_bool().context(
1871                        "[talk] standing_authorization in the machine layer must be a boolean",
1872                    )
1873                })
1874                .transpose()?
1875                .unwrap_or(false)
1876        } else {
1877            false
1878        };
1879        // `[vars]` is teravars' own input, already resolved into the render
1880        // context; `deny_unknown_fields` must not trip over it.
1881        table.remove("vars");
1882        // No layer says anything about `agents`: the roster is whatever is on
1883        // `PATH` now, exactly as when no layer exists at all. An explicit
1884        // `agents = []` is a statement and is kept.
1885        let detect_agents = !table.contains_key("agents");
1886        let mut cfg: Self = toml::Value::Table(table)
1887            .try_into()
1888            .context("deserializing magi config")
1889            .context(ConfigFailure::layers("config-deserialize", paths))?;
1890        cfg.talk.standing_authorization = standing;
1891        if !cfg.graph.question_routing {
1892            tracing::warn!(
1893                "[graph] question_routing is retired and ignored; task inquiries always use their chat"
1894            );
1895        }
1896        crate::persona::validate(&cfg.talk.personas)?;
1897        cfg.worktree.validate()?;
1898        cfg.release.validate()?;
1899        if let Some(name) = cfg.talk.operator_name() {
1900            if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1901                bail!(
1902                    "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1903                );
1904            }
1905        }
1906        if detect_agents {
1907            cfg.agents = Self::autodetected().agents;
1908        }
1909        Ok(cfg)
1910    }
1911
1912    /// `graph.candidates` was renamed `graph.implementers`. Both spellings are
1913    /// read, but the layers are merged into one table before serde sees it, so
1914    /// an old name in a lower layer and the new name in a higher one would
1915    /// arrive together and fail as a duplicate field instead of letting the
1916    /// higher layer win. Resolve it here: a single layer that writes both is
1917    /// refused (naming both keys and the file); otherwise the value from the
1918    /// last layer that wrote either key becomes `implementers`.
1919    fn normalize_renamed_keys(
1920        paths: &[PathBuf],
1921        engine: &mut teravars::Engine,
1922        ctx: &teravars::Context,
1923        table: &mut toml::map::Map<String, toml::Value>,
1924    ) -> Result<()> {
1925        let both = matches!(
1926            table.get("graph"),
1927            Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1928        );
1929        if !both {
1930            return Ok(());
1931        }
1932        let mut winner: Option<toml::Value> = None;
1933        for path in paths {
1934            let one = teravars::load_merged([path], engine, ctx)
1935                .map_err(|error| {
1936                    let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1937                    anyhow::Error::new(error).context(cause)
1938                })
1939                .with_context(|| format!("rendering {}", path.display()))?;
1940            let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1941                continue;
1942            };
1943            if g.contains_key("candidates") && g.contains_key("implementers") {
1944                bail!(
1945                    "`[graph]` sets both `implementers` and its deprecated alias \n                     `candidates` in {}; keep only `implementers`.",
1946                    path.display()
1947                );
1948            }
1949            if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1950                winner = Some(v.clone());
1951            }
1952        }
1953        if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1954            g.remove("candidates");
1955            if let Some(v) = winner {
1956                g.insert("implementers".to_owned(), v);
1957            }
1958        }
1959        Ok(())
1960    }
1961
1962    /// Refuse an array that two layers both declare, unless
1963    /// [`array_merge_policy`] says that key is meant to accumulate.
1964    ///
1965    /// teravars **appends** arrays when it merges layers, and that is wrong for
1966    /// most arrays magi has: `implementers` is an ordered list of seats,
1967    /// `notify.command` is an argv. Concatenating two of them yields something
1968    /// nobody wrote - three implementers out of a machine's two and a
1969    /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
1970    ///
1971    /// Replacing instead would be the right merge rule for those keys, but the
1972    /// rule lives in teravars, which several other projects depend on;
1973    /// changing it there is a decision for that crate, not something to fake
1974    /// here by re-reading the files with different semantics and hoping the
1975    /// two paths agree.
1976    ///
1977    /// So magi refuses the ambiguity rather than resolving it silently, for
1978    /// every array key except the short, deliberate list
1979    /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
1980    /// concatenation teravars already produces *is* what both files say, so
1981    /// there is nothing to refuse. The cost of guessing wrong on the refused
1982    /// keys is a roster the operator did not ask for and is paying for by the
1983    /// token; the append keys carry no such risk because every element runs
1984    /// (or every directory is scanned) regardless of order.
1985    fn refuse_split_arrays(
1986        paths: &[PathBuf],
1987        engine: &mut teravars::Engine,
1988        ctx: &teravars::Context,
1989    ) -> Result<()> {
1990        let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1991        for path in paths {
1992            let one = teravars::load_merged([path], engine, ctx)
1993                .map_err(|error| {
1994                    let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1995                    anyhow::Error::new(error).context(cause)
1996                })
1997                .with_context(|| format!("rendering {}", path.display()))?;
1998            for key in array_keys(&one.config, "") {
1999                if array_merge_policy(&key) == ArrayMerge::Append {
2000                    continue;
2001                }
2002                if let Some(first) = seen.get(&key) {
2003                    bail!(
2004                        "`{key}` is an array declared in two config layers:\n  \
2005                         {}\n  {}\nteravars appends arrays when it merges, so \
2006                         magi would run the concatenation of both - which is \
2007                         not what either file says. Declare `{key}` in exactly \
2008                         one of them.",
2009                        first.display(),
2010                        path.display()
2011                    );
2012                }
2013                seen.insert(key, path.clone());
2014            }
2015        }
2016        Ok(())
2017    }
2018
2019    /// Which layers contributed to a composed, appendable array key (e.g.
2020    /// `"verify.gate"`), in the same low-to-high-priority order
2021    /// [`Config::load_layers`] concatenates them in. Layers that do not
2022    /// declare `key` at all are omitted.
2023    ///
2024    /// This is a **display aid for `magi doctor` only.** The command list
2025    /// that actually runs always comes from the one joint
2026    /// [`teravars::load_merged`] call in `load_layers`, never from this
2027    /// function - the exact hazard [`Config::refuse_split_arrays`] warns
2028    /// about is two merge paths that might disagree, so this function must
2029    /// never become a second source of the *composed* value, only of which
2030    /// file wrote which line in it.
2031    ///
2032    /// Re-rendering each layer alone can, in principle, resolve a
2033    /// `{{ vars.x }}` differently than the joint render would, if `x` is
2034    /// defined in one layer and referenced in another - the same caveat
2035    /// `refuse_split_arrays`'s structural, key-only check already lives with.
2036    /// None of magi's own gate commands cross that line, and a doctor listing
2037    /// is read by a human who can compare it against the joint one printed
2038    /// alongside it, so this is judged worth the simplicity of not
2039    /// threading provenance through the real load path.
2040    pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
2041        let mut engine = teravars::Engine::default();
2042        let ctx = Self::render_ctx(paths);
2043        let mut out = Vec::new();
2044        for path in paths {
2045            let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
2046                continue;
2047            };
2048            let mut cur = &one.config;
2049            let mut found = None;
2050            let parts: Vec<&str> = key.split('.').collect();
2051            for (i, part) in parts.iter().enumerate() {
2052                match cur.get(*part) {
2053                    Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
2054                        found = Some(a);
2055                        break;
2056                    }
2057                    Some(toml::Value::Table(t)) => cur = t,
2058                    _ => break,
2059                }
2060            }
2061            let Some(values) = found else { continue };
2062            let strings: Vec<String> = values
2063                .iter()
2064                .filter_map(|v| v.as_str().map(str::to_owned))
2065                .collect();
2066            if !strings.is_empty() {
2067                out.push((path.clone(), strings));
2068            }
2069        }
2070        out
2071    }
2072
2073    /// Each layer rendered on its own, with the outcome per file: the
2074    /// settings screen's way of saying which layer a value came from and which
2075    /// layer is the one that does not parse. A **display aid only**, for the
2076    /// same reason as [`Config::array_provenance`]: the effective config
2077    /// always comes from the one joint [`Config::load_layers`].
2078    pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
2079        let mut engine = teravars::Engine::default();
2080        let ctx = Self::render_ctx(paths);
2081        paths
2082            .iter()
2083            .map(|path| {
2084                let one = teravars::load_merged([path], &mut engine, &ctx)
2085                    .map(|m| m.config)
2086                    .with_context(|| format!("rendering {}", path.display()));
2087                (path.clone(), one)
2088            })
2089            .collect()
2090    }
2091
2092    /// Render a composed command list for `magi doctor`: the joined command
2093    /// line the run actually uses, plus - only when more than one layer
2094    /// contributed - which layer wrote which line.
2095    ///
2096    /// A single contributing layer (the common case today) stays the plain
2097    /// one-line summary magi has always printed, `empty` included: that
2098    /// honest "(none — ...)" is what caught a real gate-composition gap
2099    /// before this array could compose at all, and composition should not
2100    /// make the common case noisier.
2101    pub fn describe_composed(
2102        paths: &[PathBuf],
2103        commands: &[String],
2104        key: &str,
2105        empty: &str,
2106    ) -> String {
2107        if commands.is_empty() {
2108            return empty.to_owned();
2109        }
2110        let joined = commands.join(" && ");
2111        let provenance = Self::array_provenance(paths, key);
2112        if provenance.len() <= 1 {
2113            return joined;
2114        }
2115        let mut out = joined;
2116        for (path, cmds) in &provenance {
2117            out.push_str(&format!("\n    [{}] {}", path.display(), cmds.join(" && ")));
2118        }
2119        out
2120    }
2121
2122    /// Resolve the config for `repo`, honouring an explicit `--config` path.
2123    ///
2124    /// Returns the config and the layers it came from, empty for built-in
2125    /// defaults. The repository layers come from the remote-tracking ref as it
2126    /// stands (see the module doc); use [`Config::discover_fetched`] where a
2127    /// stale ref would matter.
2128    #[track_caller]
2129    pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2130        #[cfg(test)]
2131        crate::web::request_cost::discovery();
2132        tracing::trace!(
2133            caller = %std::panic::Location::caller(),
2134            explicit = explicit.is_some(),
2135            "discovering configuration"
2136        );
2137        if let Some(p) = explicit {
2138            let paths = vec![p.to_path_buf()];
2139            return Ok((Self::load_layers(&paths)?, paths));
2140        }
2141        let paths = Self::layers_checked(repo)?;
2142        if paths.is_empty() {
2143            return Ok((Self::autodetected(), paths));
2144        }
2145        Ok((Self::load_layers(&paths)?, paths))
2146    }
2147
2148    /// [`Config::discover`] after `git fetch <remote> <base>`: for every path
2149    /// that is about to start work. A failed fetch is an error.
2150    pub async fn discover_fetched(
2151        repo: &Path,
2152        explicit: Option<&Path>,
2153    ) -> Result<(Self, Vec<PathBuf>)> {
2154        if explicit.is_none() && is_git_repo(repo) {
2155            // A checkout that was never cloned from the remote has no
2156            // `<remote>/HEAD`; learn it here (refs/remotes only) so an
2157            // ordinary start recovers instead of failing in `discover`.
2158            let (remote, cfg_base) = probe_remote_base(repo);
2159            let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2160                .await
2161                .with_context(|| ConfigFailure {
2162                    stage: "config-base",
2163                    target: remote.clone(),
2164                })?;
2165            let out = crate::git::fetch(repo, &remote, &base)
2166                .await
2167                .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2168                .with_context(|| ConfigFailure {
2169                    stage: "config-fetch",
2170                    target: format!("{remote}/{base}"),
2171                })?;
2172            if !out.ok() {
2173                return Err(anyhow::anyhow!(
2174                    "cannot read magi.toml: `git fetch {remote} {base}` failed ({});                      refusing to use the local checkout's copy, which may be stale",
2175                    out.stderr.lines().next().unwrap_or("").trim()
2176                )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2177            }
2178            if cfg_base.is_none() {
2179                crate::git::ensure_remote_head(repo, &remote, &base).await;
2180            }
2181        }
2182        Self::discover(repo, explicit).map_err(|error| {
2183            if error.downcast_ref::<ConfigFailure>().is_some() {
2184                error
2185            } else {
2186                error.context(ConfigFailure {
2187                    stage: "config-load",
2188                    target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2189                })
2190            }
2191        })
2192    }
2193
2194    /// [`Config::layers`], but an unreadable remote ref is an error.
2195    fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2196        let mut paths: Vec<PathBuf> = Self::machine_layer()
2197            .into_iter()
2198            .filter(|p| p.is_file())
2199            .collect();
2200        paths.extend(Self::repo_layers(repo)?);
2201        Ok(paths)
2202    }
2203
2204    /// Describe a repository layer without directing the operator to its cache.
2205    pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2206        let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2207        if let Some(root) = cached {
2208            let relative = path.strip_prefix(root).unwrap_or(path);
2209            let reference = resolve_remote_base(repo)
2210                .map(|(remote, base)| format!("{remote}/{base}"))
2211                .unwrap_or_else(|_| "remote base".to_owned());
2212            format!(
2213                "{} at {reference} (including its includes)",
2214                repo.join(relative).display()
2215            )
2216        } else {
2217            format!("{} (including its includes)", path.display())
2218        }
2219    }
2220
2221    /// Only the repository layers (lowest first), from `<remote>/<base>` in a
2222    /// git working tree and from disk elsewhere.
2223    pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2224        match inspect_git_repo(repo) {
2225            RepoKind::NotGit => Ok(local_repo_layers(repo)),
2226            RepoKind::Found(dirs) => remote_layers_with_git(repo, Some(dirs)),
2227            RepoKind::Fallback => remote_layers_fallback(repo),
2228        }
2229    }
2230
2231    /// Environment variable that relocates the machine-wide config layer.
2232    ///
2233    /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
2234    /// of the one under [`dirs::config_dir`]; set it to the empty string and
2235    /// magi reads no machine layer at all.
2236    ///
2237    /// This exists because the machine layer is otherwise unavoidable, and a
2238    /// test that builds a config fixture is not asking for the operator's
2239    /// preferences to be merged into it. Adding `[repos] roots` to the real
2240    /// machine config on a development box turned two passing tests red -
2241    /// `repos_list_returns_name_and_path_for_every_configured_root` and
2242    /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
2243    /// declare `[repos] roots` of their own, which [`Config::layers`] then
2244    /// found in two layers and [`Config::refuse_split_arrays`] correctly
2245    /// refused. CI never saw it: a runner has no machine config, so the suite
2246    /// was green there and red only where somebody actually uses magi.
2247    ///
2248    /// An operator gets the same escape hatch for free: a second machine
2249    /// config, or none, without moving files about.
2250    pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2251
2252    /// Every config layer that applies to `repo`, in increasing precedence.
2253    ///
2254    /// The machine layer is whatever [`Config::machine_layer`] resolves to,
2255    /// which is nothing at all in a test build.
2256    pub fn layers(repo: &Path) -> Vec<PathBuf> {
2257        let mut paths = Vec::new();
2258        paths.extend(Self::machine_layer());
2259        paths.push(repo.join(".magi").join("config.toml"));
2260        paths.push(repo.join("magi.toml"));
2261        paths.retain(|p| p.is_file());
2262        paths
2263    }
2264
2265    /// The machine-wide layer's path, when there is one.
2266    ///
2267    /// **A test build has none unless it names one.** A fixture is a complete
2268    /// statement of the config under test, and the operator's own preferences
2269    /// have no business being merged into it - least of all silently, on one
2270    /// machine, in a suite that is green everywhere else.
2271    #[cfg(test)]
2272    pub(crate) fn machine_layer() -> Option<PathBuf> {
2273        std::env::var(Self::CONFIG_DIR_ENV)
2274            .ok()
2275            .filter(|dir| !dir.trim().is_empty())
2276            .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2277    }
2278
2279    /// The machine-wide layer's path, when there is one.
2280    #[cfg(not(test))]
2281    pub(crate) fn machine_layer() -> Option<PathBuf> {
2282        match std::env::var(Self::CONFIG_DIR_ENV) {
2283            // Named, and empty on purpose: no machine layer.
2284            Ok(dir) if dir.trim().is_empty() => None,
2285            Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2286            Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2287        }
2288    }
2289
2290    /// Built-in config whose roster is the agent CLIs found on `PATH`.
2291    pub fn autodetected() -> Self {
2292        let mut cfg = Self::default();
2293        for (kind, id, model) in [
2294            (AgentKind::Claude, "opus", Some("opus")),
2295            (AgentKind::Claude, "sonnet", Some("sonnet")),
2296            (AgentKind::Antigravity, "antigravity", None),
2297            (AgentKind::Opencode, "opencode", None),
2298            (AgentKind::Codex, "codex", None),
2299            (AgentKind::Omp, "omp", None),
2300        ] {
2301            if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2302                cfg.agents.push(AgentSpec {
2303                    id: id.to_owned(),
2304                    kind,
2305                    model: model.map(str::to_owned),
2306                    command: Vec::new(),
2307                    extra_args: Vec::new(),
2308                    env: BTreeMap::new(),
2309                    prompt_delivery: None,
2310                    max_turn_secs: None,
2311                });
2312            }
2313        }
2314        cfg
2315    }
2316
2317    /// The shared build cache the verify commands and the agents both build
2318    /// into, when the config declares one. See [`Verify::cache_dir`].
2319    pub fn cache_dir(&self) -> Option<PathBuf> {
2320        self.verify.cache_dir()
2321    }
2322
2323    /// Look an agent up by id.
2324    pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2325        self.agents
2326            .iter()
2327            .find(|a| a.id == id)
2328            .with_context(|| format!("no agent with id `{id}` in the roster"))
2329    }
2330
2331    /// Rotate `count` seats out of `ids`, or out of the whole roster at
2332    /// `offset` when `ids` is empty.
2333    ///
2334    /// The one rotation rule - explicit ids cycle, an empty list rotates the
2335    /// roster - shared by every seat count [`Config::resolve_roles`] fills in,
2336    /// rather than each seat reimplementing it and drifting apart.
2337    fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2338        let mut out = Vec::with_capacity(count);
2339        for i in 0..count {
2340            let spec = if ids.is_empty() {
2341                self.agents[(i + offset) % self.agents.len()].clone()
2342            } else {
2343                self.agent(&ids[i % ids.len()])?.clone()
2344            };
2345            out.push(spec);
2346        }
2347        Ok(out)
2348    }
2349
2350    /// `ids`, resolved to specs in the order named, or the whole `[[agents]]`
2351    /// roster in file order when `ids` is empty — the same "explicit ids
2352    /// stand alone, an empty list means the whole roster" rule [`Self::rotate`]
2353    /// applies, but with no `count` to truncate to and no `offset` to wrap by.
2354    /// See [`ResolvedRoles::implementer_roster`] for why a truncated, rotated
2355    /// list cannot answer the question this exists for.
2356    fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2357        if ids.is_empty() {
2358            Ok(self.agents.clone())
2359        } else {
2360            ids.iter().map(|id| self.agent(id).cloned()).collect()
2361        }
2362    }
2363
2364    /// Fill the roles out to the configured widths.
2365    ///
2366    /// An empty role list rotates through the whole roster, so a three-agent
2367    /// roster with `implementers = 3` gives one implementation per agent, and
2368    /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
2369    /// author of candidate *i* whenever the roster has more than one agent.
2370    pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2371        if self.agents.is_empty() {
2372            bail!(
2373                "agent roster is empty: no agent CLI found on PATH and no \
2374                 [[agents]] in the config. Run `magi init` to write a starter \
2375                 magi.toml."
2376            );
2377        }
2378        let pinned = self
2379            .graph
2380            .selected_implementer
2381            .as_ref()
2382            .map(|id| self.agent(id).cloned())
2383            .transpose()?;
2384        Ok(ResolvedRoles {
2385            implementers: match &pinned {
2386                Some(agent) => vec![agent.clone()],
2387                None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2388            },
2389            judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2390            reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2391            fixer: match self.roles.fixer.as_ref() {
2392                // Ids are validated against the roster here; whether the CLI
2393                // is installed is left to invocation, like every other seat.
2394                Some(choice) => Some(crate::agent::pick_chain(
2395                    &self.agents,
2396                    Some(choice),
2397                    &|_| true,
2398                    "fixer",
2399                )?),
2400                None => None,
2401            },
2402            // Role resolution validates roster shape, but deliberately does
2403            // not preflight a CLI. The other graph seats have always deferred
2404            // that failure to invocation; doing it only for the conductor
2405            // made otherwise usable graph commands and `doctor` fail as one.
2406            conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2407                Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2408                // A fallback chain: the first id the roster knows. The rest
2409                // are `agent::pick_chain`'s business at invocation.
2410                Some(ids) if !ids.is_empty() => ids
2411                    .iter()
2412                    .find_map(|id| self.agent(id).ok())
2413                    .cloned()
2414                    .with_context(|| {
2415                        format!("[roles] conductor names no agent in the roster: {ids:?}")
2416                    })?,
2417                // Keep the normal standalone-seat preference when something
2418                // is installed, but retain a roster fallback when it is not.
2419                // Invocation then reports the unavailable CLI in the same
2420                // place it does for every other graph role.
2421                _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2422                    .unwrap_or_else(|_| self.agents[0].clone()),
2423            },
2424            implementer_roster: match pinned {
2425                Some(agent) => vec![agent],
2426                None => self.full_roster(&self.roles.implementers)?,
2427            },
2428            judge_roster: self.full_roster(&self.roles.judges)?,
2429            reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2430        })
2431    }
2432
2433    /// Advisor seats for the design-deliberation stage (see
2434    /// `graph::Runner::advise`): `[roles] advisors` when set, otherwise the
2435    /// judge roster - see [`Roles::advisors`] for why that fallback and not
2436    /// the whole roster.
2437    ///
2438    /// The fallback rotates with `offset = 1`, matching the judges line in
2439    /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
2440    /// `roles.judges`, which is empty whenever judges themselves are
2441    /// unconfigured and rotating the whole roster. Falling back with
2442    /// `offset = 0` there would silently hand the advisors a *different*
2443    /// agent set than the judges an unconfigured run would actually get,
2444    /// which is the one thing [`Roles::advisors`]'s doc promises will not
2445    /// happen.
2446    ///
2447    /// Called lazily from the graph node itself rather than folded into
2448    /// [`Config::resolve_roles`]: unlike the other roles, a failure here must
2449    /// not stop a run from starting at all - the deliberation stage is an
2450    /// enrichment `[graph] advise` can turn off, not a seat later nodes
2451    /// cannot proceed without - and at the point `resolve_roles` runs (before
2452    /// [`crate::run::RunState`] exists, on `Runner::start`) there would be no
2453    /// run yet for a resolution failure to be reported against.
2454    pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2455        if self.agents.is_empty() {
2456            bail!(
2457                "agent roster is empty: no agent CLI found on PATH and no \
2458                 [[agents]] in the config. Run `magi init` to write a starter \
2459                 magi.toml."
2460            );
2461        }
2462        if !self.roles.advisors.is_empty() {
2463            return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2464        }
2465        self.rotate(&self.roles.judges, self.graph.advisors, 1)
2466    }
2467
2468    /// The untruncated roster advisor seats hand over along: `[roles]
2469    /// advisors` when set, otherwise the judges' roster, exactly as
2470    /// [`Self::advisors`] chooses its own list.
2471    pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2472        if self.roles.advisors.is_empty() {
2473            self.full_roster(&self.roles.judges)
2474        } else {
2475            self.full_roster(&self.roles.advisors)
2476        }
2477    }
2478
2479    /// Shell prefix for [`Verify`] commands.
2480    pub fn shell(&self) -> Vec<String> {
2481        if let Some(s) = &self.verify.shell {
2482            return s.clone();
2483        }
2484        if which("sh") {
2485            vec!["sh".to_owned(), "-c".to_owned()]
2486        } else {
2487            vec!["cmd".to_owned(), "/C".to_owned()]
2488        }
2489    }
2490
2491    /// Starter config, as written by `magi init`.
2492    pub fn starter_toml() -> String {
2493        let detected = Self::autodetected();
2494        let mut s = String::from(
2495            "# magi — blind multi-agent implementation competition.\n\
2496             # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2497             #   -> blind judging -> deliberation -> private final vote\n\
2498             #   -> fold losers -> review + E2E loop -> gate -> merge.\n\
2499             #\n\
2500             # Rendered by teravars: a `[vars]` table, env\n\
2501             # and system lookups, and `include = [...]` all work. Tera\n\
2502             # braces are live everywhere in this file, but comments are\n\
2503             # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2504             # may quote `{{ ... }}` freely.\n\
2505             #\n\
2506             # Layers deep-merge in increasing\n\
2507             # precedence, so the roster can live once per machine in\n\
2508             # <config_dir>/magi/config.toml and each repo only states its own\n\
2509             # gate:\n\
2510             #   <config_dir>/magi/config.toml  <  .magi/config.toml  <  magi.toml\n\n\
2511             [vars]\n\
2512             # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2513             # Single quotes inside the braces: teravars renders the raw file\n\
2514             # text, so TOML's own \\\" escaping never reaches Tera.\n\
2515             cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2516        );
2517        if detected.agents.is_empty() {
2518            s.push_str(
2519                "# No agent CLI was found on PATH. Fill this in by hand.\n\
2520                 # kind = claude | opencode | antigravity | codex | command\n\
2521                 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2522            );
2523        } else {
2524            for a in &detected.agents {
2525                s.push_str("[[agents]]\n");
2526                s.push_str(&format!("id = {:?}\n", a.id));
2527                s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2528                if let Some(m) = &a.model {
2529                    s.push_str(&format!("model = {m:?}\n"));
2530                }
2531                s.push('\n');
2532            }
2533        }
2534        s.push_str(
2535            "# Leave a role list empty to rotate through the roster.\n\
2536             # A non-empty list is also an ordered backup list: seats take entries from the\n\
2537             # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2538             # next agent to its right, each tried once. Same for judges and reviewers.\n\
2539             # implementers = [\"opus\", \"codex\", \"sonnet\"]  # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2540             [roles]\n\
2541             implementers = []\n\
2542             judges = []\n\
2543             reviewers = []\n\
2544             # conductor = \"opus\"  # arranges the queue; unset picks a seat like chatter does\n\
2545             # synthesizer = \"opus\"  # blends the advisors into one brief; unset picks a seat like chatter does\n\
2546             # synthesizer = [\"opus\", \"codex\"]  # array form: fallback chain, each tried once on quota or failure\n\
2547             # language_judge = \"jev\"  # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2548             # dupes_judge = \"opus\"  # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2549             # fixer = \"opus\"  # applies review findings; unset keeps the winner's own author\n\
2550             # fixer = [\"opus\", \"codex\"]  # array form: fallback chain, each tried once on quota or failure\n\n\
2551             [graph]\n\
2552             # Gate GitHub prose; secret redaction is always enabled.\n\
2553             github_text_guard = true\n\
2554             # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2555             github_language = \"en\"\n\
2556             implementers = 3\n\
2557             judges = 3\n\
2558             deliberate_rounds = 1\n\
2559             reviewers = 3\n\
2560             review_rounds = 6\n\
2561             # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2562             gate_fix_rounds = 1\n\
2563             # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2564             rerun_flaky_checks = true\n\
2565             # Rerun a failed verify.e2e once on the same commit before deciding; a pass is recorded as a flake and filed once as a task.\n\
2566             rerun_failed_e2e = true\n\
2567             # Port the strengths judges named in the losing candidates onto the\n\
2568             # winner before review (best-effort; rolled back on failure or a big diff).\n\
2569             graft_runner_up = true\n\
2570             max_parallel = 4\n\
2571             language = \"en\"\n\
2572             # One CLI conversation per seat: judges keep their own argument\n\
2573             # across deliberation, the fixer keeps its implementation context.\n\
2574             sessions = true\n\
2575             # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2576             # the final gate inherit this value for compatibility.\n\
2577             timeout_review = 1200\n\
2578             # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2579             # verification independent if timeout_review changes later.\n\
2580             # timeout_verify = 1200\n\
2581             # Longest a seat waits for the shared build cache before it is\n\
2582             # spawned. Never counted against an agent's own timeout; expiry\n\
2583             # holds the run (resumable) instead of failing the agent.\n\
2584             # timeout_resource_wait = 1800\n\n\
2585             # What the chat calls you (persona address and the Chat's turn label).\n\
2586             # [talk]\n\
2587             # standing_authorization = false # machine layer only; bounded chat recovery\n\
2588             # operator_name = \"Commander\"\n\n\
2589             # Chat personas (tone only; the web Chat picks one per conversation).\n\
2590             # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2591             # them, and one with a built-in's id replaces it. `default` is the plain\n\
2592             # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2593             # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2594             # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2595             # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2596             # [[talk.personas]]\n\
2597             # id = \"gendo\"\n\
2598             # name = \"Gendo Ikari\"\n\
2599             # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2600             # icon = \"~/pictures/gendo.png\"\n\n\
2601             [verify]\n\
2602             # Run once per review round in the winner's worktree; failures are\n\
2603             # fed back to the fixer.\n\
2604             e2e = []\n\
2605             # Final gate. Every command must exit 0 before a merge.\n\
2606             gate = []\n\
2607             # Mechanical fixers (formatters) run in the winner's worktree before\n\
2608             # e2e and before the gate; whatever they change becomes one commit. A\n\
2609             # failing command only warns - the gate stays the arbiter. Same timeout\n\
2610             # as the gate (timeout_verify). Keep it light and idempotent.\n\
2611             # pre_gate = []\n\n\
2612             # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2613             # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2614             # before any agent or verify command touches it. `copy` reads from the\n\
2615             # primary checkout and never overwrites; `optional` skips a missing\n\
2616             # source. `run` goes through the shell with the worktree as cwd and\n\
2617             # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2618             # the verify timeout). Setup must not edit tracked files, and what it\n\
2619             # leaves untracked is kept out of magi's commits. Declare this in one\n\
2620             # layer only.\n\
2621             # [worktree]\n\
2622             # setup = [\n\
2623             #   { copy = \".env.example -> .env\" },\n\
2624             #   { copy = \".env.local\", optional = true },\n\
2625             #   { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2626             # ]\n\
2627             # pre_clean = [] # Repeatable cleanup before owned clean -fdx.\n\n\
2628             [merge]\n\
2629             # none | local | pr\n\
2630             mode = \"none\"\n\
2631             # expected (default) | none. Set none only in repository config without CI.\n\
2632             # Ignores all check statuses; reviews and approval still apply.\n\
2633             # ci = \"expected\"\n\
2634             # release_bump = true  # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2635             [update]\n\
2636             # off | notify | install — checked in the background, throttled.\n\
2637             mode = \"notify\"\n\
2638             # interval = \"24h\"\n\n\
2639             # Opt-in: magi web updates and restarts automatically when a newer release is found.\n\
2640             # auto_restart = false\n\
2641             # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2642             # Handover drains only short admission transactions; active workers continue\n\
2643             # on their original executable generation while new work uses the new one.\n\
2644             # Standalone magi serve cannot restart.\n\
2645             # Failed tags are skipped until process restart or a different tag.\n\
2646             # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2647             [daemon]\n\
2648             # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2649             # no new commit and no check changing state before `magi serve`\n\
2650             # notices and asks you. A failed check is rerun once on its own;\n\
2651             # still red after that escalates at once. 0 turns the watcher off.\n\
2652             # release_stall_minutes = 60\n\n\
2653             [release]\n\
2654             # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2655             # Actions never run (private, no minutes): the release pull request\n\
2656             # does not wait for CI, you approve the merge in magi, and then\n\
2657             # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2658             # runs `commands` from a clean checkout of the merge commit. A\n\
2659             # failure holds the release with a notice; it is never retried blind.\n\
2660             # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2661             # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2662             # mode = \"actions\"\n\
2663             # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2664             # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2665             # safe to repeat: a crash mid-command is treated as unfinished.\n\
2666             # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2667             # timeout_minutes = 30\n\
2668             # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2669             # The first entry is the version of record and must be the file the\n\
2670             # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2671             # rewritten to the same version. Paths are relative to the repository\n\
2672             # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2673             # is not touched.\n\
2674             # version_files = [\n\
2675             #   { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2676             #   { path = \"package.json\", kind = \"json\" },\n\
2677             #   { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2678             # ]\n",
2679        );
2680        s
2681    }
2682}
2683
2684/// Is `program` on `PATH`?
2685pub fn which(program: &str) -> bool {
2686    find_program(program).is_some()
2687}
2688
2689/// The file a bare `program` name resolves to on `PATH`, the way the OS shell
2690/// would find it.
2691///
2692/// Spawn agents through this, not by bare name: on Windows Rust's std
2693/// only tries `name.exe`, so a CLI installed as an npm `.cmd` shim (codex
2694/// since its 2026-09-23 reinstall) is "not found" even though a shell runs it.
2695/// On Windows an extensionless file is never a match: npm writes an `sh`
2696/// script beside every `.cmd` shim, and spawning that fails with os error 193.
2697pub fn find_program(program: &str) -> Option<PathBuf> {
2698    find_program_on(program, &std::env::var_os("PATH")?)
2699}
2700
2701/// [`find_program`] against an explicit `PATH`, for a child whose environment
2702/// overrides it.
2703pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2704    let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2705    find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2706}
2707
2708fn find_program_in(
2709    program: &str,
2710    paths: &std::ffi::OsStr,
2711    pathext: Option<&str>,
2712) -> Option<PathBuf> {
2713    let p = Path::new(program);
2714    if p.components().count() > 1 {
2715        return p.is_file().then(|| p.to_path_buf());
2716    }
2717    std::env::split_paths(paths).find_map(|dir| match pathext {
2718        Some(exts) => {
2719            let bare = dir.join(program);
2720            if p.extension().is_some() && bare.is_file() {
2721                return Some(bare);
2722            }
2723            exts.split(';')
2724                .filter(|e| !e.is_empty())
2725                .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2726                .find(|c| c.is_file())
2727        }
2728        None => Some(dir.join(program)).filter(|c| c.is_file()),
2729    })
2730}
2731
2732/// Sidecar naming the checkout an extracted layer stands for.
2733const REPO_MARKER: &str = ".magi-repo";
2734
2735/// Completion manifest written inside each materialised commit cache directory
2736/// before it is atomically renamed into place.
2737const CACHE_MANIFEST: &str = ".magi-cache-manifest.json";
2738const CACHE_MANIFEST_VERSION: u32 = 3;
2739const REPO_LAYER_RELS: [&str; 2] = [".magi/config.toml", "magi.toml"];
2740
2741/// Git environment overrides that alter repository discovery or ref storage.
2742/// When any of these are set, pure-filesystem inspection steps aside and
2743/// delegates to the `git` CLI.
2744const GIT_OVERRIDE_ENVS: &[&str] = &[
2745    "GIT_DIR",
2746    "GIT_COMMON_DIR",
2747    "GIT_WORK_TREE",
2748    "GIT_OBJECT_DIRECTORY",
2749    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
2750    "GIT_CEILING_DIRECTORIES",
2751    "GIT_DISCOVERY_ACROSS_FILESYSTEM",
2752    "GIT_NAMESPACE",
2753];
2754
2755fn has_git_env_override() -> bool {
2756    GIT_OVERRIDE_ENVS
2757        .iter()
2758        .any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))
2759}
2760
2761#[derive(Debug, Clone)]
2762struct GitDirs {
2763    common_dir: PathBuf,
2764    files_ref_backend: bool,
2765}
2766
2767#[derive(Debug, Clone)]
2768enum RepoKind {
2769    NotGit,
2770    Found(GitDirs),
2771    Fallback,
2772}
2773
2774fn local_repo_layers(repo: &Path) -> Vec<PathBuf> {
2775    [
2776        repo.join(".magi").join("config.toml"),
2777        repo.join("magi.toml"),
2778    ]
2779    .into_iter()
2780    .filter(|p| p.is_file())
2781    .collect()
2782}
2783
2784fn inspect_git_repo(repo: &Path) -> RepoKind {
2785    if has_git_env_override() || !repo.is_dir() {
2786        return RepoKind::Fallback;
2787    }
2788    let start = match repo.canonicalize() {
2789        Ok(p) => p,
2790        Err(_) => {
2791            if repo.is_absolute() {
2792                repo.to_path_buf()
2793            } else {
2794                match std::env::current_dir() {
2795                    Ok(cwd) => cwd.join(repo),
2796                    Err(_) => return RepoKind::Fallback,
2797                }
2798            }
2799        }
2800    };
2801
2802    for dir in start.ancestors() {
2803        let dot_git = dir.join(".git");
2804        match std::fs::symlink_metadata(&dot_git) {
2805            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2806                // A bare repository (or inside `.git` itself) has no `.git`
2807                // entry, yet `git rev-parse --git-dir` succeeds there.
2808                if dir.join("HEAD").is_file()
2809                    && dir.join("objects").is_dir()
2810                    && (dir.join("refs").is_dir() || dir.join("reftable").is_dir())
2811                {
2812                    return RepoKind::Fallback;
2813                }
2814                continue;
2815            }
2816            Err(_) => return RepoKind::Fallback,
2817            Ok(meta) => {
2818                if meta.file_type().is_symlink() {
2819                    return RepoKind::Fallback;
2820                }
2821                let git_dir = if meta.is_dir() {
2822                    if !dot_git.join("HEAD").is_file() {
2823                        return RepoKind::Fallback;
2824                    }
2825                    dot_git
2826                } else if meta.is_file() {
2827                    let Ok(raw) = std::fs::read_to_string(&dot_git) else {
2828                        return RepoKind::Fallback;
2829                    };
2830                    let Some(target) = raw
2831                        .trim_end_matches(['\r', '\n'])
2832                        .strip_prefix("gitdir:")
2833                        .map(str::trim)
2834                        .filter(|s| !s.is_empty())
2835                    else {
2836                        return RepoKind::Fallback;
2837                    };
2838                    let target_path = PathBuf::from(target);
2839                    let resolved = if target_path.is_absolute() {
2840                        target_path
2841                    } else {
2842                        dir.join(target_path)
2843                    };
2844                    if !resolved.is_dir() || !resolved.join("HEAD").is_file() {
2845                        return RepoKind::Fallback;
2846                    }
2847                    resolved
2848                } else {
2849                    return RepoKind::Fallback;
2850                };
2851
2852                let commondir_file = git_dir.join("commondir");
2853                let common_dir = match std::fs::symlink_metadata(&commondir_file) {
2854                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2855                        git_dir.canonicalize().unwrap_or(git_dir)
2856                    }
2857                    Ok(m) if m.is_file() => {
2858                        let Ok(raw) = std::fs::read_to_string(&commondir_file) else {
2859                            return RepoKind::Fallback;
2860                        };
2861                        let target = raw.trim();
2862                        if target.is_empty() {
2863                            return RepoKind::Fallback;
2864                        }
2865                        let target_path = PathBuf::from(target);
2866                        let joined = if target_path.is_absolute() {
2867                            target_path
2868                        } else {
2869                            git_dir.join(target_path)
2870                        };
2871                        let Ok(canonical) = joined.canonicalize() else {
2872                            return RepoKind::Fallback;
2873                        };
2874                        if !canonical.is_dir() {
2875                            return RepoKind::Fallback;
2876                        }
2877                        canonical
2878                    }
2879                    _ => return RepoKind::Fallback,
2880                };
2881
2882                let files_ref_backend = is_standard_files_ref_backend(&common_dir);
2883                return RepoKind::Found(GitDirs {
2884                    common_dir,
2885                    files_ref_backend,
2886                });
2887            }
2888        }
2889    }
2890    RepoKind::NotGit
2891}
2892
2893fn is_git_repo(repo: &Path) -> bool {
2894    match inspect_git_repo(repo) {
2895        RepoKind::NotGit => false,
2896        RepoKind::Found(_) => true,
2897        RepoKind::Fallback => is_git_worktree(repo),
2898    }
2899}
2900
2901fn strip_git_config_value(raw: &str) -> String {
2902    let mut out = String::new();
2903    let mut in_quotes = false;
2904    let mut escaped = false;
2905    for ch in raw.chars() {
2906        if escaped {
2907            out.push(ch);
2908            escaped = false;
2909            continue;
2910        }
2911        if in_quotes {
2912            match ch {
2913                '\\' => escaped = true,
2914                '"' => in_quotes = false,
2915                _ => out.push(ch),
2916            }
2917            continue;
2918        }
2919        match ch {
2920            '"' => in_quotes = true,
2921            '#' | ';' => break,
2922            _ => out.push(ch),
2923        }
2924    }
2925    out.trim().to_owned()
2926}
2927
2928/// True only when `common_dir` uses the standard SHA-1 + `files` ref backend
2929/// with no unknown `[extensions]` or config includes that could change ref
2930/// storage semantics.
2931fn is_standard_files_ref_backend(common_dir: &Path) -> bool {
2932    if common_dir.join("reftable").exists() || !common_dir.join("refs").is_dir() {
2933        return false;
2934    }
2935    let Ok(config) = std::fs::read_to_string(common_dir.join("config")) else {
2936        return false;
2937    };
2938    let mut section = String::new();
2939    for raw_line in config.lines() {
2940        let line = raw_line.trim();
2941        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
2942            continue;
2943        }
2944        if line.ends_with('\\') {
2945            return false;
2946        }
2947        if let Some(rest) = line.strip_prefix('[') {
2948            let Some(end) = rest.find(']') else {
2949                return false;
2950            };
2951            let trailing = rest[end + 1..].trim();
2952            if !trailing.is_empty() && !trailing.starts_with('#') && !trailing.starts_with(';') {
2953                return false;
2954            }
2955            let header = &rest[..end];
2956            section = header
2957                .split(|c: char| c.is_ascii_whitespace() || c == '"')
2958                .next()
2959                .unwrap_or("")
2960                .to_ascii_lowercase();
2961            if matches!(section.as_str(), "include" | "includeif") {
2962                return false;
2963            }
2964            continue;
2965        }
2966        let (key, val) = match line.split_once('=') {
2967            Some((k, v)) => (
2968                k.trim().to_ascii_lowercase(),
2969                strip_git_config_value(v).to_ascii_lowercase(),
2970            ),
2971            None => (
2972                strip_git_config_value(line).to_ascii_lowercase(),
2973                "true".to_owned(),
2974            ),
2975        };
2976        match section.as_str() {
2977            "core" if key == "repositoryformatversion" => {
2978                if !matches!(val.as_str(), "0" | "1") {
2979                    return false;
2980                }
2981            }
2982            "extensions" => match key.as_str() {
2983                "refstorage" if val == "files" => {}
2984                "objectformat" if val == "sha1" => {}
2985                "worktreeconfig" | "relativeworktrees" | "partialclone" | "promisor"
2986                | "preciousobjects" | "noop" | "manyfiles" => {}
2987                _ => return false,
2988            },
2989            _ => {}
2990        }
2991    }
2992    true
2993}
2994
2995fn is_safe_ref_name(name: &str) -> bool {
2996    if !name.starts_with("refs/")
2997        || name.ends_with('/')
2998        || name.starts_with("refs/bisect/")
2999        || name.starts_with("refs/worktree/")
3000        || name.starts_with("refs/rewritten/")
3001    {
3002        return false;
3003    }
3004    name.split('/').all(|part| {
3005        !part.is_empty()
3006            && part != "."
3007            && part != ".."
3008            && !part.contains('\\')
3009            && !part.bytes().any(|b| b <= 0x20 || b == 0x7f)
3010    })
3011}
3012
3013fn join_rel_path(base: &Path, rel: &str) -> PathBuf {
3014    let mut path = base.to_path_buf();
3015    for part in rel.split('/') {
3016        path.push(part);
3017    }
3018    path
3019}
3020
3021fn is_sha1_hex(s: &str) -> bool {
3022    s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
3023}
3024
3025fn is_hex_oid(s: &str) -> bool {
3026    (s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
3027}
3028
3029enum LooseRef {
3030    Missing,
3031    Oid(String),
3032    Symref(String),
3033    Unknown,
3034}
3035
3036fn read_loose_ref(common_dir: &Path, ref_name: &str) -> LooseRef {
3037    if !is_safe_ref_name(ref_name) {
3038        return LooseRef::Unknown;
3039    }
3040    let path = join_rel_path(common_dir, ref_name);
3041    match std::fs::symlink_metadata(&path) {
3042        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return LooseRef::Missing,
3043        Err(_) => return LooseRef::Unknown,
3044        Ok(meta) if !meta.is_file() => return LooseRef::Unknown,
3045        Ok(_) => {}
3046    }
3047    match std::fs::read_to_string(&path) {
3048        Err(e) if e.kind() == std::io::ErrorKind::NotFound => LooseRef::Missing,
3049        Err(_) => LooseRef::Unknown,
3050        Ok(raw) => {
3051            let trimmed = raw.trim();
3052            if let Some(target) = trimmed.strip_prefix("ref:") {
3053                let target = target.trim();
3054                if is_safe_ref_name(target) {
3055                    LooseRef::Symref(target.to_owned())
3056                } else {
3057                    LooseRef::Unknown
3058                }
3059            } else if is_sha1_hex(trimmed) {
3060                LooseRef::Oid(trimmed.to_ascii_lowercase())
3061            } else {
3062                LooseRef::Unknown
3063            }
3064        }
3065    }
3066}
3067
3068enum PackedRef {
3069    Missing,
3070    Oid(String),
3071    Unknown,
3072}
3073
3074fn read_packed_ref(common_dir: &Path, ref_name: &str) -> PackedRef {
3075    let raw = match std::fs::read_to_string(common_dir.join("packed-refs")) {
3076        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return PackedRef::Missing,
3077        Err(_) => return PackedRef::Unknown,
3078        Ok(raw) => raw,
3079    };
3080    let mut lines = raw.lines().peekable();
3081    while let Some(line) = lines.next() {
3082        let line = line.trim_end_matches('\r');
3083        if line.is_empty() || line.starts_with('#') || line.starts_with('^') {
3084            continue;
3085        }
3086        let Some((oid, name)) = line.split_once(' ') else {
3087            return PackedRef::Unknown;
3088        };
3089        if name == ref_name {
3090            if !is_sha1_hex(oid) {
3091                return PackedRef::Unknown;
3092            }
3093            if lines
3094                .peek()
3095                .is_some_and(|next| next.trim_end_matches('\r').starts_with('^'))
3096            {
3097                // Peeled tag entry: let `git` peel and verify `^{commit}`.
3098                return PackedRef::Unknown;
3099            }
3100            return PackedRef::Oid(oid.to_ascii_lowercase());
3101        }
3102    }
3103    PackedRef::Missing
3104}
3105
3106fn resolve_remote_head_files(common_dir: &Path, remote: &str) -> Option<String> {
3107    let head = format!("refs/remotes/{remote}/HEAD");
3108    match read_loose_ref(common_dir, &head) {
3109        LooseRef::Symref(target) => crate::git::remote_head_branch(remote, &target),
3110        _ => None,
3111    }
3112}
3113
3114fn resolve_ref_oid_files(common_dir: &Path, start_ref: &str) -> Option<String> {
3115    let mut current = start_ref.to_owned();
3116    for _ in 0..8 {
3117        match read_loose_ref(common_dir, &current) {
3118            LooseRef::Oid(oid) => return Some(oid),
3119            LooseRef::Symref(next) => current = next,
3120            LooseRef::Missing => {
3121                return match read_packed_ref(common_dir, &current) {
3122                    PackedRef::Oid(oid) => Some(oid),
3123                    PackedRef::Missing | PackedRef::Unknown => None,
3124                };
3125            }
3126            LooseRef::Unknown => return None,
3127        }
3128    }
3129    None
3130}
3131
3132fn repository_git() -> std::process::Command {
3133    #[cfg(test)]
3134    crate::web::request_cost::git();
3135    let mut command = std::process::Command::new("git");
3136    command.arg("--no-replace-objects");
3137    command
3138}
3139
3140fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
3141    use crate::proc::Quiet as _;
3142    let out = repository_git()
3143        .args(args)
3144        .quiet()
3145        .current_dir(repo)
3146        .stdin(std::process::Stdio::null())
3147        .output()
3148        .ok()?;
3149    out.status
3150        .success()
3151        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
3152}
3153
3154/// Is `repo` inside a git working tree? A directory that is not has no branch
3155/// to be stale against, so its files are read as they are.
3156fn is_git_worktree(repo: &Path) -> bool {
3157    git_out(repo, &["rev-parse", "--git-dir"]).is_some()
3158}
3159
3160/// Approval switches whose reviewed-branch values can only add owner holds.
3161/// Keep the allowlist and base-value lookup together when adding a switch.
3162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3163pub enum OwnerHold {
3164    /// Ask before every merge.
3165    LandApproval,
3166    /// Ask when internal review remains contested.
3167    HoldContestedMerge,
3168}
3169
3170impl OwnerHold {
3171    /// Complete allowlist of additive approval switches.
3172    pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
3173
3174    /// TOML key in the graph table.
3175    pub fn key(self) -> &'static str {
3176        match self {
3177            Self::LandApproval => "land_approval",
3178            Self::HoldContestedMerge => "hold_contested_merge",
3179        }
3180    }
3181
3182    /// Value from the trusted configuration snapshot.
3183    pub fn base_value(self, graph: &Graph) -> bool {
3184        match self {
3185            Self::LandApproval => graph.land_approval,
3186            Self::HoldContestedMerge => graph.hold_contested_merge,
3187        }
3188    }
3189}
3190
3191/// Literal true values only: no defaults, includes, rendering or other config.
3192/// Both repository files contribute monotonically, independent of precedence.
3193pub async fn branch_owner_holds(
3194    repo: &Path,
3195    head: &str,
3196) -> (Vec<(OwnerHold, String)>, Vec<String>) {
3197    let mut holds = Vec::new();
3198    let mut diagnostics = Vec::new();
3199    // Git can report a missing path even when the commit itself is absent.
3200    // Distinguish that read failure before treating missing files as normal.
3201    if let Err(error) =
3202        crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
3203    {
3204        diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
3205        return (holds, diagnostics);
3206    }
3207    for file in ["magi.toml", ".magi/config.toml"] {
3208        let object = format!("{head}:{file}");
3209        let text = match crate::git::git(repo, &["show", &object]).await {
3210            Ok(text) => text,
3211            Err(error) => {
3212                // Absence is normal; other read failures remain auditable.
3213                let error = format!("{error:#}");
3214                if !error.contains("does not exist in")
3215                    && !error.contains("exists on disk, but not in")
3216                {
3217                    diagnostics.push(format!(
3218                        "cannot read reviewed branch {file} at {head}: {error}"
3219                    ));
3220                }
3221                continue;
3222            }
3223        };
3224        let value = match toml::from_str::<toml::Value>(&text) {
3225            Ok(value) => value,
3226            Err(error) => {
3227                diagnostics.push(format!(
3228                    "cannot parse reviewed branch {file} at {head}: {error}"
3229                ));
3230                continue;
3231            }
3232        };
3233        if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
3234            diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
3235        }
3236        for hold in OwnerHold::ALL {
3237            if value
3238                .get("graph")
3239                .and_then(|g| g.get(hold.key()))
3240                .and_then(toml::Value::as_bool)
3241                == Some(true)
3242            {
3243                holds.push((hold, file.to_owned()));
3244            }
3245        }
3246    }
3247    (holds, diagnostics)
3248}
3249
3250#[derive(Deserialize, Default)]
3251struct ProbeMerge {
3252    base: Option<String>,
3253    remote: Option<String>,
3254}
3255
3256#[derive(Deserialize, Default)]
3257struct Probe {
3258    merge: Option<ProbeMerge>,
3259}
3260
3261/// `[merge]` base / remote from one file, nothing else. The file is rendered
3262/// (env templates, includes) exactly as a real load would, so a machine layer
3263/// saying `base = "{{ env.X }}"` locates the same ref; when rendering fails
3264/// (a checkout file that needs its own repo context) the plain TOML is read
3265/// instead. Unreadable is `None`: the real load reports it.
3266fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
3267    if !path.is_file() {
3268        return None;
3269    }
3270    let paths = [path.to_path_buf()];
3271    let mut engine = teravars::Engine::default();
3272    let mut ctx = Config::render_ctx(&paths);
3273    // The layered load renders every layer for the checkout being resolved;
3274    // so does this, or `{{ repo_name }}` would name the file's own directory.
3275    ctx.insert("repo", &repo.to_string_lossy());
3276    ctx.insert(
3277        "repo_name",
3278        &repo.file_name().unwrap_or_default().to_string_lossy(),
3279    );
3280    if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
3281        && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
3282    {
3283        return probe.merge;
3284    }
3285    let text = std::fs::read_to_string(path).ok()?;
3286    toml::from_str::<Probe>(&text).ok()?.merge
3287}
3288
3289/// The `[merge] remote` / `base` the layers name, before any git lookup.
3290fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
3291    let mut remote = None;
3292    let mut base = None;
3293    let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
3294    sources.push(repo.join("magi.toml"));
3295    sources.push(repo.join(".magi").join("config.toml"));
3296    for path in sources {
3297        if let Some(m) = probe_merge(&path, repo) {
3298            remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
3299            base = base.or(m.base.filter(|s| !s.trim().is_empty()));
3300        }
3301    }
3302    (remote.unwrap_or_else(|| "origin".to_owned()), base)
3303}
3304
3305/// Where the remote ref is: see the module doc for the order.
3306fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
3307    let (remote, base) = probe_remote_base(repo);
3308    let base = match base {
3309        Some(b) => b,
3310        None => {
3311            let from_files = match inspect_git_repo(repo) {
3312                RepoKind::Found(dirs) if dirs.files_ref_backend => {
3313                    resolve_remote_head_files(&dirs.common_dir, &remote)
3314                }
3315                _ => None,
3316            };
3317            match from_files {
3318                Some(b) => b,
3319                None => {
3320                    let head = format!("refs/remotes/{remote}/HEAD");
3321                    git_out(repo, &["symbolic-ref", "--quiet", &head])
3322                        .and_then(|s| crate::git::remote_head_branch(&remote, &s))
3323                        .with_context(|| missing_remote_head_msg(&remote))?
3324                }
3325            }
3326        }
3327    };
3328    Ok((remote, base))
3329}
3330
3331fn missing_remote_head_msg(remote: &str) -> String {
3332    format!(
3333        "cannot tell which branch of `{remote}` holds magi.toml: \
3334         set [merge] base, or run `git remote set-head {remote} -a`"
3335    )
3336}
3337
3338fn missing_tracking_ref_msg(remote: &str, base: &str) -> String {
3339    format!(
3340        "`{remote}/{base}` does not exist in this checkout; fetch it \
3341         (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
3342         a possibly stale local magi.toml instead"
3343    )
3344}
3345
3346fn fnv_hex(text: &str) -> String {
3347    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
3348    for b in text.bytes() {
3349        hash ^= u64::from(b);
3350        hash = hash.wrapping_mul(0x0100_0000_01b3);
3351    }
3352    format!("{hash:016x}")
3353}
3354
3355/// Does the text declare an `include` directive in any form teravars accepts
3356/// (root `include`, bare or quoted, or `[teravars] include`, as a table or an
3357/// inline table)? Parsed as TOML when it parses; a templated file that does
3358/// not parse is judged by a plain search for the word, because over-detecting
3359/// only costs an extra extraction while missing one fails the load.
3360fn declares_include(text: &str) -> bool {
3361    match toml::from_str::<toml::Table>(text) {
3362        Ok(table) => {
3363            table.contains_key("include")
3364                || table
3365                    .get("teravars")
3366                    .and_then(toml::Value::as_table)
3367                    .is_some_and(|t| t.contains_key("include"))
3368        }
3369        Err(_) => text.contains("include"),
3370    }
3371}
3372
3373/// Unpack the whole tree of `sha` into `dest`, so relative `include`s of a
3374/// repository layer resolve against the same commit.
3375fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
3376    use crate::proc::Quiet as _;
3377    let mut archive = repository_git()
3378        .args(["archive", "--format=tar", sha])
3379        .quiet()
3380        .current_dir(repo)
3381        .stdin(std::process::Stdio::null())
3382        .stdout(std::process::Stdio::piped())
3383        .stderr(std::process::Stdio::null())
3384        .spawn()
3385        .context("running git archive")?;
3386    let tar = std::process::Command::new("tar")
3387        .arg("-x")
3388        .arg("-C")
3389        .arg(dest)
3390        .quiet()
3391        .stdin(archive.stdout.take().context("git archive has no stdout")?)
3392        .output()
3393        .context("running tar")?;
3394    let status = archive.wait().context("waiting for git archive")?;
3395    if !status.success() || !tar.status.success() {
3396        bail!(
3397            "cannot unpack {sha} for the config's includes: {}",
3398            String::from_utf8_lossy(&tar.stderr).trim()
3399        );
3400    }
3401    Ok(())
3402}
3403
3404fn write_extracted(path: &Path, bytes: impl AsRef<[u8]>) -> Result<()> {
3405    use std::io::Write as _;
3406    match std::fs::remove_file(path) {
3407        Ok(()) => {}
3408        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
3409        Err(e) => return Err(e.into()),
3410    }
3411    std::fs::File::create_new(path)?.write_all(bytes.as_ref())?;
3412    Ok(())
3413}
3414
3415#[derive(Debug, Serialize, Deserialize)]
3416struct CacheManifest {
3417    version: u32,
3418    sha: String,
3419    repo: String,
3420    layers: Vec<String>,
3421    extracted_tree: bool,
3422}
3423
3424fn read_cached_layers(dir: &Path, sha: &str, repo: &Path) -> Option<Vec<PathBuf>> {
3425    let raw = std::fs::read(dir.join(CACHE_MANIFEST)).ok()?;
3426    let manifest: CacheManifest = serde_json::from_slice(&raw).ok()?;
3427    if manifest.version != CACHE_MANIFEST_VERSION
3428        || manifest.sha != sha
3429        || manifest.repo != repo.to_string_lossy()
3430        || manifest.layers.len() > REPO_LAYER_RELS.len()
3431    {
3432        return None;
3433    }
3434    let mut out = Vec::with_capacity(manifest.layers.len());
3435    let mut last_idx: Option<usize> = None;
3436    for rel in &manifest.layers {
3437        let idx = REPO_LAYER_RELS.iter().position(|allowed| *allowed == rel)?;
3438        if last_idx.is_some_and(|prev| idx <= prev) {
3439            return None;
3440        }
3441        last_idx = Some(idx);
3442        let file = join_rel_path(dir, rel);
3443        if !file.is_file() || !file.parent().is_some_and(|p| p.join(REPO_MARKER).is_file()) {
3444            return None;
3445        }
3446        out.push(file);
3447    }
3448    Some(out)
3449}
3450
3451enum BatchEntry {
3452    Missing,
3453    Object {
3454        oid: String,
3455        kind: String,
3456        content: Vec<u8>,
3457    },
3458}
3459
3460fn parse_cat_file_batch(mut buf: &[u8], expected: usize) -> Result<Vec<BatchEntry>> {
3461    let mut entries = Vec::with_capacity(expected);
3462    for _ in 0..expected {
3463        let Some(nl) = buf.iter().position(|&b| b == b'\n') else {
3464            bail!("unexpected EOF in git cat-file --batch header");
3465        };
3466        let line = std::str::from_utf8(&buf[..nl])
3467            .context("non-UTF-8 git cat-file --batch header")?
3468            .trim_end_matches('\r');
3469        buf = &buf[nl + 1..];
3470        if line.ends_with(" missing") || line.ends_with(" ambiguous") {
3471            entries.push(BatchEntry::Missing);
3472            continue;
3473        }
3474        let mut parts = line.split_whitespace();
3475        let (Some(oid), Some(kind), Some(size_str), None) =
3476            (parts.next(), parts.next(), parts.next(), parts.next())
3477        else {
3478            bail!("unexpected git cat-file --batch header: {line}");
3479        };
3480        let size: usize = size_str
3481            .parse()
3482            .with_context(|| format!("invalid git cat-file --batch size: {size_str}"))?;
3483        if buf.len() < size + 1 || buf[size] != b'\n' {
3484            bail!("truncated git cat-file --batch body for {oid}");
3485        }
3486        let content = buf[..size].to_vec();
3487        buf = &buf[size + 1..];
3488        entries.push(BatchEntry::Object {
3489            oid: oid.to_owned(),
3490            kind: kind.to_owned(),
3491            content,
3492        });
3493    }
3494    Ok(entries)
3495}
3496
3497/// Verify `<sha>^{commit}` and read `.magi/config.toml` and `magi.toml` from
3498/// that commit in one `git cat-file --batch` invocation.
3499fn read_commit_layers_batch(
3500    repo: &Path,
3501    sha: &str,
3502    remote: &str,
3503    base: &str,
3504) -> Result<(String, Vec<(&'static str, String)>)> {
3505    use crate::proc::Quiet as _;
3506    use std::io::Write as _;
3507
3508    let mut child = repository_git()
3509        .args(["cat-file", "--batch"])
3510        .quiet()
3511        .current_dir(repo)
3512        .stdin(std::process::Stdio::piped())
3513        .stdout(std::process::Stdio::piped())
3514        .stderr(std::process::Stdio::piped())
3515        .spawn()
3516        .context("running git cat-file --batch")?;
3517    if let Some(mut stdin) = child.stdin.take() {
3518        let mut query = format!("{sha}^{{commit}}\n");
3519        for rel in REPO_LAYER_RELS {
3520            query.push_str(&format!("{sha}:{rel}\n"));
3521        }
3522        if let Err(e) = stdin.write_all(query.as_bytes())
3523            && e.kind() != std::io::ErrorKind::BrokenPipe
3524        {
3525            return Err(e).context("writing query to git cat-file --batch");
3526        }
3527    }
3528    let out = child
3529        .wait_with_output()
3530        .context("waiting for git cat-file --batch")?;
3531    if !out.status.success() {
3532        bail!(
3533            "cannot read config from {remote}/{base} ({sha}): {}",
3534            String::from_utf8_lossy(&out.stderr).trim()
3535        );
3536    }
3537    let entries = parse_cat_file_batch(&out.stdout, 1 + REPO_LAYER_RELS.len())?;
3538    let mut iter = entries.into_iter();
3539    let commit_sha = match iter.next() {
3540        Some(BatchEntry::Object { oid, kind, .. }) if kind == "commit" && is_hex_oid(&oid) => oid,
3541        _ => bail!("{}", missing_tracking_ref_msg(remote, base)),
3542    };
3543    // Batch "missing" conflates absent paths with missing objects. Verify
3544    // absence against the commit tree before publishing an immutable manifest.
3545    let present_paths = if iter
3546        .as_slice()
3547        .iter()
3548        .any(|e| matches!(e, BatchEntry::Missing))
3549    {
3550        let tree = git_out(
3551            repo,
3552            &[
3553                "ls-tree",
3554                "--full-tree",
3555                "--name-only",
3556                &commit_sha,
3557                "--",
3558                ".magi/config.toml",
3559                "magi.toml",
3560            ],
3561        )
3562        .context("cannot read repository configuration tree")?;
3563        tree.lines().map(str::to_owned).collect::<Vec<_>>()
3564    } else {
3565        Vec::new()
3566    };
3567    let mut texts = Vec::new();
3568    for (rel, entry) in REPO_LAYER_RELS.into_iter().zip(iter) {
3569        match entry {
3570            BatchEntry::Missing => {
3571                if present_paths.iter().any(|path| path == rel) {
3572                    bail!("cannot read {rel} from {remote}/{base} ({commit_sha}): missing object");
3573                }
3574            }
3575            BatchEntry::Object { kind, content, .. } if kind == "blob" => {
3576                texts.push((rel, String::from_utf8_lossy(&content).into_owned()));
3577            }
3578            BatchEntry::Object { kind, .. } => {
3579                bail!(
3580                    "cannot read {rel} from {remote}/{base} ({commit_sha}): expected blob, found {kind}"
3581                );
3582            }
3583        }
3584    }
3585    Ok((commit_sha, texts))
3586}
3587
3588fn resolve_common_and_commit_cli(
3589    repo: &Path,
3590    remote: &str,
3591    base: &str,
3592) -> Option<(PathBuf, String)> {
3593    let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3594    if !remote.starts_with('-') && !base.starts_with('-') {
3595        let out = git_out(
3596            repo,
3597            &[
3598                "rev-parse",
3599                "--path-format=absolute",
3600                "--git-common-dir",
3601                &spec,
3602            ],
3603        )?;
3604        let mut lines = out.lines().map(str::trim).filter(|l| !l.is_empty());
3605        let common = lines.next()?;
3606        let sha = lines.next()?;
3607        if lines.next().is_none() && is_hex_oid(sha) {
3608            return Some((PathBuf::from(common), sha.to_owned()));
3609        }
3610    }
3611    let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3612        .map(|s| s.trim().to_owned())
3613        .filter(|s| is_hex_oid(s))?;
3614    let common = git_out(
3615        repo,
3616        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
3617    )
3618    .map(|s| PathBuf::from(s.trim()))?;
3619    Some((common, sha))
3620}
3621
3622/// Resolve `refs/remotes/<remote>/HEAD` and its target commit in one `git`
3623/// process when the pure-filesystem fast path does not apply (e.g. reftable,
3624/// sha256, peeled tags, or Git environment overrides).
3625fn resolve_remote_head_and_commit_cli(repo: &Path, remote: &str) -> Result<(String, String)> {
3626    let head = format!("refs/remotes/{remote}/HEAD");
3627    if let Some(out) = git_out(
3628        repo,
3629        &[
3630            "for-each-ref",
3631            "--format=%(refname)%09%(symref)%09%(objecttype)%09%(objectname)%09%(*objecttype)%09%(*objectname)",
3632            &head,
3633        ],
3634    ) {
3635        for line in out.lines() {
3636            let parts: Vec<&str> = line.trim_end_matches('\r').split('\t').collect();
3637            if parts.len() != 6 || parts[0] != head {
3638                continue;
3639            }
3640            let symref = parts[1];
3641            if let Some(base) = crate::git::remote_head_branch(remote, symref) {
3642                if parts[2] == "commit" && is_hex_oid(parts[3]) {
3643                    return Ok((base, parts[3].to_owned()));
3644                }
3645                if parts[4] == "commit" && is_hex_oid(parts[5]) {
3646                    return Ok((base, parts[5].to_owned()));
3647                }
3648                let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3649                let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3650                    .map(|s| s.trim().to_owned())
3651                    .filter(|s| is_hex_oid(s))
3652                    .with_context(|| missing_tracking_ref_msg(remote, &base))?;
3653                return Ok((base, sha));
3654            }
3655        }
3656    }
3657    // `for-each-ref` omits dangling symrefs and non-matching refs. Distinguish
3658    // a missing `HEAD` symref from a valid `HEAD` whose tracking branch is gone.
3659    let base = git_out(repo, &["symbolic-ref", "--quiet", &head])
3660        .and_then(|s| crate::git::remote_head_branch(remote, &s))
3661        .with_context(|| missing_remote_head_msg(remote))?;
3662    let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3663    let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3664        .map(|s| s.trim().to_owned())
3665        .filter(|s| is_hex_oid(s))
3666        .with_context(|| missing_tracking_ref_msg(remote, &base))?;
3667    Ok((base, sha))
3668}
3669
3670fn remote_layers_fallback(repo: &Path) -> Result<Vec<PathBuf>> {
3671    let (remote, cfg_base) = probe_remote_base(repo);
3672    if let Some(base) = cfg_base {
3673        if let Some((common_dir, sha)) = resolve_common_and_commit_cli(repo, &remote, &base) {
3674            return materialize_remote_layers(repo, Some(common_dir), &remote, &base, &sha, true);
3675        }
3676        if !is_git_worktree(repo) {
3677            return Ok(local_repo_layers(repo));
3678        }
3679        bail!("{}", missing_tracking_ref_msg(&remote, &base));
3680    }
3681    if !is_git_worktree(repo) {
3682        return Ok(local_repo_layers(repo));
3683    }
3684    remote_layers_with_git(repo, None)
3685}
3686
3687/// The repository layers (`.magi/config.toml`, `magi.toml`; lowest first) of
3688/// `<remote>/<base>`, extracted from one commit so both files agree.
3689fn remote_layers_with_git(repo: &Path, git_dirs: Option<GitDirs>) -> Result<Vec<PathBuf>> {
3690    let (remote, cfg_base) = probe_remote_base(repo);
3691
3692    // Fast path: standard SHA-1 + `files` ref backend resolves both the remote
3693    // HEAD symref (when needed) and the tracking ref OID directly from the
3694    // common git directory with zero subprocess spawns.
3695    if let Some(dirs) = &git_dirs
3696        && dirs.files_ref_backend
3697    {
3698        let base_from_files = match &cfg_base {
3699            Some(b) => Some(b.clone()),
3700            None => resolve_remote_head_files(&dirs.common_dir, &remote),
3701        };
3702        if let Some(base) = base_from_files {
3703            let tracking = format!("refs/remotes/{remote}/{base}");
3704            if let Some(sha) = resolve_ref_oid_files(&dirs.common_dir, &tracking) {
3705                return materialize_remote_layers(
3706                    repo,
3707                    Some(dirs.common_dir.clone()),
3708                    &remote,
3709                    &base,
3710                    &sha,
3711                    false,
3712                );
3713            }
3714        }
3715    }
3716
3717    // Fallback path: non-`files` ref backend (e.g. reftable), SHA-256, peeled
3718    // tags, env overrides, or missing/broken refs. Keep steady-state cost to at
3719    // most one `git` process when the ref resolves.
3720    let (common_dir, base, sha) = match (git_dirs, cfg_base) {
3721        (Some(dirs), Some(base)) => {
3722            let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3723            let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3724                .map(|s| s.trim().to_owned())
3725                .filter(|s| is_hex_oid(s))
3726                .with_context(|| missing_tracking_ref_msg(&remote, &base))?;
3727            (Some(dirs.common_dir), base, sha)
3728        }
3729        (Some(dirs), None) => {
3730            let (base, sha) = resolve_remote_head_and_commit_cli(repo, &remote)?;
3731            (Some(dirs.common_dir), base, sha)
3732        }
3733        (None, Some(base)) => {
3734            let (common_dir, sha) = resolve_common_and_commit_cli(repo, &remote, &base)
3735                .with_context(|| missing_tracking_ref_msg(&remote, &base))?;
3736            (Some(common_dir), base, sha)
3737        }
3738        (None, None) => {
3739            let (base, sha) = resolve_remote_head_and_commit_cli(repo, &remote)?;
3740            (None, base, sha)
3741        }
3742    };
3743    materialize_remote_layers(repo, common_dir, &remote, &base, &sha, true)
3744}
3745
3746fn materialize_remote_layers(
3747    repo: &Path,
3748    common_dir: Option<PathBuf>,
3749    remote: &str,
3750    base: &str,
3751    sha: &str,
3752    verified: bool,
3753) -> Result<Vec<PathBuf>> {
3754    let repo_key = repo.to_string_lossy();
3755    let key_for = |commit_sha: &str| {
3756        format!(
3757            "{commit_sha}-{}-v{CACHE_MANIFEST_VERSION}",
3758            fnv_hex(&repo_key)
3759        )
3760    };
3761    let primary_root = common_dir.map(|c| c.join("magi").join("config"));
3762    let fallback_root = dirs::cache_dir().map(|p| p.join("magi").join("config"));
3763    let lookup = |commit_sha: &str| -> Option<Vec<PathBuf>> {
3764        let key = key_for(commit_sha);
3765        if let Some(root) = &primary_root
3766            && let Some(layers) = read_cached_layers(&root.join(&key), commit_sha, repo)
3767        {
3768            return Some(layers);
3769        }
3770        read_cached_layers(&fallback_root.as_ref()?.join(&key), commit_sha, repo)
3771    };
3772    if let Some(layers) = lookup(sha) {
3773        if !verified {
3774            // Observing a ref and its cache key is not proof that the commit
3775            // still exists. Git validates the object store (including packs
3776            // and alternates); an unchanged ref or TTL cannot prove that.
3777            let commit = git_out(
3778                repo,
3779                &[
3780                    "rev-parse",
3781                    "--verify",
3782                    "--quiet",
3783                    &format!("{sha}^{{commit}}"),
3784                ],
3785            );
3786            if !commit.is_some_and(|s| s.trim() == sha) {
3787                bail!("{}", missing_tracking_ref_msg(remote, base));
3788            }
3789        }
3790        return Ok(layers);
3791    }
3792
3793    let (commit_sha, texts) = read_commit_layers_batch(repo, sha, remote, base)?;
3794    if commit_sha != sha
3795        && let Some(layers) = lookup(&commit_sha)
3796    {
3797        return Ok(layers);
3798    }
3799
3800    let key = key_for(&commit_sha);
3801    let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
3802    // Content-addressed and built beside the final name, then renamed in: a
3803    // concurrent `discover` sees the whole directory (with manifest) or none
3804    // of it, never a half-written file.
3805    let build = |root: &Path| -> Result<Vec<PathBuf>> {
3806        let final_dir = root.join(&key);
3807        if let Some(layers) = read_cached_layers(&final_dir, &commit_sha, repo) {
3808            return Ok(layers);
3809        }
3810        static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3811        let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3812        std::fs::create_dir_all(root)?;
3813        let tmp = root.join(format!(
3814            "{key}.tmp-{}-{}-{seq}",
3815            std::process::id(),
3816            std::time::SystemTime::now()
3817                .duration_since(std::time::UNIX_EPOCH)
3818                .map(|d| d.as_nanos())
3819                .unwrap_or_default()
3820        ));
3821        let filled = (|| -> Result<()> {
3822            std::fs::create_dir_all(&tmp)?;
3823            if wants_tree {
3824                extract_tree(repo, &commit_sha, &tmp)?;
3825            }
3826            for (rel, text) in &texts {
3827                let file = join_rel_path(&tmp, rel);
3828                let parent = file.parent().unwrap_or(&tmp);
3829                std::fs::create_dir_all(parent)?;
3830                write_extracted(&file, text)?;
3831                write_extracted(&parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
3832            }
3833            let manifest = CacheManifest {
3834                version: CACHE_MANIFEST_VERSION,
3835                sha: commit_sha.clone(),
3836                repo: repo.to_string_lossy().into_owned(),
3837                layers: texts.iter().map(|(rel, _)| (*rel).to_owned()).collect(),
3838                extracted_tree: wants_tree,
3839            };
3840            write_extracted(
3841                &tmp.join(CACHE_MANIFEST),
3842                serde_json::to_vec(&manifest).context("serialize config cache manifest")?,
3843            )?;
3844            Ok(())
3845        })();
3846        if let Err(e) = filled {
3847            let _ = std::fs::remove_dir_all(&tmp);
3848            return Err(e);
3849        }
3850        if std::fs::rename(&tmp, &final_dir).is_err() {
3851            // Lost the race to another process building the same commit, or
3852            // hit a preexisting unverified directory (rename cannot overwrite
3853            // directories on Windows). Only reuse `final_dir` if its manifest
3854            // validates; otherwise fail so the caller falls back cleanly.
3855            let _ = std::fs::remove_dir_all(&tmp);
3856            return read_cached_layers(&final_dir, &commit_sha, repo)
3857                .with_context(|| format!("cannot place {}", final_dir.display()));
3858        }
3859        Ok(texts
3860            .iter()
3861            .map(|(rel, _)| join_rel_path(&final_dir, rel))
3862            .collect())
3863    };
3864    let layers = match primary_root.as_deref().map(&build) {
3865        Some(Ok(layers)) => layers,
3866        _ => {
3867            let root = fallback_root
3868                .as_deref()
3869                .context("no user config cache directory")?;
3870            build(root).with_context(|| format!("extracting config from {remote}/{base}"))?
3871        }
3872    };
3873    Ok(layers)
3874}
3875
3876#[cfg(test)]
3877mod tests {
3878    #[test]
3879    fn standing_authorization_is_only_from_the_named_machine_layer() {
3880        let dir = tempfile::tempdir().unwrap();
3881        let machine = dir.path().join("machine.toml");
3882        let repo = dir.path().join("magi.toml");
3883        std::fs::write(&machine, "[talk]\nstanding_authorization = false\n").unwrap();
3884        std::fs::write(&repo, "[talk]\nstanding_authorization = true\n").unwrap();
3885        let layers = [machine.clone(), repo.clone()];
3886        let load = |paths| Config::load_layers_with_machine(paths, Some(machine.clone())).unwrap();
3887        assert!(!load(&layers).talk.standing_authorization);
3888        assert!(
3889            !load(std::slice::from_ref(&repo))
3890                .talk
3891                .standing_authorization
3892        );
3893        std::fs::write(&machine, "[talk]\nstanding_authorization = true\n").unwrap();
3894        std::fs::write(&repo, "[talk]\nstanding_authorization = false\n").unwrap();
3895        assert!(load(&layers).talk.standing_authorization);
3896    }
3897
3898    #[test]
3899    fn run_records_with_the_retired_editing_network_key_still_load() {
3900        // Run records from v0.205-v0.207 carry it in their config snapshot.
3901        for value in ["enabled", "restricted"] {
3902            let mut graph = serde_json::to_value(Graph::default()).unwrap();
3903            graph["editing_network"] = serde_json::json!(value);
3904            let back: Graph = serde_json::from_value(graph).unwrap();
3905            assert!(
3906                serde_json::to_value(&back)
3907                    .unwrap()
3908                    .get("editing_network")
3909                    .is_none()
3910            );
3911            let from_toml: Graph = toml::from_str(&format!("editing_network = {value:?}")).unwrap();
3912            assert!(
3913                !toml::to_string(&from_toml)
3914                    .unwrap()
3915                    .contains("editing_network")
3916            );
3917        }
3918    }
3919
3920    #[test]
3921    fn coordination_defaults_off_and_validates_rendered_layer_values() {
3922        let dir = tempfile::tempdir().unwrap();
3923        let machine = dir.path().join("machine.toml");
3924        let repo = dir.path().join("repo.toml");
3925        std::fs::write(&machine, "").unwrap();
3926        assert!(Config::default().coordination.is_none());
3927        assert!(Config::load(&machine).unwrap().coordination.is_none());
3928        std::fs::write(
3929            &machine,
3930            r#"
3931[vars]
3932contract = "updater.contract"
3933[coordination]
3934contract_file = "{{ vars.contract }}"
3935contract_token = "protocol-v1"
3936lock_file = "updater.lock"
3937"#,
3938        )
3939        .unwrap();
3940        let cfg = Config::load(&machine).unwrap();
3941        let policy = cfg.coordination.unwrap();
3942        assert_eq!(policy.contract_file, "updater.contract");
3943        assert_eq!(policy.contract_token, "protocol-v1");
3944        assert_eq!(policy.lock_file, "updater.lock");
3945        std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
3946        let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
3947        let policy = cfg.coordination.unwrap();
3948        assert_eq!(policy.contract_file, "updater.contract");
3949        assert_eq!(policy.lock_file, "repository.lock");
3950        std::fs::write(
3951            &repo,
3952            r#"
3953[vars]
3954bad = "../escape"
3955[coordination]
3956lock_file = "{{ vars.bad }}"
3957"#,
3958        )
3959        .unwrap();
3960        let error = Config::load_layers(&[machine, repo]).unwrap_err();
3961        assert!(format!("{error:#}").contains("coordination.lock_file"));
3962    }
3963
3964    #[test]
3965    fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
3966        let dir = tempfile::tempdir().unwrap();
3967        let path = dir.path().join("config.toml");
3968        let valid = toml::toml! {
3969            [coordination]
3970            contract_file = "updater.contract"
3971            contract_token = "protocol-v1"
3972            lock_file = "updater.lock"
3973        };
3974        for key in ["contract_file", "lock_file"] {
3975            for bad in [
3976                "",
3977                " ",
3978                " file",
3979                "file ",
3980                "\tfile",
3981                "file\t",
3982                ".",
3983                "..",
3984                "file..name",
3985                "../escape",
3986                "a/b",
3987                "a\\b",
3988                "/absolute",
3989                "C:drive",
3990                "C:\\absolute",
3991                "nul\0name",
3992            ] {
3993                let mut table = valid.clone();
3994                table["coordination"][key] = bad.into();
3995                std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3996                let error = Config::load(&path).unwrap_err();
3997                assert!(
3998                    format!("{error:#}").contains(&format!("coordination.{key}")),
3999                    "{bad:?}: {error:#}"
4000                );
4001            }
4002        }
4003        for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
4004            let mut table = valid.clone();
4005            table["coordination"]["contract_token"] = bad.into();
4006            std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4007            let error = Config::load(&path).unwrap_err();
4008            assert!(
4009                format!("{error:#}").contains("coordination.contract_token"),
4010                "{error:#}"
4011            );
4012        }
4013        for key in ["contract_file", "contract_token", "lock_file"] {
4014            let mut table = valid.clone();
4015            table["coordination"].as_table_mut().unwrap().remove(key);
4016            std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4017            let error = Config::load(&path).unwrap_err();
4018            assert!(
4019                format!("{error:#}").contains(&format!("coordination.{key}")),
4020                "{error:#}"
4021            );
4022        }
4023        let mut table = valid;
4024        table["coordination"]
4025            .as_table_mut()
4026            .unwrap()
4027            .insert("typo".into(), "value".into());
4028        std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4029        assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
4030    }
4031
4032    #[test]
4033    fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
4034        let mut cfg = Config::default();
4035        assert_eq!(
4036            cfg.context_window("claude-sonnet-4-5-20250929"),
4037            Some(200_000)
4038        );
4039        assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
4040        assert_eq!(cfg.context_window("mystery-model"), None);
4041        cfg.context_windows
4042            .insert("claude-sonnet-4-5".into(), 1_000_000);
4043        cfg.context_windows.insert("claude-sonnet-4".into(), 5);
4044        cfg.context_windows.insert("mystery".into(), 32_768);
4045        // Longest user prefix beats a shorter one and the built-in table.
4046        assert_eq!(
4047            cfg.context_window("claude-sonnet-4-5-20250929"),
4048            Some(1_000_000)
4049        );
4050        // An exact name beats any prefix.
4051        cfg.context_windows
4052            .insert("claude-sonnet-4-5-20250929".into(), 7);
4053        assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
4054        assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
4055    }
4056
4057    use super::*;
4058
4059    /// npm writes an extensionless `sh` script beside `codex.cmd`; on Windows
4060    /// the `.cmd` is the spawnable one (os error 193 otherwise, 2026-09-23).
4061    #[test]
4062    fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
4063        let dir = tempfile::tempdir().unwrap();
4064        std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
4065        std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
4066        let paths = dir.path().as_os_str();
4067        assert_eq!(
4068            find_program_in("codex", paths, Some(".EXE;.CMD")),
4069            Some(dir.path().join("codex.cmd"))
4070        );
4071        assert_eq!(
4072            find_program_in("codex", paths, None),
4073            Some(dir.path().join("codex"))
4074        );
4075        assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
4076    }
4077
4078    fn spec(id: &str) -> AgentSpec {
4079        AgentSpec {
4080            id: id.to_owned(),
4081            kind: AgentKind::Command,
4082            model: None,
4083            command: vec!["true".to_owned()],
4084            extra_args: Vec::new(),
4085            env: BTreeMap::new(),
4086            prompt_delivery: None,
4087            max_turn_secs: None,
4088        }
4089    }
4090
4091    #[test]
4092    fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
4093        let default: Merge = toml::from_str("").unwrap();
4094        assert_eq!(default.ci, MergeCi::Expected);
4095        let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
4096        assert_eq!(
4097            config.merge.ci.expectation(),
4098            crate::land::CiExpectation::Absent
4099        );
4100        assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
4101        assert!(Config::starter_toml().contains("# ci = \"expected\""));
4102    }
4103
4104    #[test]
4105    fn github_text_guard_defaults_on_and_can_be_disabled() {
4106        let default: Graph = toml::from_str("").unwrap();
4107        assert!(default.github_text_guard);
4108        let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
4109        assert!(!disabled.github_text_guard);
4110        let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
4111        assert!(!config.graph.github_text_guard);
4112        assert!(Config::starter_toml().contains("github_text_guard = true"));
4113    }
4114
4115    #[test]
4116    fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
4117        assert!(Graph::default().rerun_flaky_checks);
4118        let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
4119        assert!(!off.rerun_flaky_checks);
4120        assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
4121    }
4122
4123    #[test]
4124    fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
4125        // `timeout_verify` used to not exist: `verify.e2e`/`verify.gate` ran
4126        // under `timeout_review`. A config written before this field existed
4127        // must run exactly as before, which means its default has to be the
4128        // same 1200s `timeout_review` has always defaulted to.
4129        let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
4130        assert_eq!(g.timeout_verify, None);
4131        assert_eq!(g.verify_timeout(), 3600);
4132    }
4133
4134    #[test]
4135    fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
4136        // The bug this field exists to close: `[graph] timeout_review = 45`
4137        // used to shrink the real-machine `verify.e2e`/`verify.gate` budget
4138        // along with the reviewer seats' own timeout, because both read the
4139        // same field.
4140        let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
4141        assert_eq!(g.timeout_review, 45);
4142        assert_eq!(
4143            g.verify_timeout(),
4144            45,
4145            "an omitted legacy value follows review"
4146        );
4147        let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
4148            .expect("parse explicit override");
4149        assert_eq!(explicit.verify_timeout(), 1200);
4150    }
4151
4152    #[test]
4153    fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
4154        let g: Graph = toml::from_str("implementers = 4\n").unwrap();
4155        assert_eq!(g.implementers, 4);
4156        let g: Graph = toml::from_str("candidates = 5\n").unwrap();
4157        assert_eq!(g.implementers, 5);
4158    }
4159
4160    fn layered(lower: &str, upper: &str) -> Result<Config> {
4161        let dir = tempfile::tempdir().unwrap();
4162        let a = dir.path().join("a.toml");
4163        let b = dir.path().join("b.toml");
4164        std::fs::write(&a, lower).unwrap();
4165        std::fs::write(&b, upper).unwrap();
4166        Config::load_layers(&[a, b])
4167    }
4168
4169    #[test]
4170    fn graph_implementers_higher_layer_wins_across_spellings() {
4171        let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
4172        assert_eq!(c.graph.implementers, 5);
4173        let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
4174        assert_eq!(c.graph.implementers, 5);
4175        let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
4176        assert_eq!(c.graph.implementers, 2);
4177    }
4178
4179    #[test]
4180    fn graph_implementers_both_keys_in_one_layer_is_refused() {
4181        let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
4182            .unwrap_err()
4183            .to_string();
4184        assert!(
4185            err.contains("candidates") && err.contains("implementers"),
4186            "{err}"
4187        );
4188        assert!(err.contains("b.toml"), "{err}");
4189    }
4190
4191    #[test]
4192    fn a_toml_layer_written_before_these_fields_existed_still_parses() {
4193        // `deny_unknown_fields` cuts both ways: a config from before
4194        // `timeout_verify`/`e2e_every_round` existed must still parse, with
4195        // both defaulted rather than refused as unknown-in-reverse.
4196        let g: Graph =
4197            toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
4198                .expect("an old-shaped [graph] table must still parse");
4199        assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
4200        assert!(
4201            !g.e2e_every_round,
4202            "off by default, same as before this field existed"
4203        );
4204    }
4205
4206    #[test]
4207    fn empty_roles_rotate_judges_off_their_own_candidate() {
4208        // Three seats, said out loud: this is a test about *rotation*, and it
4209        // has nothing to say about how many candidates a task buys by default.
4210        let cfg = Config {
4211            agents: vec![spec("a"), spec("b"), spec("c")],
4212            graph: Graph {
4213                implementers: 3,
4214                ..Graph::default()
4215            },
4216            ..Config::default()
4217        };
4218        let roles = cfg.resolve_roles().unwrap();
4219        let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
4220        let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
4221        assert_eq!(impls, ["a", "b", "c"]);
4222        assert_eq!(judges, ["b", "c", "a"]);
4223        for (i, j) in judges.iter().enumerate() {
4224            assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
4225        }
4226    }
4227
4228    #[test]
4229    fn single_agent_roster_fills_every_seat() {
4230        let cfg = Config {
4231            agents: vec![spec("solo")],
4232            graph: Graph {
4233                implementers: 3,
4234                ..Graph::default()
4235            },
4236            ..Config::default()
4237        };
4238        let roles = cfg.resolve_roles().unwrap();
4239        assert_eq!(roles.implementers.len(), 3);
4240        assert!(roles.judges.iter().all(|a| a.id == "solo"));
4241    }
4242
4243    #[test]
4244    fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
4245        // `implementers = 1` (a solo run) still resolves `implementers` down to
4246        // one slot, but `implementer_roster` must carry every agent in the
4247        // roster, in file order, for `graph::Runner`'s quota fallback to walk
4248        // forward through once that one slot's agent runs out of quota.
4249        let cfg = Config {
4250            agents: vec![spec("a"), spec("b"), spec("c")],
4251            graph: Graph {
4252                implementers: 1,
4253                ..Graph::default()
4254            },
4255            ..Config::default()
4256        };
4257        let roles = cfg.resolve_roles().unwrap();
4258        assert_eq!(roles.implementers.len(), 1);
4259        let roster: Vec<&str> = roles
4260            .implementer_roster
4261            .iter()
4262            .map(|a| a.id.as_str())
4263            .collect();
4264        assert_eq!(roster, ["a", "b", "c"]);
4265    }
4266
4267    #[test]
4268    fn implementer_roster_follows_explicit_ids_in_the_order_named() {
4269        let cfg = Config {
4270            agents: vec![spec("a"), spec("b"), spec("c")],
4271            roles: Roles {
4272                implementers: vec!["c".to_owned(), "a".to_owned()],
4273                ..Roles::default()
4274            },
4275            graph: Graph {
4276                implementers: 1,
4277                ..Graph::default()
4278            },
4279            ..Config::default()
4280        };
4281        let roles = cfg.resolve_roles().unwrap();
4282        // Unaffected by the new field: still just the first named id.
4283        assert_eq!(roles.implementers.len(), 1);
4284        assert_eq!(roles.implementers[0].id, "c");
4285        let roster: Vec<&str> = roles
4286            .implementer_roster
4287            .iter()
4288            .map(|a| a.id.as_str())
4289            .collect();
4290        assert_eq!(roster, ["c", "a"]);
4291    }
4292
4293    #[test]
4294    fn explicit_roles_win() {
4295        let cfg = Config {
4296            agents: vec![spec("a"), spec("b")],
4297            roles: Roles {
4298                implementers: vec!["b".to_owned()],
4299                judges: vec!["a".to_owned()],
4300                reviewers: Vec::new(),
4301                fixer: Some("a".into()),
4302                ..Roles::default()
4303            },
4304            ..Config::default()
4305        };
4306        let roles = cfg.resolve_roles().unwrap();
4307        assert!(roles.implementers.iter().all(|a| a.id == "b"));
4308        assert!(roles.judges.iter().all(|a| a.id == "a"));
4309        let fixer = roles.fixer.unwrap();
4310        assert_eq!(fixer.len(), 1);
4311        assert_eq!(fixer[0].id, "a");
4312        assert_eq!(roles.conductor.id, "a");
4313    }
4314
4315    #[test]
4316    fn fixer_takes_a_string_or_an_ordered_chain() {
4317        let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
4318        assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
4319        let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
4320        assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
4321
4322        let resolve = |fixer: Option<AgentChoice>| {
4323            Config {
4324                agents: vec![spec("a"), spec("b"), spec("c")],
4325                roles: Roles {
4326                    fixer,
4327                    ..Roles::default()
4328                },
4329                ..Config::default()
4330            }
4331            .resolve_roles()
4332        };
4333        let ids = |r: &ResolvedRoles| -> Vec<String> {
4334            r.fixer
4335                .as_ref()
4336                .unwrap()
4337                .iter()
4338                .map(|s| s.id.clone())
4339                .collect()
4340        };
4341        // The string form is a chain of one; unset stays unset (the winner's author).
4342        assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
4343        assert!(resolve(None).unwrap().fixer.is_none());
4344        // Order kept, an unknown id skipped, a duplicate keeps its first place.
4345        let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
4346        assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
4347        // Nothing resolving names the role.
4348        let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
4349        assert!(format!("{err:#}").contains("fixer"), "{err:#}");
4350    }
4351
4352    #[test]
4353    fn unknown_agent_id_is_an_error() {
4354        let cfg = Config {
4355            agents: vec![spec("a")],
4356            roles: Roles {
4357                judges: vec!["nope".to_owned()],
4358                ..Roles::default()
4359            },
4360            ..Config::default()
4361        };
4362        assert!(cfg.resolve_roles().is_err());
4363    }
4364
4365    #[test]
4366    fn conductor_role_is_resolved_validated_and_has_a_fallback() {
4367        let mut cfg = Config {
4368            agents: vec![spec("a"), spec("b")],
4369            ..Config::default()
4370        };
4371        assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
4372
4373        cfg.roles.conductor = Some("b".into());
4374        assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
4375
4376        cfg.roles.conductor = Some("missing".into());
4377        assert!(cfg.resolve_roles().is_err());
4378    }
4379
4380    #[test]
4381    fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
4382        let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
4383        assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
4384        assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
4385
4386        let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
4387        assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
4388        assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
4389
4390        for roles in [one, chain] {
4391            let text = toml::to_string(&roles).unwrap();
4392            let back: Roles = toml::from_str(&text).unwrap();
4393            assert_eq!(back.synthesizer, roles.synthesizer);
4394            assert_eq!(back.chatter, roles.chatter);
4395        }
4396        let text = toml::to_string(&Roles {
4397            conductor: Some("x".into()),
4398            ..Roles::default()
4399        })
4400        .unwrap();
4401        assert!(
4402            text.contains("conductor = \"x\""),
4403            "string stays a string: {text}"
4404        );
4405        assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
4406    }
4407
4408    #[test]
4409    fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
4410        for (text, ids) in [
4411            (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
4412            (
4413                r#"dupes_judge = ["first", "second"]"#,
4414                vec!["first", "second"],
4415            ),
4416            ("dupes_judge = []", vec![]),
4417        ] {
4418            let roles: Roles = toml::from_str(text).unwrap();
4419            assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
4420            let serialized = toml::to_string(&roles).unwrap();
4421            let back: Roles = toml::from_str(&serialized).unwrap();
4422            assert_eq!(back.dupes_judge, roles.dupes_judge);
4423            assert!(serialized.contains(text));
4424        }
4425        assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
4426        assert!(Roles::default().dupes_judge.is_none());
4427        assert!(Config::starter_toml().contains("# dupes_judge ="));
4428
4429        // Standalone roles are resolved lazily, just like chatter.
4430        let mut cfg = Config {
4431            agents: vec![spec("a")],
4432            ..Config::default()
4433        };
4434        cfg.roles.dupes_judge = Some("missing".into());
4435        assert!(cfg.resolve_roles().is_ok());
4436    }
4437
4438    #[test]
4439    fn an_empty_choice_counts_as_unset() {
4440        assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
4441        assert!(AgentChoice::One("  ".to_owned()).ids().is_empty());
4442        assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
4443    }
4444
4445    #[test]
4446    fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
4447        // Unlike `conductor`, `synthesizer` is never validated by
4448        // `resolve_roles` — it is looked up lazily by
4449        // `graph::Runner::synthesize_brief` the same way `[roles] chatter`
4450        // is looked up by `talk::begin`, so this exercises `agent::pick`
4451        // directly instead of going through `resolve_roles`.
4452        let mut cfg = Config {
4453            agents: vec![spec("a"), spec("b")],
4454            ..Config::default()
4455        };
4456        let want = primary(cfg.roles.synthesizer.as_ref());
4457        assert_eq!(
4458            crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
4459                .unwrap()
4460                .id,
4461            "a",
4462            "unset falls back to agent::pick's own default order"
4463        );
4464
4465        cfg.roles.synthesizer = Some("b".into());
4466        let want = primary(cfg.roles.synthesizer.as_ref());
4467        assert_eq!(
4468            crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
4469                .unwrap()
4470                .id,
4471            "b",
4472            "the named agent wins over the default order"
4473        );
4474    }
4475
4476    #[test]
4477    fn empty_roster_is_an_error() {
4478        assert!(Config::default().resolve_roles().is_err());
4479    }
4480
4481    #[test]
4482    fn advise_defaults_to_on_with_three_proposals() {
4483        let g = Graph::default();
4484        assert!(g.advise);
4485        assert!(g.graft_runner_up, "graft is on by default");
4486        assert_eq!(g.advisors, 3);
4487    }
4488
4489    #[test]
4490    fn unset_advisors_falls_back_to_the_judge_roster() {
4491        let cfg = Config {
4492            agents: vec![spec("a"), spec("b")],
4493            roles: Roles {
4494                judges: vec!["b".to_owned()],
4495                ..Roles::default()
4496            },
4497            graph: Graph {
4498                advisors: 2,
4499                ..Graph::default()
4500            },
4501            ..Config::default()
4502        };
4503        let advisors = cfg.advisors().expect("advisors resolve");
4504        assert_eq!(advisors.len(), 2);
4505        assert!(
4506            advisors.iter().all(|a| a.id == "b"),
4507            "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
4508        );
4509    }
4510
4511    #[test]
4512    fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
4513        let cfg = Config {
4514            agents: vec![spec("a"), spec("b")],
4515            roles: Roles {
4516                judges: vec!["b".to_owned()],
4517                advisors: vec!["a".to_owned()],
4518                ..Roles::default()
4519            },
4520            graph: Graph {
4521                advisors: 2,
4522                ..Graph::default()
4523            },
4524            ..Config::default()
4525        };
4526        let advisors = cfg.advisors().expect("advisors resolve");
4527        assert!(advisors.iter().all(|a| a.id == "a"));
4528    }
4529
4530    /// Neither `[roles] advisors` nor `[roles] judges` set: an unconfigured
4531    /// advisor roster must resolve to the exact same agents an unconfigured
4532    /// judge panel would get - same ids, same rotation offset - or the
4533    /// promise in [`Roles::advisors`]'s doc ("advisor diversity for free")
4534    /// does not actually hold.
4535    #[test]
4536    fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
4537        let cfg = Config {
4538            agents: vec![spec("a"), spec("b"), spec("c")],
4539            graph: Graph {
4540                advisors: 3,
4541                judges: 3,
4542                ..Graph::default()
4543            },
4544            ..Config::default()
4545        };
4546        let advisors = cfg.advisors().expect("advisors resolve");
4547        let judges = cfg.resolve_roles().expect("roles resolve").judges;
4548        let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
4549        let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
4550        assert_eq!(
4551            advisor_ids, judge_ids,
4552            "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
4553        );
4554    }
4555
4556    #[test]
4557    fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
4558        let cfg = Config {
4559            agents: vec![spec("a")],
4560            roles: Roles {
4561                advisors: vec!["nope".to_owned()],
4562                ..Roles::default()
4563            },
4564            graph: Graph {
4565                advisors: 1,
4566                ..Graph::default()
4567            },
4568            ..Config::default()
4569        };
4570        let err = cfg.advisors().expect_err("`nope` is not in the roster");
4571        assert!(format!("{err:#}").contains("nope"));
4572    }
4573
4574    #[test]
4575    fn repos_default_to_no_roots_and_a_day_of_trust() {
4576        assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
4577        assert_eq!(Config::default().repos.scan_ttl, 86_400);
4578        assert_eq!(Config::default().repos.fetch_interval, 600);
4579        assert!(!Config::default().repos.auto_clone);
4580        assert!(Config::default().repos.clone_command.is_none());
4581    }
4582
4583    #[test]
4584    fn a_config_file_with_no_repos_table_still_loads() {
4585        let dir = tempfile::tempdir().unwrap();
4586        let path = dir.path().join("magi.toml");
4587        std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4588        let cfg = Config::load(&path).expect("must load without [repos]");
4589        assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
4590        assert_eq!(cfg.repos.scan_ttl, 86_400);
4591    }
4592
4593    /// A fixture is the whole config under test.
4594    ///
4595    /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
4596    /// a machine where somebody had written `<config_dir>/magi/config.toml`
4597    /// the suite silently loaded it as the lowest layer. Adding `[repos]
4598    /// roots` there turned two web tests red - their fixtures declare
4599    /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
4600    /// array key spread across two layers. CI stayed green throughout,
4601    /// because a runner has no such file: the suite failed only where magi is
4602    /// actually used.
4603    ///
4604    /// So a test build has no machine layer unless it asks for one, and this
4605    /// is that promise. Written against a real file at the real location so
4606    /// it fails if `machine_layer` starts reading it again.
4607    #[test]
4608    fn a_test_build_does_not_read_the_operators_machine_config() {
4609        let repo = tempfile::tempdir().unwrap();
4610        std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4611
4612        let layers = Config::layers(repo.path());
4613        assert_eq!(
4614            layers,
4615            vec![repo.path().join("magi.toml")],
4616            "only the fixture's own file may be a layer"
4617        );
4618        if let Some(real) = dirs::config_dir() {
4619            let machine = real.join("magi").join("config.toml");
4620            assert!(
4621                !layers.contains(&machine),
4622                "the operator's {} must not be a layer in a test build",
4623                machine.display()
4624            );
4625        }
4626    }
4627
4628    #[test]
4629    fn auto_upgrade_config_defaults_and_opt_in() {
4630        let default: Update = toml::from_str("").unwrap();
4631        assert!(!default.auto_restart);
4632        assert_eq!(default.mode, UpdateMode::Notify);
4633        let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
4634        assert!(enabled.auto_restart);
4635        assert_eq!(enabled.interval.as_deref(), Some("2h"));
4636        assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
4637    }
4638
4639    #[test]
4640    fn starter_toml_loads_through_teravars() {
4641        let dir = tempfile::tempdir().unwrap();
4642        let path = dir.path().join("magi.toml");
4643        std::fs::write(&path, Config::starter_toml()).unwrap();
4644        let parsed = Config::load(&path).expect("starter config must load");
4645        assert_eq!(parsed.graph.implementers, 3);
4646        assert_eq!(parsed.merge.mode, MergeMode::None);
4647        assert_eq!(parsed.merge.style, MergeStyle::Merge);
4648        assert!(parsed.graph.sessions);
4649        assert!(parsed.graph.github_text_guard);
4650        assert_eq!(parsed.graph.timeout_review, 1200);
4651        assert_eq!(parsed.graph.verify_timeout(), 1200);
4652        assert_eq!(parsed.update.mode, UpdateMode::Notify);
4653    }
4654
4655    #[test]
4656    fn release_defaults_to_actions_and_the_starter_documents_it() {
4657        let dir = tempfile::tempdir().unwrap();
4658        let path = dir.path().join("magi.toml");
4659        std::fs::write(&path, Config::starter_toml()).unwrap();
4660        let r = Config::load(&path).unwrap().release;
4661        assert_eq!(r.mode, ReleaseMode::Actions);
4662        assert!(!r.is_local());
4663        assert!(r.commands.is_empty());
4664        assert_eq!(r.timeout_minutes, 30);
4665        assert!(Config::starter_toml().contains("# mode = \"actions\""));
4666    }
4667
4668    #[test]
4669    fn release_local_parses_and_unknown_keys_are_refused() {
4670        let dir = tempfile::tempdir().unwrap();
4671        let path = dir.path().join("magi.toml");
4672        std::fs::write(
4673            &path,
4674            "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
4675        )
4676        .unwrap();
4677        let r = Config::load(&path).unwrap().release;
4678        assert!(r.is_local());
4679        assert_eq!(r.commands.len(), 2);
4680        assert_eq!(r.timeout_minutes, 5);
4681        std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
4682        assert!(Config::load(&path).is_err());
4683        std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
4684        assert!(Config::load(&path).is_err());
4685    }
4686
4687    #[test]
4688    fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
4689        let dir = tempfile::tempdir().unwrap();
4690        let path = dir.path().join("magi.toml");
4691        std::fs::write(&path, Config::starter_toml()).unwrap();
4692        assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
4693        assert!(Config::starter_toml().contains("# pre_gate = []"));
4694    }
4695
4696    #[test]
4697    fn release_version_files_parse_default_empty_and_are_validated() {
4698        let dir = tempfile::tempdir().unwrap();
4699        let path = dir.path().join("magi.toml");
4700        std::fs::write(&path, "").unwrap();
4701        assert!(
4702            Config::load(&path)
4703                .unwrap()
4704                .release
4705                .version_files
4706                .is_empty()
4707        );
4708        std::fs::write(
4709            &path,
4710            "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
4711        )
4712        .unwrap();
4713        let files = Config::load(&path).unwrap().release.version_files;
4714        assert_eq!(files.len(), 2);
4715        assert_eq!(files[1].kind, VersionKind::Json);
4716        for bad in [
4717            "{ path = \"package.json\", kind = \"json\" }",
4718            "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
4719            "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
4720            "{ path = \"Cargo.toml\", kind = \"yaml\" }",
4721        ] {
4722            std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
4723            assert!(Config::load(&path).is_err(), "{bad}");
4724        }
4725        assert!(Config::starter_toml().contains("# version_files = ["));
4726    }
4727
4728    #[test]
4729    fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
4730        let starter = Config::starter_toml();
4731        assert!(starter.contains("When timeout_verify is omitted, E2E and"));
4732        assert!(starter.contains("verification independent if timeout_review changes later"));
4733        assert!(starter.contains("# timeout_verify = 1200"));
4734    }
4735
4736    #[test]
4737    fn starter_toml_documents_chat_personas() {
4738        let starter = Config::starter_toml();
4739        assert!(starter.contains("# [[talk.personas]]"));
4740        assert!(starter.contains("tone only"));
4741    }
4742
4743    #[test]
4744    fn talk_personas_parse_and_are_validated() {
4745        let dir = tempfile::tempdir().unwrap();
4746        let path = dir.path().join("magi.toml");
4747        std::fs::write(
4748            &path,
4749            "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
4750             [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
4751        )
4752        .unwrap();
4753        let cfg = Config::load(&path).expect("loads");
4754        assert_eq!(cfg.talk.personas.len(), 2);
4755        let catalog = crate::persona::catalog(&cfg.talk.personas);
4756        let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
4757        assert_eq!(
4758            (rei.name.as_str(), rei.prompt.as_str()),
4759            ("Quiet", "Be brief.")
4760        );
4761        assert_eq!(catalog.last().unwrap().id, "gendo");
4762
4763        for (body, needle) in [
4764            (
4765                "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
4766                "empty `id`",
4767            ),
4768            (
4769                "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
4770                "empty `prompt`",
4771            ),
4772            (
4773                "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
4774                 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
4775                "more than once",
4776            ),
4777            (
4778                "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
4779                "cannot be redefined",
4780            ),
4781        ] {
4782            std::fs::write(&path, body).unwrap();
4783            let err = format!("{:#}", Config::load(&path).unwrap_err());
4784            assert!(err.contains(needle), "{needle}: {err}");
4785        }
4786    }
4787
4788    #[test]
4789    fn talk_operator_name_is_trimmed_and_validated() {
4790        let dir = tempfile::tempdir().unwrap();
4791        let path = dir.path().join("magi.toml");
4792        let load = |body: &str| {
4793            std::fs::write(&path, body).unwrap();
4794            Config::load(&path)
4795        };
4796        let ok = load("[talk]\noperator_name = \"  Commander \"\n").expect("ok");
4797        assert_eq!(ok.talk.operator_name(), Some("Commander"));
4798        let blank = load("[talk]\noperator_name = \"   \"\n").expect("blank");
4799        assert_eq!(blank.talk.operator_name(), None);
4800        assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
4801        let long = "x".repeat(65);
4802        assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
4803    }
4804
4805    #[test]
4806    fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
4807        let dir = tempfile::tempdir().unwrap();
4808        let load = |body: &str| {
4809            let path = dir.path().join("c.toml");
4810            std::fs::write(&path, body).unwrap();
4811            Config::load(&path)
4812        };
4813        let ok = load(
4814            "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
4815             [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
4816        )
4817        .unwrap();
4818        let c = crate::persona::catalog(&ok.talk.personas);
4819        assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
4820        assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
4821        assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
4822        let oversized = format!(
4823            "data:image/png;base64,{}",
4824            "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
4825        );
4826        for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
4827            for (id, fields) in [
4828                ("rei", ""),
4829                ("default", ""),
4830                ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
4831            ] {
4832                let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
4833                let cfg = load(&body).expect("bad icon must not invalidate config");
4834                let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
4835                assert_eq!(persona.id, id);
4836                assert!(crate::persona_icon::load(bad).is_err());
4837            }
4838        }
4839        let doc = Config::starter_toml();
4840        assert!(doc.contains("# icon = "));
4841    }
4842
4843    #[test]
4844    fn talk_personas_in_two_layers_are_refused() {
4845        let dir = tempfile::tempdir().unwrap();
4846        let machine = dir.path().join("machine.toml");
4847        let repo = dir.path().join("repo.toml");
4848        let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
4849        std::fs::write(&machine, one).unwrap();
4850        std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
4851        let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
4852        assert!(err.contains("talk.personas"), "{err}");
4853    }
4854
4855    #[test]
4856    fn starter_toml_documents_role_lists_as_backup_order() {
4857        let starter = Config::starter_toml();
4858        assert!(starter.contains("also an ordered backup list"));
4859        assert!(starter.contains("codex then sonnet are spares"));
4860    }
4861
4862    /// A repository whose ruleset forbids merge commits declares that once,
4863    /// here, rather than magi asking GitHub about it on every render (see
4864    /// [`MergeStyle`]'s own doc for why).
4865    #[test]
4866    fn a_repository_can_declare_a_linear_history_merge_style() {
4867        let dir = tempfile::tempdir().unwrap();
4868        let path = dir.path().join("magi.toml");
4869        std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
4870        let parsed = Config::load(&path).expect("config must load");
4871        assert_eq!(parsed.merge.style, MergeStyle::Squash);
4872    }
4873
4874    #[test]
4875    fn later_layers_win_and_vars_render() {
4876        let dir = tempfile::tempdir().unwrap();
4877        let machine = dir.path().join("machine.toml");
4878        let project = dir.path().join("magi.toml");
4879        // The machine layer owns the roster...
4880        std::fs::write(
4881            &machine,
4882            "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
4883             [graph]\ncandidates = 3\nmax_parallel = 8\n[verify]\nbuild_cache = \"shared\"\n",
4884        )
4885        .unwrap();
4886        // ...and the project layer only states what is repo-specific, plus a
4887        // `[vars]` value interpolated into a command.
4888        std::fs::write(
4889            &project,
4890            "[vars]\ncache = \"/shared\"\n\n\
4891             [graph]\ncandidates = 2\n\n\
4892             [verify]\nbuild_cache = \"isolated\"\n\
4893             gate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
4894        )
4895        .unwrap();
4896
4897        let cfg = Config::load_layers(&[machine, project]).expect("layered load");
4898        assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
4899        assert_eq!(cfg.graph.implementers, 2, "project layer wins");
4900        assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
4901        assert_eq!(cfg.verify.build_cache, BuildCache::Isolated);
4902        assert_eq!(
4903            cfg.verify.gate,
4904            ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
4905        );
4906        // The rendered command is where the cache path is read back from.
4907        assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
4908    }
4909
4910    #[test]
4911    fn saved_config_without_a_build_cache_policy_remains_shared() {
4912        let saved: Config = serde_json::from_str(r#"{"verify":{"gate":["cargo test"]}}"#).unwrap();
4913        assert_eq!(saved.verify.build_cache, BuildCache::Shared);
4914    }
4915
4916    #[test]
4917    fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
4918        // An operator who writes no `[graph]` timeout keys at all must still
4919        // land on the hour, not on the five/fifteen minutes this turn used
4920        // to hardcode before it read from config.
4921        let g = Graph::default();
4922        assert_eq!(g.timeout_talk, 3600);
4923
4924        let dir = tempfile::tempdir().unwrap();
4925        let path = dir.path().join("magi.toml");
4926        std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4927        let cfg = Config::load(&path).expect("must load without timeout_talk set");
4928        assert_eq!(cfg.graph.timeout_talk, 3600);
4929    }
4930
4931    #[test]
4932    fn an_overridden_talk_timeout_reaches_the_loaded_config() {
4933        let dir = tempfile::tempdir().unwrap();
4934        let path = dir.path().join("magi.toml");
4935        std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
4936        let cfg = Config::load(&path).expect("must load");
4937        assert_eq!(cfg.graph.timeout_talk, 120);
4938    }
4939
4940    #[test]
4941    fn the_disk_defaults_are_the_measurements_made_up_front() {
4942        let cfg = Config::default();
4943        assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
4944        assert!(cfg.disk.auto_fold);
4945        assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
4946        assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
4947    }
4948
4949    #[test]
4950    fn an_unset_disk_section_is_the_safe_default() {
4951        let dir = tempfile::tempdir().unwrap();
4952        std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
4953        let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
4954        assert_eq!(cfg.disk, Disk::default());
4955    }
4956
4957    #[test]
4958    fn env_is_available_to_templates_with_a_default() {
4959        let dir = tempfile::tempdir().unwrap();
4960        let path = dir.path().join("magi.toml");
4961        // teravars ships no `env`; magi adds it, and the `default` filter has
4962        // to cover the unset case or every machine would need the variable.
4963        //
4964        // Deliberately no named variable: `env` is keyed by the exact spelling
4965        // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
4966        // test asserting `env.PATH` passes on one runner and fails on another.
4967        // The map's non-emptiness is the platform-neutral claim.
4968        std::fs::write(
4969            &path,
4970            "[verify]\n\
4971             gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
4972             \"populated={{ env | length > 0 }}\"]\n",
4973        )
4974        .unwrap();
4975        let cfg = Config::load(&path).expect("env lookup must render");
4976        assert_eq!(cfg.verify.gate[0], "cache=fallback");
4977        assert_eq!(cfg.verify.gate[1], "populated=true");
4978    }
4979
4980    #[test]
4981    fn a_broken_template_names_the_file() {
4982        let dir = tempfile::tempdir().unwrap();
4983        let path = dir.path().join("magi.toml");
4984        std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
4985        let err = Config::load(&path).expect_err("must not silently ignore");
4986        assert!(err.to_string().contains("teravars"), "{err}");
4987    }
4988
4989    #[test]
4990    fn tera_syntax_in_comments_is_inert() {
4991        // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
4992        // comment may quote template syntax without rendering. Before 0.2.2 this
4993        // load failed: the commented-out braces reached the template parser.
4994        let dir = tempfile::tempdir().unwrap();
4995        let path = dir.path().join("magi.toml");
4996        std::fs::write(
4997            &path,
4998            "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
4999             [graph]\ncandidates = 2\n",
5000        )
5001        .unwrap();
5002        let cfg = Config::load(&path).expect("comments must be inert, not rendered");
5003        assert_eq!(cfg.graph.implementers, 2);
5004    }
5005
5006    #[test]
5007    fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
5008        use std::time::Duration;
5009
5010        let mut s: AgentSpec =
5011            toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
5012        let budget = Duration::from_millis(1500);
5013        assert_eq!(s.max_turn_secs, None);
5014        assert_eq!(s.turn_timeout(budget), budget);
5015        assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
5016        for (cap, expected) in [
5017            (1, Duration::from_secs(1)),
5018            (2, budget),
5019            (0, Duration::ZERO),
5020        ] {
5021            s.max_turn_secs = Some(cap);
5022            let saved = toml::to_string(&s).unwrap();
5023            let loaded: AgentSpec = toml::from_str(&saved).unwrap();
5024            assert_eq!(loaded.max_turn_secs, Some(cap));
5025            assert_eq!(loaded.turn_timeout(budget), expected);
5026        }
5027    }
5028
5029    #[test]
5030    fn opencode_defaults_to_file_delivery() {
5031        let mut s = spec("oc");
5032        s.kind = AgentKind::Opencode;
5033        assert_eq!(s.delivery(), Delivery::File);
5034        s.prompt_delivery = Some(Delivery::Argv);
5035        assert_eq!(s.delivery(), Delivery::Argv);
5036    }
5037    #[test]
5038    fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
5039        // Both default on, and that pair is the safety property: `land` takes
5040        // over the watching an operator was doing by hand, `land_approval`
5041        // keeps the irreversible step a human decision. An unattended merge
5042        // needs BOTH flipped, which has to be chosen deliberately twice.
5043        let g = Graph::default();
5044        assert!(
5045            g.land,
5046            "stopping at an open PR left the watching to a human"
5047        );
5048        assert!(
5049            g.land_approval,
5050            "on-by-default land is only defensible while this is also on"
5051        );
5052        assert!(g.land_rounds > 0, "a loop with no budget never terminates");
5053        assert!(
5054            g.hold_contested_merge,
5055            "a contested hand-off must still reach a human when approvals are off"
5056        );
5057    }
5058    #[test]
5059    fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
5060        // teravars appends arrays. For an ordered list of seats, or an argv,
5061        // the concatenation is something neither file says - and the operator
5062        // pays for the extra seats by the token.
5063        let dir = tempfile::tempdir().unwrap();
5064        let machine = dir.path().join("machine.toml");
5065        let repo = dir.path().join("magi.toml");
5066        std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
5067        std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
5068
5069        let err = Config::load_layers(&[machine.clone(), repo.clone()])
5070            .expect_err("two layers naming one array must not merge silently");
5071        assert_eq!(
5072            err.downcast_ref::<ConfigFailure>().unwrap().stage,
5073            "config-merge"
5074        );
5075        let err = err.to_string();
5076        assert!(err.contains("roles.implementers"), "{err}");
5077        // Both files are named: the fix is to delete one of them, and the
5078        // operator has to know which two to choose between.
5079        assert!(err.contains("machine.toml"), "{err}");
5080        assert!(err.contains("magi.toml"), "{err}");
5081    }
5082
5083    #[test]
5084    fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
5085        // The split the layering exists for: state a preference machine-wide,
5086        // let the repository own its own lists.
5087        let dir = tempfile::tempdir().unwrap();
5088        let machine = dir.path().join("machine.toml");
5089        let repo = dir.path().join("magi.toml");
5090        std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
5091        std::fs::write(
5092            &repo,
5093            "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
5094             [roles]\nimplementers = [\"oc\"]\n",
5095        )
5096        .unwrap();
5097
5098        let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
5099        assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
5100        assert_eq!(cfg.roles.implementers, ["oc"]);
5101        assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
5102    }
5103
5104    #[test]
5105    fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
5106        // The `editorconfig-checker` distribution problem: a shared layer
5107        // wants to add a gate command without erasing the repository's own.
5108        let dir = tempfile::tempdir().unwrap();
5109        let machine = dir.path().join("machine.toml");
5110        let repo = dir.path().join("magi.toml");
5111        std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
5112        std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5113
5114        let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5115        assert_eq!(
5116            cfg.verify.gate,
5117            [
5118                "editorconfig-checker".to_owned(),
5119                "cargo make check".to_owned()
5120            ],
5121            "low-priority (machine) command first, high-priority (repo) command after"
5122        );
5123    }
5124
5125    fn load_one(body: &str) -> Result<Config> {
5126        let dir = tempfile::tempdir().unwrap();
5127        let path = dir.path().join("magi.toml");
5128        std::fs::write(&path, body).unwrap();
5129        Config::load_layers(&[path])
5130    }
5131
5132    #[test]
5133    fn pre_clean_config_is_strict_and_single_layer() {
5134        assert!(Config::default().worktree.pre_clean.is_empty());
5135        let good = load_one("[worktree]\npre_clean = [{run = 'cleanup', timeout_secs = 60}]\n");
5136        assert_eq!(good.unwrap().worktree.pre_clean[0].timeout_secs, Some(60));
5137        for bad in [
5138            "{}",
5139            "{run = ''}",
5140            "{run = ' ', timeout_secs = 2}",
5141            "{run = 'x', timeout_secs = 0}",
5142            "{run = 'x', timeout_secs = -1}",
5143            "{copy = 'cache'}",
5144            "{run = 'x', optional = true}",
5145            "'x'",
5146        ] {
5147            assert!(
5148                load_one(&format!("[worktree]\npre_clean = [{bad}]\n")).is_err(),
5149                "{bad}"
5150            );
5151        }
5152        let dir = tempfile::tempdir().unwrap();
5153        let a = dir.path().join("a.toml");
5154        let b = dir.path().join("b.toml");
5155        for path in [&a, &b] {
5156            std::fs::write(path, "[worktree]\npre_clean = [{run = 'cleanup'}]\n").unwrap();
5157        }
5158        assert!(
5159            Config::load_layers(&[a, b])
5160                .unwrap_err()
5161                .to_string()
5162                .contains("worktree.pre_clean")
5163        );
5164    }
5165
5166    #[test]
5167    fn worktree_setup_defaults_to_empty_and_parses_steps() {
5168        assert!(Config::default().worktree.setup.is_empty());
5169        let cfg = load_one(
5170            "[worktree]\nsetup = [\n  { copy = \".env.example -> .env\" },\n  \
5171             { copy = \"x\", optional = true },\n  { run = \"true\", timeout_secs = 5 },\n]\n",
5172        )
5173        .unwrap();
5174        assert_eq!(cfg.worktree.setup.len(), 3);
5175        assert!(cfg.worktree.setup[1].optional);
5176        assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
5177    }
5178
5179    #[test]
5180    fn worktree_setup_rejects_malformed_steps() {
5181        for bad in [
5182            "{ copy = \"a\", run = \"b\" }",
5183            "{ optional = true }",
5184            "{ copy = \"a -> ../b\" }",
5185            "{ copy = \"a -> /abs\" }",
5186            "{ copy = \"a -> .git/config\" }",
5187            "{ run = \"b\", optional = true }",
5188            "{ copy = \"a\", timeout_secs = 3 }",
5189            "{ run = \"b\", bogus = 1 }",
5190        ] {
5191            let body = format!("[worktree]\nsetup = [{bad}]\n");
5192            assert!(load_one(&body).is_err(), "{bad}");
5193        }
5194    }
5195
5196    #[test]
5197    fn worktree_setup_in_two_layers_is_refused() {
5198        let dir = tempfile::tempdir().unwrap();
5199        let machine = dir.path().join("machine.toml");
5200        let repo = dir.path().join("magi.toml");
5201        std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
5202        std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
5203        assert!(Config::load_layers(&[machine, repo]).is_err());
5204    }
5205
5206    #[test]
5207    fn starter_toml_documents_worktree_setup() {
5208        let starter = Config::starter_toml();
5209        assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
5210        // The commented example must be valid once uncommented.
5211        let body = starter.replace("# [worktree]", "[worktree]");
5212        let mut out = String::new();
5213        let mut live = false;
5214        for line in body.lines() {
5215            if line == "[worktree]" {
5216                live = true;
5217            } else if live && !line.starts_with("# ") {
5218                live = false;
5219            }
5220            out.push_str(&if live {
5221                line.replacen("# ", "", 1)
5222            } else {
5223                line.to_owned()
5224            });
5225            out.push('\n');
5226        }
5227        let cfg = load_one(&out).expect("uncommented example loads");
5228        assert_eq!(cfg.worktree.setup.len(), 3);
5229    }
5230
5231    #[test]
5232    fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
5233        let dir = tempfile::tempdir().unwrap();
5234        let machine = dir.path().join("machine.toml");
5235        let repo = dir.path().join("magi.toml");
5236        std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
5237        std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
5238
5239        let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5240        assert_eq!(
5241            cfg.verify.e2e,
5242            ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
5243        );
5244    }
5245
5246    #[test]
5247    fn two_layers_declaring_repos_roots_are_both_scanned() {
5248        let dir = tempfile::tempdir().unwrap();
5249        let machine = dir.path().join("machine.toml");
5250        let repo = dir.path().join("magi.toml");
5251        std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
5252        std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
5253
5254        let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5255        assert_eq!(
5256            cfg.repos.roots,
5257            [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
5258        );
5259    }
5260
5261    #[test]
5262    fn duplicate_gate_commands_across_layers_both_run() {
5263        // Dropping the duplicate would be a silent surprise; the operator
5264        // sees a slower gate, never a missing one.
5265        let dir = tempfile::tempdir().unwrap();
5266        let machine = dir.path().join("machine.toml");
5267        let repo = dir.path().join("magi.toml");
5268        std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
5269        std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
5270
5271        let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5272        assert_eq!(
5273            cfg.verify.gate,
5274            ["same-command".to_owned(), "same-command".to_owned()]
5275        );
5276    }
5277
5278    #[test]
5279    fn notify_command_is_still_refused_across_two_layers() {
5280        // An argv, not a set: concatenating two of them is not a program.
5281        let dir = tempfile::tempdir().unwrap();
5282        let machine = dir.path().join("machine.toml");
5283        let repo = dir.path().join("magi.toml");
5284        std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
5285        std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
5286
5287        let err = Config::load_layers(&[machine.clone(), repo.clone()])
5288            .expect_err("an argv split across layers must not concatenate");
5289        assert_eq!(
5290            err.downcast_ref::<ConfigFailure>().unwrap().stage,
5291            "config-merge"
5292        );
5293        let err = err.to_string();
5294        assert!(err.contains("notify.command"), "{err}");
5295        assert!(err.contains("machine.toml"), "{err}");
5296        assert!(err.contains("magi.toml"), "{err}");
5297    }
5298
5299    #[test]
5300    fn one_layer_declaring_verify_gate_runs_unchanged() {
5301        // The classification must not change behaviour for the configuration
5302        // this very repository has today: exactly one layer names the gate.
5303        let dir = tempfile::tempdir().unwrap();
5304        let path = dir.path().join("magi.toml");
5305        std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5306
5307        let cfg = Config::load(&path).expect("single layer must still load");
5308        assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
5309    }
5310
5311    #[test]
5312    fn layered_parse_failures_name_the_failing_input() {
5313        let dir = tempfile::tempdir().unwrap();
5314        let a = dir.path().join("a.toml");
5315        let b = dir.path().join("b.toml");
5316        std::fs::write(&a, "[graph").unwrap();
5317        std::fs::write(&b, "[verify").unwrap();
5318        let paths = [a.clone(), b.clone()];
5319        let first = Config::load_layers(&paths).unwrap_err();
5320        let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
5321        assert_eq!(first_cause.stage, "config-parse");
5322        assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
5323        std::fs::write(&a, "").unwrap();
5324        let second = Config::load_layers(&paths).unwrap_err();
5325        let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
5326        assert_eq!(second_cause.stage, "config-parse");
5327        assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
5328        assert_ne!(first_cause.target, second_cause.target);
5329    }
5330
5331    #[test]
5332    fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
5333        let dir = tempfile::tempdir().unwrap();
5334        let machine = dir.path().join("machine.toml");
5335        let repo = dir.path().join("magi.toml");
5336        std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
5337        std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5338        let paths = vec![machine.clone(), repo.clone()];
5339
5340        let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
5341        let described =
5342            Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
5343        assert!(described.contains("editorconfig-checker && cargo make check"));
5344        assert!(
5345            described.contains(&machine.display().to_string()),
5346            "{described}"
5347        );
5348        assert!(
5349            described.contains(&repo.display().to_string()),
5350            "{described}"
5351        );
5352
5353        // A single contributing layer stays the plain one-line summary.
5354        let single = vec![repo.clone()];
5355        let solo_cfg = Config::load_layers(&single).expect("single layer loads");
5356        let solo_described =
5357            Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
5358        assert_eq!(solo_described, "cargo make check");
5359    }
5360
5361    mod remote_layers {
5362        use super::*;
5363
5364        fn git(dir: &Path, args: &[&str]) {
5365            use crate::proc::Quiet as _;
5366            let out = std::process::Command::new("git")
5367                .args(args)
5368                .quiet()
5369                .current_dir(dir)
5370                .output()
5371                .unwrap();
5372            assert!(out.status.success(), "git {args:?}: {out:?}");
5373        }
5374
5375        /// A checkout whose origin/main carries `remote` as magi.toml and whose
5376        /// working tree carries `disk`.
5377        fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
5378            let tmp = tempfile::tempdir().unwrap();
5379            let bare = tmp.path().join("o.git");
5380            git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
5381            let repo = tmp.path().join("repo");
5382            std::fs::create_dir_all(&repo).unwrap();
5383            git(&repo, &["init", "-b", "trunk"]);
5384            git(&repo, &["config", "user.name", "t"]);
5385            git(&repo, &["config", "user.email", "t@example.com"]);
5386            std::fs::write(repo.join("magi.toml"), remote).unwrap();
5387            git(&repo, &["add", "-A"]);
5388            git(&repo, &["commit", "-m", "x"]);
5389            git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
5390            git(&repo, &["push", "origin", "trunk"]);
5391            git(&repo, &["fetch", "origin"]);
5392            git(&repo, &["remote", "set-head", "origin", "trunk"]);
5393            std::fs::write(repo.join("magi.toml"), disk).unwrap();
5394            (tmp, repo)
5395        }
5396
5397        #[tokio::test]
5398        async fn branch_owner_holds_only_add_literal_true_values() {
5399            for (text, expected) in [
5400                ("[graph]\nland_approval = true\n", true),
5401                ("[graph]\nland_approval = false\n", false),
5402                ("[graph]\nland = true\n", false),
5403                ("[graph\n", false),
5404                ("[graph]\nland_approval = \"yes\"\n", false),
5405                ("[graph]\nland_approval = 1\n", false),
5406            ] {
5407                let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
5408                let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
5409                let (holds, _) = branch_owner_holds(&repo, &head).await;
5410                assert_eq!(
5411                    holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
5412                    expected
5413                );
5414                assert!(
5415                    !holds
5416                        .iter()
5417                        .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
5418                );
5419                for base in [false, true] {
5420                    let mut cfg = Config::default();
5421                    cfg.graph.land_approval = base;
5422                    let mut state = crate::run::RunState::new(
5423                        repo.clone(),
5424                        "trunk".into(),
5425                        head.clone(),
5426                        "review".into(),
5427                        cfg,
5428                    );
5429                    state.observe_branch_owner_holds(&head).await;
5430                    assert!(
5431                        state.branch_owner_holds.is_empty(),
5432                        "competition candidates are excluded"
5433                    );
5434                    state.reviewed_commits = Some(Vec::new());
5435                    state.observe_branch_owner_holds(&head).await;
5436                    assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
5437                }
5438            }
5439        }
5440
5441        #[tokio::test]
5442        async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
5443            let (_tmp, repo) = fixture(
5444                "[graph]\nland_approval = true\n",
5445                "[graph]\nland_approval = true\n",
5446            );
5447            git(&repo, &["rm", "magi.toml"]);
5448            std::fs::create_dir(repo.join(".magi")).unwrap();
5449            std::fs::write(
5450                repo.join(".magi/config.toml"),
5451                "[graph]\nhold_contested_merge = true\n",
5452            )
5453            .unwrap();
5454            git(&repo, &["add", "."]);
5455            git(&repo, &["commit", "-m", "nested hold"]);
5456            let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
5457            let (holds, _) = branch_owner_holds(&repo, &head).await;
5458            assert_eq!(
5459                holds,
5460                [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
5461            );
5462            let (holds, diagnostics) =
5463                branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
5464            assert!(holds.is_empty());
5465            assert!(!diagnostics.is_empty());
5466            let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
5467            assert!(holds.is_empty());
5468            assert!(!diagnostics.is_empty());
5469            for base in [false, true] {
5470                let mut cfg = Config::default();
5471                cfg.graph.land_approval = base;
5472                let mut state = crate::run::RunState::new(
5473                    repo.clone(),
5474                    "trunk".into(),
5475                    head.clone(),
5476                    "review".into(),
5477                    cfg,
5478                );
5479                state.reviewed_commits = Some(Vec::new());
5480                state.observe_branch_owner_holds(&head).await;
5481                assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
5482                state
5483                    .observe_branch_owner_holds("0000000000000000000000000000000000000000")
5484                    .await;
5485                assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
5486            }
5487        }
5488
5489        #[test]
5490        fn reads_the_remote_blob_not_the_working_tree() {
5491            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5492            let (cfg, _) = Config::discover(&repo, None).unwrap();
5493            assert_eq!(cfg.graph.implementers, 2);
5494        }
5495
5496        #[test]
5497        fn detached_head_still_reads_the_remote() {
5498            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5499            git(&repo, &["checkout", "--detach"]);
5500            let (cfg, _) = Config::discover(&repo, None).unwrap();
5501            assert_eq!(cfg.graph.implementers, 2);
5502        }
5503
5504        #[test]
5505        fn a_missing_ref_is_an_error_not_a_fallback() {
5506            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5507            git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5508            let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
5509            assert!(err.contains("origin"), "{err}");
5510        }
5511
5512        #[test]
5513        fn merge_base_in_the_checkout_locates_the_ref() {
5514            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
5515            assert!(Config::discover(&repo, None).is_err());
5516        }
5517
5518        #[test]
5519        fn the_magi_dir_layer_is_read_too() {
5520            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5521            std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
5522            std::fs::create_dir_all(repo.join(".magi")).unwrap();
5523            std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
5524            git(&repo, &["add", "-A"]);
5525            git(&repo, &["commit", "-m", "y"]);
5526            git(&repo, &["push", "origin", "trunk"]);
5527            git(&repo, &["fetch", "origin"]);
5528            let ((cfg, layers), (_, cold_git)) =
5529                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5530            assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
5531            assert_eq!(layers.len(), 2);
5532            assert_eq!(cold_git, 1);
5533            let common_cache = repo
5534                .join(".git")
5535                .canonicalize()
5536                .unwrap()
5537                .join("magi")
5538                .join("config");
5539            assert!(
5540                layers.iter().all(|p| p.starts_with(&common_cache)),
5541                "expected .magi/config.toml and magi.toml to cache under common git dir {}, got {layers:?}",
5542                common_cache.display()
5543            );
5544
5545            let ((cfg_warm, warm_layers), (_, warm_git)) =
5546                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5547            assert_eq!((cfg_warm.graph.implementers, cfg_warm.graph.judges), (2, 3));
5548            assert_eq!(warm_layers, layers);
5549            assert_eq!(warm_git, 1);
5550        }
5551
5552        #[test]
5553        fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
5554            let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
5555            std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
5556            std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
5557            git(&repo, &["add", "-A"]);
5558            git(&repo, &["commit", "-m", "inc"]);
5559            git(&repo, &["push", "origin", "trunk"]);
5560            git(&repo, &["fetch", "origin"]);
5561            // The working tree's copy differs and must not be used.
5562            std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
5563            let (cfg, _) = Config::discover(&repo, None).unwrap();
5564            assert_eq!(cfg.graph.implementers, 2);
5565        }
5566
5567        #[test]
5568        fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
5569            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
5570            let m = t.path().join("machine.toml");
5571            std::fs::write(
5572                &m,
5573                "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
5574            )
5575            .unwrap();
5576            let (remote, base) = {
5577                let probe = probe_merge(&m, &repo).unwrap();
5578                (probe.remote, probe.base)
5579            };
5580            assert_eq!((remote, base), (None, Some("trunk".to_owned())));
5581        }
5582
5583        #[test]
5584        fn a_machine_layer_base_sees_the_checkouts_repo_name() {
5585            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5586            let m = t.path().join("machine.toml");
5587            std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
5588            let probe = probe_merge(&m, &repo).unwrap();
5589            assert_eq!(probe.base.as_deref(), Some("repo"));
5590        }
5591
5592        #[test]
5593        fn every_include_form_is_recognised() {
5594            assert!(declares_include("include = [\"a.toml\"]\n"));
5595            assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
5596            assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
5597            assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
5598            assert!(!declares_include("[graph]\ncandidates = 2\n"));
5599        }
5600
5601        #[test]
5602        fn an_explicit_config_is_read_as_named() {
5603            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5604            let own = t.path().join("own.toml");
5605            std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
5606            let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
5607            assert_eq!(cfg.graph.implementers, 4);
5608        }
5609
5610        #[test]
5611        fn discover_fetched_fails_when_the_fetch_does() {
5612            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5613            std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
5614            let rt = tokio::runtime::Builder::new_current_thread()
5615                .enable_all()
5616                .build()
5617                .unwrap();
5618            let err = rt
5619                .block_on(Config::discover_fetched(&repo, None))
5620                .unwrap_err();
5621            assert!(format!("{err:#}").contains("fetch"), "{err:#}");
5622        }
5623
5624        #[test]
5625        fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
5626            let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
5627            let remote = tmp.path().join("o.git");
5628            let offline = tmp.path().join("offline.git");
5629            std::fs::rename(&remote, &offline).unwrap();
5630            let rt = tokio::runtime::Builder::new_current_thread()
5631                .enable_all()
5632                .build()
5633                .unwrap();
5634            let fetch = rt
5635                .block_on(Config::discover_fetched(&repo, None))
5636                .unwrap_err();
5637            let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
5638            assert_eq!(fetch_cause.stage, "config-fetch");
5639            assert_eq!(fetch_cause.target, "origin/trunk");
5640
5641            std::fs::rename(&offline, &remote).unwrap();
5642            let parse = rt
5643                .block_on(Config::discover_fetched(&repo, None))
5644                .unwrap_err();
5645            let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
5646            assert_eq!(parse_cause.stage, "config-parse");
5647            assert!(parse_cause.target.contains("magi.toml"));
5648            assert!(
5649                !parse_cause.target.contains("/magi/config/"),
5650                "cache commit paths are incidental"
5651            );
5652            assert_ne!(fetch_cause.stage, parse_cause.stage);
5653        }
5654
5655        #[test]
5656        fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
5657            // Never-fetched remote + followRemoteHEAD=never: fetch creates
5658            // origin/trunk but not origin/HEAD, which discovery then re-reads.
5659            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5660            git(&repo, &["remote", "set-head", "origin", "-d"]);
5661            git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5662            git(
5663                &repo,
5664                &["config", "remote.origin.followRemoteHEAD", "never"],
5665            );
5666            let rt = tokio::runtime::Builder::new_current_thread()
5667                .enable_all()
5668                .build()
5669                .unwrap();
5670            let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
5671            assert_eq!(cfg.graph.implementers, 2);
5672        }
5673
5674        #[test]
5675        fn a_non_git_directory_reads_its_files() {
5676            let dir = tempfile::tempdir().unwrap();
5677            std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
5678            let (cfg, (discoveries, git_calls)) =
5679                crate::web::request_cost::measure_sync(|| Config::discover(dir.path(), None));
5680            assert_eq!(cfg.unwrap().0.graph.implementers, 4);
5681            assert_eq!((discoveries, git_calls), (1, 0));
5682        }
5683
5684        fn push_remote_config(bare: &Path, branch: &str, magi_toml: &str) {
5685            let tmp = tempfile::tempdir().unwrap();
5686            let clone = tmp.path().join("push");
5687            git(
5688                tmp.path(),
5689                &["clone", "-b", branch, &bare.to_string_lossy(), "push"],
5690            );
5691            git(&clone, &["config", "user.name", "t"]);
5692            git(&clone, &["config", "user.email", "t@example.com"]);
5693            std::fs::write(clone.join("magi.toml"), magi_toml).unwrap();
5694            git(&clone, &["add", "magi.toml"]);
5695            git(&clone, &["commit", "-m", "update config"]);
5696            git(&clone, &["push", "origin", branch]);
5697        }
5698
5699        #[test]
5700        fn repeated_discovers_stay_within_bounded_git_spawns() {
5701            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5702
5703            // Cold cache: two processes to read the commit and prove absent
5704            // paths, then one commit validation per subsequent load.
5705            let (values, (discoveries, cold_git)) = crate::web::request_cost::measure_sync(|| {
5706                (0..20)
5707                    .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5708                    .collect::<Vec<_>>()
5709            });
5710            assert!(values.iter().all(|&n| n == 2));
5711            assert_eq!(discoveries, 20);
5712            assert_eq!(cold_git, 21);
5713
5714            // Warm cache: one validation per load, no layer extraction.
5715            let (values, (discoveries, warm_git)) = crate::web::request_cost::measure_sync(|| {
5716                (0..20)
5717                    .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5718                    .collect::<Vec<_>>()
5719            });
5720            assert!(values.iter().all(|&n| n == 2));
5721            assert_eq!(discoveries, 20);
5722            assert_eq!(warm_git, 20);
5723        }
5724
5725        #[test]
5726        fn reftable_warm_discover_uses_one_git_process() {
5727            let tmp = tempfile::tempdir().unwrap();
5728            let repo = tmp.path();
5729            git(repo, &["init", "--ref-format=reftable", "-b", "trunk"]);
5730            git(repo, &["config", "user.name", "t"]);
5731            git(repo, &["config", "user.email", "t@example.com"]);
5732            std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
5733            git(repo, &["add", "magi.toml"]);
5734            git(repo, &["commit", "-m", "config"]);
5735            git(repo, &["update-ref", "refs/remotes/origin/trunk", "HEAD"]);
5736            git(
5737                repo,
5738                &[
5739                    "symbolic-ref",
5740                    "refs/remotes/origin/HEAD",
5741                    "refs/remotes/origin/trunk",
5742                ],
5743            );
5744            assert_eq!(
5745                Config::discover(repo, None).unwrap().0.graph.implementers,
5746                2
5747            );
5748            let (values, (_, count)) = crate::web::request_cost::measure_sync(|| {
5749                (0..10)
5750                    .map(|_| Config::discover(repo, None).unwrap().0.graph.implementers)
5751                    .collect::<Vec<_>>()
5752            });
5753            assert_eq!(values, vec![2; 10]);
5754            assert_eq!(count, 10);
5755        }
5756
5757        #[test]
5758        fn zero_layer_repository_caches_empty_manifest() {
5759            let tmp = tempfile::tempdir().unwrap();
5760            let bare = tmp.path().join("o.git");
5761            git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
5762            let repo = tmp.path().join("repo");
5763            std::fs::create_dir_all(&repo).unwrap();
5764            git(&repo, &["init", "-b", "trunk"]);
5765            git(&repo, &["config", "user.name", "t"]);
5766            git(&repo, &["config", "user.email", "t@example.com"]);
5767            std::fs::write(repo.join("README.md"), "hello\n").unwrap();
5768            git(&repo, &["add", "-A"]);
5769            git(&repo, &["commit", "-m", "no config"]);
5770            git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
5771            git(&repo, &["push", "origin", "trunk"]);
5772            git(&repo, &["fetch", "origin"]);
5773            git(&repo, &["remote", "set-head", "origin", "trunk"]);
5774
5775            let (layers, (_, cold_git)) = crate::web::request_cost::measure_sync(|| {
5776                let mut last = Vec::new();
5777                for _ in 0..20 {
5778                    last = Config::discover(&repo, None).unwrap().1;
5779                }
5780                last
5781            });
5782            assert!(layers.is_empty());
5783            assert_eq!(cold_git, 21);
5784
5785            let (layers, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
5786                let mut last = Vec::new();
5787                for _ in 0..20 {
5788                    last = Config::discover(&repo, None).unwrap().1;
5789                }
5790                last
5791            });
5792            assert!(layers.is_empty());
5793            assert_eq!(warm_git, 20);
5794        }
5795
5796        #[test]
5797        fn moved_loose_and_packed_refs_are_observed_immediately() {
5798            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5799            let bare = t.path().join("o.git");
5800
5801            // Warm initial commit.
5802            assert_eq!(
5803                Config::discover(&repo, None).unwrap().0.graph.implementers,
5804                2
5805            );
5806            let (_, (_, warm_git)) =
5807                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5808            assert_eq!(warm_git, 1);
5809
5810            // Move loose ref without touching the working tree.
5811            push_remote_config(&bare, "trunk", "[graph]\ncandidates = 3\n");
5812            git(&repo, &["fetch", "origin"]);
5813            let (cfg, (_, moved_git)) =
5814                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5815            assert_eq!(cfg.graph.implementers, 3);
5816            assert_eq!(moved_git, 2);
5817            let (cfg, (_, warm_after_move)) =
5818                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5819            assert_eq!(cfg.graph.implementers, 3);
5820            assert_eq!(warm_after_move, 1);
5821
5822            // Pack all refs so the tracking ref lives only in `packed-refs`.
5823            git(&repo, &["pack-refs", "--all"]);
5824            let (cfg, (_, packed_warm)) =
5825                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5826            assert_eq!(cfg.graph.implementers, 3);
5827            assert_eq!(packed_warm, 1);
5828
5829            // Advance the remote again and pack-refs so only `packed-refs` moves.
5830            push_remote_config(&bare, "trunk", "[graph]\ncandidates = 4\n");
5831            git(&repo, &["fetch", "origin"]);
5832            git(&repo, &["pack-refs", "--all"]);
5833            let (cfg, (_, packed_move)) =
5834                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5835            assert_eq!(cfg.graph.implementers, 4);
5836            assert_eq!(packed_move, 2);
5837            let (cfg, (_, packed_warm_2)) =
5838                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5839            assert_eq!(cfg.graph.implementers, 4);
5840            assert_eq!(packed_warm_2, 1);
5841
5842            // Confirm working tree still holds the stale value and was never used.
5843            assert!(
5844                std::fs::read_to_string(repo.join("magi.toml"))
5845                    .unwrap()
5846                    .contains("candidates = 9")
5847            );
5848        }
5849
5850        #[test]
5851        fn linked_worktree_reuses_common_dir_cache_with_one_warm_git_spawn() {
5852            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5853            let bare = t.path().join("o.git");
5854            let wt = t.path().join("linked-wt");
5855            git(
5856                &repo,
5857                &["worktree", "add", "--detach", &wt.to_string_lossy()],
5858            );
5859
5860            let (cfg, (_, cold_git)) =
5861                crate::web::request_cost::measure_sync(|| Config::discover(&wt, None).unwrap().0);
5862            assert_eq!(cfg.graph.implementers, 2);
5863            assert_eq!(cold_git, 2);
5864
5865            let (values, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
5866                (0..10)
5867                    .map(|_| Config::discover(&wt, None).unwrap().0.graph.implementers)
5868                    .collect::<Vec<_>>()
5869            });
5870            assert!(values.iter().all(|&n| n == 2));
5871            assert_eq!(warm_git, 10);
5872
5873            push_remote_config(&bare, "trunk", "[graph]\ncandidates = 5\n");
5874            git(&wt, &["fetch", "origin"]);
5875            let (cfg, (_, moved_git)) =
5876                crate::web::request_cost::measure_sync(|| Config::discover(&wt, None).unwrap().0);
5877            assert_eq!(cfg.graph.implementers, 5);
5878            assert_eq!(moved_git, 2);
5879        }
5880
5881        #[test]
5882        fn deleted_or_retargeted_refs_never_reuse_stale_cache() {
5883            let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5884            let bare = t.path().join("o.git");
5885            assert_eq!(
5886                Config::discover(&repo, None).unwrap().0.graph.implementers,
5887                2
5888            );
5889
5890            // Deleting the tracking ref after warming must error, not reuse cache.
5891            git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5892            assert!(Config::discover(&repo, None).is_err());
5893
5894            // Restore tracking ref, create an alternate branch on remote, and
5895            // move `origin/HEAD` to point at it.
5896            git(&repo, &["fetch", "origin"]);
5897            git(&repo, &["checkout", "-b", "alt"]);
5898            std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 6\n").unwrap();
5899            git(&repo, &["add", "magi.toml"]);
5900            git(&repo, &["commit", "-m", "alt"]);
5901            git(&repo, &["push", "origin", "alt"]);
5902            git(&repo, &["fetch", "origin"]);
5903            let _ = bare;
5904            git(&repo, &["remote", "set-head", "origin", "alt"]);
5905            assert_eq!(
5906                Config::discover(&repo, None).unwrap().0.graph.implementers,
5907                6
5908            );
5909
5910            // Deleting `origin/HEAD` (with no [merge] base) must error.
5911            git(&repo, &["remote", "set-head", "origin", "-d"]);
5912            assert!(Config::discover(&repo, None).is_err());
5913        }
5914
5915        #[test]
5916        fn include_repository_reuses_extracted_tree_with_one_warm_git_spawn() {
5917            let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
5918            std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
5919            std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
5920            git(&repo, &["add", "-A"]);
5921            git(&repo, &["commit", "-m", "inc"]);
5922            git(&repo, &["push", "origin", "trunk"]);
5923            git(&repo, &["fetch", "origin"]);
5924            std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
5925
5926            let (cfg, (_, cold_git)) =
5927                crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5928            assert_eq!(cfg.graph.implementers, 2);
5929            // Batch read, absence proof and archive for the include tree.
5930            assert_eq!(cold_git, 3);
5931
5932            let (values, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
5933                (0..10)
5934                    .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5935                    .collect::<Vec<_>>()
5936            });
5937            assert!(values.iter().all(|&n| n == 2));
5938            assert_eq!(warm_git, 10);
5939        }
5940
5941        #[test]
5942        fn partial_clone_loads_promised_config_blob() {
5943            let (tmp, source) = fixture("[graph]\ncandidates = 2\n", "");
5944            let bare = tmp.path().join("o.git");
5945            git(&bare, &["config", "uploadpack.allowFilter", "true"]);
5946            let clone = tmp.path().join("partial");
5947            git(
5948                tmp.path(),
5949                &[
5950                    "clone",
5951                    "--no-local",
5952                    "--no-checkout",
5953                    "--filter=blob:none",
5954                    &bare.to_string_lossy(),
5955                    &clone.to_string_lossy(),
5956                ],
5957            );
5958            let oid = git_out(&source, &["rev-parse", "HEAD:magi.toml"]).unwrap();
5959            let missing = repository_git()
5960                .env("GIT_NO_LAZY_FETCH", "1")
5961                .args(["cat-file", "-e", oid.trim()])
5962                .current_dir(&clone)
5963                .output()
5964                .unwrap();
5965            assert!(!missing.status.success(), "fixture must omit the blob");
5966            assert_eq!(
5967                Config::discover(&clone, None).unwrap().0.graph.implementers,
5968                2
5969            );
5970        }
5971
5972        #[test]
5973        fn missing_config_blob_is_not_cached_as_an_absent_layer() {
5974            let (_tmp, repo) = fixture("[graph]\ncandidates = 2\n", "");
5975            let oid = git_out(&repo, &["rev-parse", "HEAD:magi.toml"]).unwrap();
5976            let oid = oid.trim();
5977            let blob = repo.join(".git/objects").join(&oid[..2]).join(&oid[2..]);
5978            let saved = blob.with_extension("saved");
5979            std::fs::rename(&blob, &saved).unwrap();
5980            assert!(Config::discover(&repo, None).is_err());
5981            std::fs::rename(saved, blob).unwrap();
5982            assert_eq!(
5983                Config::discover(&repo, None).unwrap().0.graph.implementers,
5984                2
5985            );
5986        }
5987
5988        #[test]
5989        fn a_cached_config_does_not_hide_a_missing_base_commit() {
5990            let (_tmp, repo) = fixture("[graph]\ncandidates = 2\n", "");
5991            assert_eq!(
5992                Config::discover(&repo, None).unwrap().0.graph.implementers,
5993                2
5994            );
5995            let oid = git_out(&repo, &["rev-parse", "HEAD"]).unwrap();
5996            let oid = oid.trim();
5997            let commit = repo.join(".git/objects").join(&oid[..2]).join(&oid[2..]);
5998            let saved = commit.with_extension("saved");
5999            std::fs::rename(&commit, &saved).unwrap();
6000            assert!(Config::discover(&repo, None).is_err());
6001            std::fs::rename(saved, commit).unwrap();
6002            assert_eq!(
6003                Config::discover(&repo, None).unwrap().0.graph.implementers,
6004                2
6005            );
6006        }
6007
6008        #[test]
6009        fn corrupt_cache_directory_without_manifest_is_not_trusted() {
6010            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6011            let sha = git_out(&repo, &["rev-parse", "refs/remotes/origin/trunk^{commit}"])
6012                .unwrap()
6013                .trim()
6014                .to_owned();
6015            let key = format!(
6016                "{sha}-{}-v{CACHE_MANIFEST_VERSION}",
6017                fnv_hex(&repo.to_string_lossy())
6018            );
6019            let bad_dir = repo.join(".git/magi/config").join(&key);
6020            std::fs::create_dir_all(&bad_dir).unwrap();
6021            std::fs::write(bad_dir.join("magi.toml"), "[graph]\ncandidates = 9\n").unwrap();
6022            std::fs::write(bad_dir.join(REPO_MARKER), repo.to_string_lossy().as_bytes()).unwrap();
6023
6024            // Must ignore the unmanifested directory and read the real commit.
6025            let (cfg, _) = Config::discover(&repo, None).unwrap();
6026            assert_eq!(cfg.graph.implementers, 2);
6027        }
6028
6029        #[test]
6030        fn resolve_remote_head_and_commit_cli_uses_one_git_process() {
6031            let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6032            let expected = git_out(&repo, &["rev-parse", "refs/remotes/origin/trunk^{commit}"])
6033                .unwrap()
6034                .trim()
6035                .to_owned();
6036            let (resolved, (_, git_calls)) = crate::web::request_cost::measure_sync(|| {
6037                resolve_remote_head_and_commit_cli(&repo, "origin").unwrap()
6038            });
6039            assert_eq!(resolved, ("trunk".to_owned(), expected));
6040            assert_eq!(git_calls, 1);
6041        }
6042
6043        #[test]
6044        fn standard_files_ref_backend_rejects_nonstandard_git_config() {
6045            let tmp = tempfile::tempdir().unwrap();
6046            let common = tmp.path().join("git");
6047            std::fs::create_dir_all(common.join("refs")).unwrap();
6048
6049            let check = |cfg: &str| {
6050                std::fs::write(common.join("config"), cfg).unwrap();
6051                is_standard_files_ref_backend(&common)
6052            };
6053
6054            assert!(check("[core]\n\trepositoryformatversion = 0\n"));
6055            assert!(check(
6056                "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tworktreeConfig = true\n\trefStorage = files\n\tobjectFormat = sha1\n"
6057            ));
6058            assert!(!check(
6059                "[core]\n\trepositoryformatversion = 1\n[extensions]\n\trefStorage = reftable\n"
6060            ));
6061            assert!(!check(
6062                "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tobjectFormat = sha256\n"
6063            ));
6064            assert!(!check(
6065                "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tunknownExt\n"
6066            ));
6067            assert!(!check(
6068                "[core]\n\trepositoryformatversion = 1\n[extensions] refStorage = reftable\n"
6069            ));
6070            assert!(!check(
6071                "[core]\n\trepositoryformatversion = 0\n[include]\n\tpath = extra.cfg\n"
6072            ));
6073            assert!(!check(
6074                "[core]\n\trepositoryformatversion = 0\n\tfoo = bar\\\nbaz\n"
6075            ));
6076        }
6077    }
6078
6079    #[test]
6080    fn github_language_defaults_to_english_and_accepts_japanese() {
6081        let default: Graph = toml::from_str("").unwrap();
6082        assert_eq!(default.github_language, "en");
6083        assert!(default.github_english() && default.language_gate());
6084        let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
6085        assert!(!ja.github_english() && !ja.language_gate());
6086        // Independent of the operator-facing language.
6087        let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
6088        assert!(only_ops.language_gate());
6089        let off: Graph = toml::from_str("github_text_guard = false").unwrap();
6090        assert!(!off.language_gate() && off.github_english());
6091        assert!(Config::starter_toml().contains("github_language = \"en\""));
6092    }
6093}