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