magi/config.rs
1//! Run configuration: the agent roster, the shape of the graph, and the
2//! blindness / verification policy.
3//!
4//! Layers, lowest precedence first: `<config_dir>/magi/config.toml` (machine),
5//! `.magi/config.toml`, `magi.toml`. With none, built-in defaults apply, the
6//! agent roster derived from the agent CLIs actually installed on this
7//! machine. `--config <path>` replaces the whole stack with that one file.
8//!
9//! **The repository layers are read from `<remote>/<base>`, never from the
10//! working tree.** A primary checkout is often stale or on a detached HEAD, so
11//! a gate read from it can be older than the one the branch under review is
12//! cut from (run ce6e failed on a gate step `origin/main` had already
13//! dropped). `git show <sha>:magi.toml` of the remote-tracking ref's commit is
14//! written to a content-addressed directory under the git common dir
15//! (`<common>/magi/config/<sha>-<hash of repo>/`, temp dir when that is not
16//! writable) and loaded from there.
17//!
18//! `remote` and `base` are themselves in the file, so they are resolved in a
19//! fixed order, first hit wins:
20//!
21//! 1. `[merge] base` / `remote` of the machine layer, rendered as a real load
22//! would (env templates, includes);
23//! 2. the same keys, read minimally (only `[merge]`, nothing deserialized into
24//! `Config`) from the checkout's `magi.toml`, then `.magi/config.toml` -
25//! only to *locate* the ref; an unreadable file is ignored;
26//! 3. `remote` defaults to `origin`, `base` to what
27//! `refs/remotes/<remote>/HEAD` points at.
28//!
29//! [`Config::discover`] is synchronous and reads the remote-tracking ref as it
30//! is (`daemon::fetch_loop` keeps it fresh); [`Config::discover_fetched`] runs
31//! `git fetch` first and is what every path that starts work uses. A failed
32//! fetch, a missing ref or an unresolvable base is an **error**, never a
33//! silent fall back to the working tree or a local branch. Two cases are not
34//! that: an explicit `--config`, and a `repo` that is not a git working tree
35//! at all (no branch exists, so nothing can be stale).
36//!
37//! A repository layer that declares `include = [...]` gets the whole tree of
38//! that commit extracted, so relative includes resolve against the same
39//! commit. The directory is built beside its name and renamed in, so a
40//! concurrent `discover` never reads a half-written layer.
41use std::collections::BTreeMap;
42use std::path::{Path, PathBuf};
43
44use anyhow::{Context as _, Result, bail};
45use serde::{Deserialize, Serialize};
46
47/// Which CLI drives an agent.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
49#[serde(rename_all = "lowercase")]
50pub enum AgentKind {
51 /// Anthropic Claude Code (`claude -p`).
52 Claude,
53 /// opencode (`opencode run`).
54 Opencode,
55 /// Antigravity CLI (`agy -p`). Gemini CLI is deliberately absent: Google
56 /// retired the standalone client for individual accounts in favour of this
57 /// one, so an adapter for it would be dead code on a live machine.
58 Antigravity,
59 /// OpenAI Codex CLI (`codex exec`). The one roster member with a real
60 /// read-only mode: `--sandbox read-only` is enforced by the CLI, not by
61 /// the prompt.
62 Codex,
63 /// oh-my-pi (`omp -p --mode=json`). Another CLI with no read-only mode of
64 /// its own - `--auto-approve` gates reads and writes together - so a
65 /// read-only seat rests on the prompt and on the worktree discipline the
66 /// other non-codex seats already rely on. It is also the roster member that
67 /// reaches DeepSeek, whose models ship in `omp`'s own catalog.
68 Omp,
69 /// Arbitrary command. The escape hatch, and what the test suite drives.
70 Command,
71}
72
73impl AgentKind {
74 /// Executable that must be on `PATH` for this kind, if any.
75 pub fn program(self) -> Option<&'static str> {
76 match self {
77 Self::Claude => Some("claude"),
78 Self::Opencode => Some("opencode"),
79 Self::Antigravity => Some("agy"),
80 Self::Codex => Some("codex"),
81 Self::Omp => Some("omp"),
82 Self::Command => None,
83 }
84 }
85
86 /// Lowercase name as written in the config file.
87 pub fn as_str(self) -> &'static str {
88 match self {
89 Self::Claude => "claude",
90 Self::Opencode => "opencode",
91 Self::Antigravity => "antigravity",
92 Self::Codex => "codex",
93 Self::Omp => "omp",
94 Self::Command => "command",
95 }
96 }
97
98 /// Every kind the roster can name, in display order.
99 ///
100 /// This is what `magi doctor` lists, and it has to be one list rather than
101 /// the same set typed out again wherever a kind is enumerated. The last
102 /// time it was typed out twice, `omp` was added as a roster member and the
103 /// doctor output went on saying the machine had four CLIs - which reads as
104 /// "that agent is not installed" to the person the command exists for.
105 pub const ALL: [Self; 6] = [
106 Self::Claude,
107 Self::Opencode,
108 Self::Antigravity,
109 Self::Codex,
110 Self::Omp,
111 Self::Command,
112 ];
113}
114
115/// How the prompt reaches the agent process.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
117#[serde(rename_all = "lowercase")]
118pub enum Delivery {
119 /// Piped on stdin.
120 Stdin,
121 /// Passed as a positional argument. Beware OS command-line limits.
122 Argv,
123 /// Written to a file; the agent is told to read it. No length limit.
124 File,
125}
126
127/// One addressable agent in the roster.
128#[derive(Debug, Clone, Deserialize, Serialize)]
129#[serde(deny_unknown_fields)]
130pub struct AgentSpec {
131 /// Stable identifier used by `[roles]` and by the stats tables.
132 pub id: String,
133 /// Which CLI to drive.
134 pub kind: AgentKind,
135 /// Model passed through to the CLI (`--model` / `-m`). CLI default if unset.
136 #[serde(default)]
137 pub model: Option<String>,
138 /// `kind = "command"` only: argv. Supports `{prompt_file}`, `{cwd}`,
139 /// `{label}`, `{session}` placeholders.
140 #[serde(default)]
141 pub command: Vec<String>,
142 /// Extra arguments appended to the built command line.
143 #[serde(default)]
144 pub extra_args: Vec<String>,
145 /// Extra environment variables for the child process.
146 #[serde(default)]
147 pub env: BTreeMap<String, String>,
148 /// Override the per-kind prompt delivery default.
149 #[serde(default)]
150 pub prompt_delivery: Option<Delivery>,
151}
152
153impl AgentSpec {
154 /// Default prompt delivery for this agent.
155 ///
156 /// `opencode` and `agy` take the prompt as an argument, which on Windows
157 /// caps out around 32 KiB — well under a judging prompt carrying three
158 /// patches — so both get a file instead.
159 pub fn delivery(&self) -> Delivery {
160 self.prompt_delivery.unwrap_or(match self.kind {
161 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
162 // `codex exec -` reads the prompt from stdin, so the whole
163 // instruction arrives without an argv length limit and without a
164 // tool round-trip to open a file.
165 AgentKind::Codex => Delivery::Stdin,
166 // `omp -p` reads the prompt from stdin too, and a judging prompt
167 // carrying three patches is well past the Windows argv cap, so this
168 // is the only delivery that works for every node.
169 AgentKind::Omp => Delivery::Stdin,
170 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
171 })
172 }
173
174 /// Human-facing label, e.g. `opus (claude:opus)`.
175 pub fn display(&self) -> String {
176 match &self.model {
177 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
178 None => format!("{} ({})", self.id, self.kind.as_str()),
179 }
180 }
181}
182
183/// A standalone seat's agent: one roster id, or an ordered fallback chain.
184///
185/// The string form is what every existing config uses and serializes back as
186/// a string; the array form tries each id at most once, in order, moving on
187/// when a call ends in quota or fails (see [`crate::agent::pick_chain`]).
188/// An empty string or array is the same as unset.
189#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
190#[serde(untagged)]
191pub enum AgentChoice {
192 /// One agent id.
193 One(String),
194 /// Ordered fallback chain of agent ids.
195 Chain(Vec<String>),
196}
197
198impl AgentChoice {
199 /// The ids named, in order, with blanks dropped. Empty means unset.
200 pub fn ids(&self) -> Vec<&str> {
201 let all: Vec<&str> = match self {
202 Self::One(id) => vec![id.as_str()],
203 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
204 };
205 all.into_iter()
206 .map(str::trim)
207 .filter(|id| !id.is_empty())
208 .collect()
209 }
210
211 /// The first id named, if any.
212 pub fn primary(&self) -> Option<&str> {
213 self.ids().into_iter().next()
214 }
215}
216
217impl From<&str> for AgentChoice {
218 fn from(id: &str) -> Self {
219 Self::One(id.to_owned())
220 }
221}
222
223/// The first id of an optional choice: what a single-seat caller resolves.
224pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
225 choice.and_then(AgentChoice::primary)
226}
227
228/// Explicit role assignment. Empty lists are filled in by
229/// [`Config::resolve_roles`] by rotating the roster.
230#[derive(Debug, Clone, Default, Deserialize, Serialize)]
231#[serde(deny_unknown_fields, default)]
232pub struct Roles {
233 /// Agents that implement the task, one worktree each.
234 pub implementers: Vec<String>,
235 /// Agents that rank the candidates blind.
236 pub judges: Vec<String>,
237 /// Agents that review the winning patch.
238 pub reviewers: Vec<String>,
239 /// Agent that applies review findings. Defaults to the winner's author.
240 ///
241 /// Accepts one id or an ordered array of ids: a fallback chain, see
242 /// [`AgentChoice`]. The review loop, the gate-fix round, `land`'s fix
243 /// rounds and the rebase conflict round move to the next id when one
244 /// errors, hits its quota or answers nothing usable; each id is tried at
245 /// most once per call, and once a fallback answered, the rest of the run
246 /// starts from it (see `crate::fixer`). Unset keeps the winner's author.
247 pub fixer: Option<AgentChoice>,
248 /// Agent that answers the standing chat's turns (`src/talk.rs`).
249 ///
250 /// Unset picks a `claude` seat, else the first runnable agent in roster
251 /// order (see [`crate::agent::pick`]) - which is roster *order*, not a
252 /// judgement about who converses well. Naming one here matters once an
253 /// agent is also sitting as a judge: the chat is opened far more often
254 /// than any single competition, and every open competes with that judge
255 /// seat for the same account's concurrency. A timeout on an ordinary chat
256 /// turn traced to exactly this - `opus` triple-booked as chatter and judge
257 /// - is what this field exists to let an operator break apart.
258 ///
259 /// Accepts one id or an ordered array of ids: a fallback chain, see
260 /// [`AgentChoice`].
261 pub chatter: Option<AgentChoice>,
262 /// Agent that arranges the queue between polls: `crate::conduct`'s single
263 /// seat, called once per cycle to decide a runnable task's `blocked_by`
264 /// and how a stalled or finished task recovers.
265 ///
266 /// The same precedent as [`Self::chatter`] for a seat that stands alone
267 /// rather than rotating through the roster - resolved through
268 /// [`crate::agent::pick`], so unset falls back to its own default order
269 /// (a claude seat, else the first runnable agent) rather than reusing a
270 /// judge or reviewer seat that the conductor's own poll-cycle cadence
271 /// would otherwise compete with for the same account's concurrency.
272 ///
273 /// Accepts a string or a fallback chain, like [`Self::chatter`].
274 pub conductor: Option<AgentChoice>,
275 /// Seats for the design-deliberation stage `graph::Runner::advise` runs
276 /// before `implement`: independent, read-only design proposals gathered
277 /// once a run has a settled task instruction and before any implementer
278 /// touches the repository.
279 ///
280 /// Empty falls back to `judges` rather than to the whole roster: a panel
281 /// trusted to rank patches independently is exactly the panel worth
282 /// asking to sketch a design independently, and an operator who has
283 /// already thought about judge diversity gets advisor diversity for free
284 /// instead of a fourth roster to maintain.
285 pub advisors: Vec<String>,
286 /// Agent that blends [`Self::advisors`]' proposals into the one design
287 /// brief `graph::Runner::synthesize_brief` carries into every
288 /// implementer's prompt.
289 ///
290 /// The same precedent as [`Self::chatter`] and [`Self::conductor`] for a
291 /// seat that stands alone rather than rotating through the roster -
292 /// resolved through [`crate::agent::pick`], so unset falls back to its
293 /// own default order (a claude seat, else the first runnable agent in
294 /// roster order) - exactly today's behavior, unchanged by leaving this
295 /// field out.
296 ///
297 /// Accepts a string or a fallback chain, like [`Self::chatter`].
298 pub synthesizer: Option<AgentChoice>,
299}
300
301/// Graph shape and limits.
302#[derive(Debug, Clone, Deserialize, Serialize)]
303#[serde(deny_unknown_fields, default)]
304pub struct Graph {
305 /// Parallel implementations of the same task (the number of implementer
306 /// seats; pairs with [`Roles::implementers`]). **One by default.**
307 ///
308 /// Formerly `candidates`, still read as a deprecated alias.
309 ///
310 /// Competition is the thing magi is for, and it is still here - it is just
311 /// no longer what every task buys without being asked. Three days and 13
312 /// runs on this repository, which is the workload these numbers are drawn
313 /// from:
314 ///
315 /// - **0 of 13** competed runs reached a merge. Everything that landed in
316 /// that window went through `magi review` - the cheap half, no
317 /// competition - and passed on the first try.
318 /// - The judges' first choices **split 73% of the time** (8 of 11
319 /// tallies). Candidates that close together make the ranking a weak
320 /// signal for what it costs to produce.
321 /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
322 /// review 28min, **verify 5min** - and verify is the node that caught a
323 /// defect every reviewer had passed as clean. The cheapest step is the
324 /// one that earns its place every time.
325 ///
326 /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
327 /// single-seat default would have shipped the worse implementation in
328 /// roughly a quarter of them. That is exactly why this is a *default* and
329 /// not a removal - `magi run --candidates N` and a per-task seat count are
330 /// how a task that deserves a competition gets one.
331 ///
332 /// A single-candidate run needs no special case: `Runner::review`'s doc
333 /// records that `execute` already degrades to implement -> review -> gate
334 /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
335 /// no two first choices to reconcile and `vote` returns early.
336 #[serde(alias = "candidates")]
337 pub implementers: usize,
338 /// Independent judges.
339 pub judges: usize,
340 /// Deliberation rounds when the judges' first choices disagree.
341 pub deliberate_rounds: usize,
342 /// Reviewers per review round. **Three by default** - the smallest panel
343 /// a lens cycle (see [`crate::prompt::Lens`]) covers exactly once, so the
344 /// default panel reads the patch for spec compliance, regressions, and
345 /// simplicity without repeating an angle. Review is also the one stage
346 /// [`Self::implementers`]'s doc describes as running on every task
347 /// regardless of competition, which is what makes a panel worth its cost
348 /// here even though `implementers` itself defaults to one.
349 pub reviewers: usize,
350 /// Maximum review+fix rounds before the run is declared blocked.
351 pub review_rounds: usize,
352 /// Fix rounds a failing `verify.gate` gets before the run is blocked. The
353 /// fixer is handed the gate's own output; `0` keeps the old behaviour of
354 /// blocking on the first red gate. Independent of [`Self::review_rounds`]
355 /// so a run that spent its review budget can still repair a one-line gate
356 /// failure.
357 pub gate_fix_rounds: usize,
358 /// Maximum agent processes running at once.
359 pub max_parallel: usize,
360 /// Language for the prose the agents write (`en` / `ja` / any language name).
361 pub language: String,
362 /// Keep one CLI conversation per seat, so a judge remembers its own
363 /// argument across deliberation rounds and the fixer remembers its own
364 /// implementation across review rounds.
365 ///
366 /// Sessions are scoped to a *seat*, never to an agent id: the same model
367 /// sitting as implementer and as judge gets two unrelated conversations,
368 /// which is what keeps blind judging blind.
369 pub sessions: bool,
370 /// Per-node timeouts, seconds.
371 pub timeout_implement: u64,
372 /// Per-node timeouts, seconds.
373 pub timeout_judge: u64,
374 /// Per-node timeouts, seconds.
375 pub timeout_review: u64,
376 /// Timeout for `verify.e2e` and `verify.gate`, seconds. Separate from
377 /// [`Self::timeout_review`] so shrinking a reviewer's budget cannot
378 /// silently shrink a real-machine command's budget too — the two used to
379 /// share `timeout_review`, and turning a slow reviewer down cut the
380 /// timeout `cargo test --all-targets` runs under along with it. When
381 /// omitted, preserves legacy configurations by using
382 /// [`Self::timeout_review`]. Set an explicit value to make verification
383 /// independent of later review-seat budget changes.
384 pub timeout_verify: Option<u64>,
385 /// Per-node timeouts, seconds.
386 pub timeout_fix: u64,
387 /// Wall-clock limit for one turn of [`crate::talk`]'s standing
388 /// conversation, seconds.
389 ///
390 /// An hour: the operator is not watching this turn resolve in real time,
391 /// so the budget can match what the work - reading files, running
392 /// commands, checking their output - actually needs rather than what a
393 /// person waiting on a phone can tolerate.
394 pub timeout_talk: u64,
395 /// Retries for an agent invocation that fails or returns nothing usable.
396 pub retries: usize,
397 /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
398 pub worktree_root: Option<PathBuf>,
399 /// After the pull request is open, keep going: watch its checks and
400 /// reviews, run a fix round when they are unhappy, and ask to merge.
401 ///
402 /// On, because stopping at an open pull request left the operator doing
403 /// the watching by hand - six times in the session this was built in - and
404 /// that is the work the loop exists to take. It only engages for
405 /// `merge = "pr"`; every other merge mode ends the run as before.
406 ///
407 /// Turning this on does **not** hand magi the merge button:
408 /// [`Graph::land_approval`] is on too, and nothing merges without an
409 /// explicit answer. Setting both to their non-defaults is the only way to
410 /// get an unattended merge, and it has to be chosen twice.
411 pub land: bool,
412 /// Land rounds - watch, fix, push - before the run is left for a human.
413 pub land_rounds: usize,
414 /// Ask the owner before merging, showing what is about to land.
415 ///
416 /// On, and it is what makes `land` safe to have on: the question carries a
417 /// rendered panel - the diffstat, the patch, the checks, the review
418 /// comments that were addressed, and the subject the squash will use - so
419 /// the decision is made on evidence rather than on trust, from wherever
420 /// the operator happens to be.
421 ///
422 /// Silence is a hold. An unanswered approval never merges, and neither
423 /// does any answer other than the word `merge`.
424 pub land_approval: bool,
425 /// Ask the owner before merging a run whose review loop handed off over a
426 /// contested finding: the last round ended with a Major-or-above finding
427 /// still open *and* at least one reviewer's final vote (after
428 /// reconsideration) was reject. Findings raised in the last round are
429 /// never fixed or re-reviewed, so this is the one case an unattended
430 /// merge would land over a reviewer's explicit objection.
431 ///
432 /// On. Interaction with [`Self::land_approval`]: when that is on, every
433 /// merge is asked about and this key changes nothing. When it is off,
434 /// this key alone decides whether a contested hand-off is asked about
435 /// (the question says why); every other run still merges unattended.
436 /// Read at land time, so turning it off restores the unattended merge at
437 /// once. The pull request is opened either way; only the merge waits.
438 pub hold_contested_merge: bool,
439 /// After a run's pull request merges, file the findings its last review
440 /// round left open as follow-up tasks (`crate::followup`) instead of
441 /// letting them vanish with the merge: every Major-or-above finding, and
442 /// every finding of a seat whose final vote was reject. Other Minor/Nit
443 /// findings are only listed in the pull-request comment. Does not affect
444 /// whether the merge happens. On; best-effort, a failure is a run event.
445 pub file_followups: bool,
446 /// How long to wait for an owner to answer a question before the run is
447 /// abandoned, seconds. A parked run costs nothing, so this is generous;
448 /// it exists so a forgotten question cannot pin a worktree forever.
449 pub answer_timeout: u64,
450 /// What a round does when one or more reviewer seats never answered
451 /// (timeout, crash, unparsable output).
452 pub incomplete_review: IncompleteReviewPolicy,
453 /// Run `verify.e2e` on every round, even one that already has blocking
454 /// findings and another round left to try.
455 ///
456 /// Off by default: a round with a blocking finding and rounds still left
457 /// is going back to the fixer regardless of what `verify.e2e` says, so
458 /// running it first only spends the round's slowest step (minutes, on a
459 /// Rust repo's `cargo test --all-targets`) on a head about to be
460 /// rewritten anyway. `verify.e2e` still runs once a round has no
461 /// blocking findings left (a round cannot go `clean` without it) and the
462 /// final `verify.gate` always runs on the actual tree that would land —
463 /// deferring is about *when* e2e runs mid-loop, never about skipping it.
464 ///
465 /// Set this to restore the old every-round diagnostic behaviour: e2e
466 /// output from a round that still has blocking findings is occasionally
467 /// useful on its own (a runtime failure a reviewer's panel would not
468 /// have caught by reading), and this is the way back to seeing it every
469 /// round instead of only once the panel has nothing left to flag.
470 pub e2e_every_round: bool,
471 /// Run the design-deliberation stage before `implement`: independent
472 /// advisor seats each sketch a design, and (when at least one produced a
473 /// usable proposal) a synthesis blends them into a brief carried in the
474 /// implementer's prompt. See `graph::Runner::advise`.
475 ///
476 /// On by default. A design sketch is a few paragraphs an agent can write
477 /// without touching the repository, where a full implementation is a
478 /// tool loop that re-reads the codebase on every turn - so three
479 /// sketches, gathered once before `implement` starts, cost a fraction of
480 /// a fourth candidate and buy back a form of the same disagreement
481 /// [`Self::implementers`]'s doc describes moving away from being the
482 /// default, on every run rather than only the ones an operator remembers
483 /// to ask for with `--implementers`.
484 pub advise: bool,
485 /// How many independent design proposals the deliberation stage gathers.
486 /// **Three by default** - the same number [`Self::implementers`]'s doc
487 /// names as the point where a fourth judge's first choice stopped
488 /// changing the tally.
489 pub advisors: usize,
490}
491
492impl Default for Graph {
493 fn default() -> Self {
494 Self {
495 implementers: 1,
496 judges: 3,
497 deliberate_rounds: 1,
498 reviewers: 3,
499 review_rounds: 6,
500 gate_fix_rounds: 1,
501 max_parallel: 4,
502 language: "en".to_owned(),
503 sessions: true,
504 timeout_implement: 3600,
505 timeout_judge: 1200,
506 timeout_review: 1200,
507 timeout_verify: None,
508 timeout_fix: 1800,
509 timeout_talk: 3600,
510 retries: 1,
511 worktree_root: None,
512 land: true,
513 land_rounds: 4,
514 land_approval: true,
515 hold_contested_merge: true,
516 file_followups: true,
517 answer_timeout: 86_400,
518 incomplete_review: IncompleteReviewPolicy::Block,
519 e2e_every_round: false,
520 advise: true,
521 advisors: 3,
522 }
523 }
524}
525
526impl Graph {
527 /// Effective machine-command budget. Older configuration files had only
528 /// `timeout_review`, which also governed verification, so absence is a
529 /// compatibility fallback rather than a new 1200-second default.
530 pub fn verify_timeout(&self) -> u64 {
531 self.timeout_verify.unwrap_or(self.timeout_review)
532 }
533}
534
535/// What a review round does when a reviewer seat never answered.
536///
537/// A round where half the panel timed out is not evidence of a clean patch —
538/// it is evidence of nothing. The default refuses to call that clean; `warn`
539/// exists for an operator who would rather keep a flaky seat from stalling
540/// every run, and accepts that the gap is on them to read in the report.
541#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
542#[serde(rename_all = "lowercase")]
543pub enum IncompleteReviewPolicy {
544 /// A round with a missing seat is never `clean`: with nothing raised to
545 /// fix, the round is re-reviewed instead of gating; with the max rounds
546 /// exhausted, the run is left `Blocked` rather than declared ready.
547 Block,
548 /// A round with a missing seat can still gate as clean, once every seat
549 /// that *did* answer raised nothing blocking and verification is green.
550 /// The record keeps the gap visible (`magi show`, `magi stats`) even
551 /// though the run does not wait on it.
552 Warn,
553}
554
555/// What to do when vendor-identifying text is found in material shown to judges.
556#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
557#[serde(rename_all = "lowercase")]
558pub enum LeakPolicy {
559 /// Record the leak, show the patch unmodified.
560 Warn,
561 /// Replace the token with `[REDACTED]` in the presented patch.
562 Redact,
563 /// Abort the run.
564 Fail,
565}
566
567/// Blindness policy.
568///
569/// Commit messages and candidate summaries are *always* stripped of
570/// attribution trailers and redacted — that is where signatures actually
571/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
572/// redaction would corrupt the artifact under judgement.
573#[derive(Debug, Clone, Deserialize, Serialize)]
574#[serde(deny_unknown_fields, default)]
575pub struct Blind {
576 /// Install a per-worktree `commit-msg` hook that deletes attribution
577 /// trailers before they can land in a candidate's history.
578 pub commit_msg_hook: bool,
579 /// Literal, case-insensitive substrings. A line containing any of them is
580 /// dropped from commit messages and summaries; the `commit-msg` hook is
581 /// generated from the same list.
582 pub strip_lines: Vec<String>,
583 /// Case-insensitive substrings that identify a vendor or model.
584 pub vendor_tokens: Vec<String>,
585 /// Policy for vendor tokens found in the patch body.
586 pub on_leak: LeakPolicy,
587 /// Seed for label assignment and per-judge presentation order. Derived from
588 /// the run id when unset; set it to make a run reproducible.
589 pub seed: Option<u64>,
590}
591
592impl Default for Blind {
593 fn default() -> Self {
594 Self {
595 commit_msg_hook: true,
596 strip_lines: [
597 "Co-Authored-By:",
598 "Signed-off-by:",
599 "Assisted-by:",
600 "Generated-by:",
601 "Generated with",
602 "\u{1f916}",
603 ]
604 .iter()
605 .map(|s| (*s).to_owned())
606 .collect(),
607 vendor_tokens: [
608 "claude",
609 "anthropic",
610 "codex",
611 "openai",
612 "chatgpt",
613 "gemini",
614 "grok",
615 "xai",
616 "copilot",
617 "opencode",
618 "qoder",
619 "cursor",
620 "\u{1f916}",
621 ]
622 .iter()
623 .map(|s| (*s).to_owned())
624 .collect(),
625 on_leak: LeakPolicy::Warn,
626 seed: None,
627 }
628 }
629}
630
631/// Shell commands that gate the winner.
632#[derive(Debug, Clone, Default, Deserialize, Serialize)]
633#[serde(deny_unknown_fields, default)]
634pub struct Verify {
635 /// Run in the winner's worktree once per review round. Its output is fed
636 /// back to the fixer. This is the "real machine" leg of the review.
637 pub e2e: Vec<String>,
638 /// Final gate. Must all exit 0 before a merge is attempted.
639 pub gate: Vec<String>,
640 /// Mechanical fixers (formatters) run in the winner's worktree just before
641 /// `gate`, after review is clean. Anything they change is committed as one
642 /// neutral-identity commit so the gate and the PR see it. A command that
643 /// fails or times out is a warning, never a failed run: the gate stays the
644 /// single arbiter. Empty (the default) turns the feature off. Runs under
645 /// `graph.verify_timeout()` per command, like the gate. Meant for light
646 /// tools: it is not scanned for `CARGO_TARGET_DIR`, and it should be
647 /// idempotent since a resumed run may repeat it.
648 #[serde(default)]
649 pub pre_gate: Vec<String>,
650 /// Shell used to run the commands above. Defaults to `sh -c`, or
651 /// `cmd /C` when `sh` is not on `PATH`.
652 pub shell: Option<Vec<String>>,
653}
654
655impl Verify {
656 /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
657 /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
658 /// this reads back. One rendering is enough - they all set the same
659 /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
660 /// command is checked before the gate because the e2e rebuilds the crate.
661 pub fn cache_dir(&self) -> Option<PathBuf> {
662 self.e2e
663 .iter()
664 .chain(self.gate.iter())
665 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
666 }
667}
668
669/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
670///
671/// The numbers below come from one incident, not from theory: a machine with
672/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
673/// Three multi-gigabyte classes of junk accumulated side by side - per-run
674/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
675/// each verify round and each implementation wave recompiles the derived
676/// section of the project into, and the outputs of runs that were removed but
677/// whose folders nobody deleted.
678#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
679#[serde(deny_unknown_fields, default)]
680pub struct Disk {
681 /// Free space, in bytes, below which no new run may start: the daemon and
682 /// the `magi run` gate answer with "the disk is full" instead of letting
683 /// the graph fill it the rest of the way. `0` turns the gate off.
684 ///
685 /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
686 /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
687 /// competition triggers and small enough that a 1 TB disk with 100 GB free
688 /// is nowhere near the threshold.
689 pub min_free_bytes: u64,
690 /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
691 /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
692 /// worktrees removed. `0` turns the janitor off.
693 ///
694 /// Default true.
695 pub auto_fold: bool,
696 /// How old a finished run must be before the janitor folds it, seconds.
697 ///
698 /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
699 /// run that `Ready` a week ago is worktrees holding a compile each. Six
700 /// hours is long enough that nobody loses an answer in the gap between
701 /// reading the report and starting from it, and short enough that a backlog
702 /// cannot pile up across two nights.
703 pub fold_grace_secs: u64,
704 /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
705 /// verify commands), in bytes. When the janitor runs and the cache is over
706 /// it, files are dropped oldest-first until it is not. `0` turns pruning
707 /// off - the cache then only ever grows, which is the operator's call.
708 ///
709 /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
710 /// shared cache on top of ~16 GB in the primary target directory and 6.7-
711 /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
712 /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
713 /// pruning only costs the rebuild of the dropped files, not of the world)
714 /// without letting one addled cache swallow the machine.
715 pub cache_limit_bytes: u64,
716}
717
718impl Default for Disk {
719 fn default() -> Self {
720 Self {
721 min_free_bytes: 8 * 1024 * 1024 * 1024,
722 auto_fold: true,
723 fold_grace_secs: 6 * 60 * 60,
724 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
725 }
726 }
727}
728
729/// What to do with the winning branch.
730#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
731#[serde(rename_all = "lowercase")]
732pub enum MergeMode {
733 /// Leave the branch alone and print the merge command matching
734 /// [`Merge::style`].
735 None,
736 /// Merge into the base branch in the primary worktree, using
737 /// [`Merge::style`].
738 Local,
739 /// Push the branch and open a PR with `gh pr create`. Landing this PR
740 /// (`[graph] land`) always squashes — see `land`'s module doc — so
741 /// [`Merge::style`] does not apply here.
742 Pr,
743}
744
745/// How the winning branch is attached to the base branch: what
746/// `mode = "local"` runs, and what `mode = "none"`'s printed guidance tells
747/// the operator to run by hand.
748///
749/// Read from configuration rather than asked of the repository at run time
750/// (e.g. `gh api repos/{owner}/{repo}/rulesets`) for two reasons: it keeps
751/// `mode = "none"`'s guidance a pure function of `RunState`, assertable in a
752/// unit test the same way `land::decide` is kept pure (see that module's
753/// doc), and it works for a base branch that is not hosted on GitHub, or not
754/// reachable at all, at the moment the report is rendered. An operator whose
755/// base branch enforces a ruleset already knows what it allows; declaring it
756/// once here is cheaper than magi re-discovering it, with a network call, on
757/// every render.
758#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
759#[serde(rename_all = "lowercase")]
760pub enum MergeStyle {
761 /// `git merge --no-ff`: every candidate commit lands, plus a merge
762 /// commit that records the merge as its own event in history. Rejected
763 /// by a base branch whose ruleset requires linear history or forbids
764 /// merge commits outright.
765 #[default]
766 Merge,
767 /// `git merge --squash` followed by a commit under an explicit message:
768 /// every candidate commit folds into one, and none of the candidate's
769 /// own placeholder subjects (`magi: candidate A (uncommitted work)`)
770 /// reach the base branch. No merge commit, so this satisfies a linear-
771 /// history ruleset.
772 Squash,
773 /// A fast-forward-only merge: every candidate commit lands verbatim, in
774 /// order, with no merge commit. Only succeeds because the winner was
775 /// already rebased onto the tracked base tip before this runs (see
776 /// `Runner::sync_to_base`) — equivalent to GitHub's "rebase and merge"
777 /// once that has happened.
778 Rebase,
779}
780
781/// Merge policy.
782#[derive(Debug, Clone, Deserialize, Serialize)]
783#[serde(deny_unknown_fields, default)]
784pub struct Merge {
785 /// Default is [`MergeMode::None`]: magi never touches your base branch
786 /// unless you ask it to.
787 pub mode: MergeMode,
788 /// Base branch. Defaults to the branch checked out when the run started.
789 pub base: Option<String>,
790 /// How the winner is attached to `base`; see [`MergeStyle`]. Ignored by
791 /// `mode = "pr"`.
792 pub style: MergeStyle,
793 /// Remote for `mode = "pr"`.
794 pub remote: String,
795 /// After a `mode = "pr"` run lands, open a `chore/release-vX.Y.Z` pull
796 /// request sized to the change by an agent's own judgement, so a version
797 /// bump does not depend on a human remembering to cut one.
798 ///
799 /// Only acts on Rust repositories (a `Cargo.toml` at the root of the base
800 /// branch); on any other repository it is a no-op that records one event.
801 ///
802 /// On by default. **Turning this off means a merge landed from the phone
803 /// never becomes a release**, so `POST /api/upgrade` keeps reporting
804 /// "already on the newest release" against a `main` that has moved past
805 /// it - the same gap this feature exists to close. Only for a repository
806 /// that wants to keep cutting releases by hand.
807 pub release_bump: bool,
808}
809
810impl Default for Merge {
811 fn default() -> Self {
812 Self {
813 mode: MergeMode::None,
814 base: None,
815 style: MergeStyle::default(),
816 remote: "origin".to_owned(),
817 release_bump: true,
818 }
819 }
820}
821
822/// How magi keeps itself current.
823#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
824#[serde(rename_all = "lowercase")]
825pub enum UpdateMode {
826 /// Never check.
827 Off,
828 /// Check in the background and print a one-line banner when a newer
829 /// release exists.
830 Notify,
831 /// Check and install silently.
832 Install,
833}
834
835/// Self-update policy.
836#[derive(Debug, Clone, Deserialize, Serialize)]
837#[serde(deny_unknown_fields, default)]
838pub struct Update {
839 /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
840 pub mode: UpdateMode,
841 /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
842 pub interval: Option<String>,
843}
844
845impl Default for Update {
846 fn default() -> Self {
847 Self {
848 mode: UpdateMode::Notify,
849 interval: None,
850 }
851 }
852}
853
854/// Who performs the release after a `chore/release-vX.Y.Z` pull request merges.
855#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
856#[serde(rename_all = "lowercase")]
857pub enum ReleaseMode {
858 /// The repository's own workflows do (`auto-tag.yml` then `release.yml`),
859 /// and the release pull request merges on its checks.
860 #[default]
861 Actions,
862 /// magi does, from this machine: no CI is awaited, the owner approves the
863 /// merge, and magi then tags and runs [`Release::commands`]. See
864 /// [`crate::release_local`].
865 Local,
866}
867
868/// `[release]`: releasing without GitHub Actions. Opt-in per repository.
869#[derive(Debug, Clone, Deserialize, Serialize)]
870#[serde(deny_unknown_fields, default)]
871pub struct Release {
872 /// [`ReleaseMode::Actions`] (default: nothing changes) or
873 /// [`ReleaseMode::Local`].
874 pub mode: ReleaseMode,
875 /// Shell commands run in order, from a clean checkout of the merge commit,
876 /// once the tag is pushed. The first failure stops the list. They see
877 /// `MAGI_RELEASE_VERSION`, `MAGI_RELEASE_TAG`, `MAGI_RELEASE_COMMIT` and
878 /// `MAGI_RELEASE_PR` in the environment; `{{ ... }}` cannot carry the
879 /// version because teravars renders the whole file before any release
880 /// exists. Only read when `mode = "local"`.
881 pub commands: Vec<String>,
882 /// Minutes each command may run before it is killed and counted as failed.
883 pub timeout_minutes: u64,
884}
885
886impl Default for Release {
887 fn default() -> Self {
888 Self {
889 mode: ReleaseMode::Actions,
890 commands: Vec::new(),
891 timeout_minutes: 30,
892 }
893 }
894}
895
896impl Release {
897 /// Is this repository released by magi rather than by its workflows?
898 pub fn is_local(&self) -> bool {
899 self.mode == ReleaseMode::Local
900 }
901}
902
903/// Top-level configuration.
904#[derive(Debug, Clone, Default, Deserialize, Serialize)]
905#[serde(deny_unknown_fields, default)]
906pub struct Config {
907 /// Agent roster.
908 pub agents: Vec<AgentSpec>,
909 /// Role assignment.
910 pub roles: Roles,
911 /// Graph shape.
912 pub graph: Graph,
913 /// Blindness policy.
914 pub blind: Blind,
915 /// Verification commands.
916 pub verify: Verify,
917 /// Disk hygiene.
918 pub disk: Disk,
919 /// Merge policy.
920 pub merge: Merge,
921 /// Self-update policy.
922 pub update: Update,
923 /// Project-specific text appended to the node prompts.
924 pub prompts: Prompts,
925 /// How the operator is told a run is waiting on them.
926 pub notify: Notify,
927 /// Local repositories the plan surface can start or derive a conversation
928 /// against.
929 pub repos: Repos,
930 /// Policy for the standing conversation ([`crate::talk`]).
931 pub talk: Talk,
932 /// How many runs `magi serve`'s own loop drives at once.
933 pub daemon: Daemon,
934 /// Who tags and publishes after a release pull request merges.
935 pub release: Release,
936 /// Context-window sizes in tokens, keyed by model name, merged over
937 /// [`BUILTIN_CONTEXT_WINDOWS`]. See [`Config::context_window`].
938 pub context_windows: BTreeMap<String, u64>,
939}
940
941/// Context windows of models magi commonly drives, in tokens.
942///
943/// A convenience, not a source of truth: vendors resize windows and ship new
944/// models faster than this table is edited, so an entry that is stale or
945/// missing is fixed by `[context_windows]` in `magi.toml`, which wins. Matched
946/// by [`Config::context_window`]: exact name first, then the longest key that
947/// prefixes the model name (so a dated or suffixed id such as
948/// `claude-sonnet-4-5-20250929` finds `claude-sonnet-4-5`). A model matching
949/// nothing has no percentage - the UI shows the raw count.
950const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
951 ("claude-opus-4", 200_000),
952 ("claude-sonnet-4", 200_000),
953 ("claude-haiku-4", 200_000),
954 ("claude-3", 200_000),
955 ("opus", 200_000),
956 ("sonnet", 200_000),
957 ("haiku", 200_000),
958 ("gpt-5", 400_000),
959 ("gpt-4.1", 1_000_000),
960 ("gpt-4o", 128_000),
961 ("o3", 200_000),
962 ("o4-mini", 200_000),
963 ("gemini-2.5", 1_000_000),
964 ("deepseek", 128_000),
965];
966
967impl Config {
968 /// Context window in tokens for `model`: `[context_windows]` first, then
969 /// the built-in table; within each, an exact name beats the longest
970 /// prefix. `None` for an unknown model, which is a deliberate answer -
971 /// guessing a denominator would print a confident wrong percentage.
972 pub fn context_window(&self, model: &str) -> Option<u64> {
973 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
974 let mut best: Option<(usize, u64)> = None;
975 for (key, window) in entries {
976 if key == model {
977 return Some(window);
978 }
979 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
980 best = Some((key.len(), window));
981 }
982 }
983 best.map(|(_, w)| w)
984 }
985 lookup(
986 model,
987 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
988 )
989 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
990 }
991}
992
993/// How the daemon loop itself behaves, as opposed to what one run does.
994///
995/// Machine-layer material in the same sense [`Repos::roots`] is: how many
996/// competitions this machine's own loop is willing to babysit at once is a
997/// fact about the machine running `magi serve`, not about any one
998/// repository's task, so it belongs in `<config_dir>/magi/config.toml`
999/// rather than a repository's own `magi.toml` - though, like `Repos::roots`,
1000/// nothing stops a repository from setting it too, since a scalar field
1001/// takes whichever layer has the highest precedence.
1002#[derive(Debug, Clone, Deserialize, Serialize)]
1003#[serde(deny_unknown_fields, default)]
1004pub struct Daemon {
1005 /// How many runs `magi serve` may have actively in flight at once.
1006 /// **One by default** - today's behaviour, one run at a time.
1007 ///
1008 /// This is a different knob from [`Graph::max_parallel`], and the two
1009 /// must not be confused: `max_parallel` bounds how many agent *processes*
1010 /// one run starts inside itself (implementers, judges, reviewers -
1011 /// candidates competing on a single task); this field bounds how many
1012 /// *runs* - whole competitions, each with its own `max_parallel` budget -
1013 /// the loop drives side by side, possibly across different tasks and
1014 /// different repositories. Raising `max_parallel` buys a bigger panel for
1015 /// one task; raising this buys more tasks worked at once. A config file
1016 /// that meant one and wrote the other would either starve a competition
1017 /// of judges or leave the rest of the backlog waiting for no reason.
1018 ///
1019 /// A run parked waiting on the operator's land-merge approval - see
1020 /// [`crate::land`] - does not hold one of these slots while it waits: the
1021 /// whole point of parking there is to let the loop spend the slot on
1022 /// something runnable instead of sitting on a decision only a human can
1023 /// make. So even at the default of `1`, an approval that comes back does
1024 /// not queue behind whatever else the loop happens to be running.
1025 pub max_concurrent_runs: usize,
1026 /// Let a task marked [`crate::queue::Task::interrupt`] (`magi task
1027 /// interrupt`) cut ahead of whatever `magi serve` already has in flight,
1028 /// instead of waiting for it to finish.
1029 ///
1030 /// **Off by default.** When enabled, a run that is in flight and is not
1031 /// itself the interrupt candidate may be paused at its next safe node
1032 /// boundary - see [`crate::graph::Runner::park_here`] - so the marked
1033 /// task can run alone; the paused run resumes automatically, through the
1034 /// same path any other parked run does, the moment the interrupting
1035 /// task's own run reaches a terminal status. This is opt-in because it
1036 /// bends the loop's own "one run at a time" principle (see this repository's
1037 /// `magi serve` help) for a specific, explicit operator request, and a
1038 /// repository that never files an interrupt task pays nothing for having
1039 /// it on - but an operator who does not want any run of theirs preempted,
1040 /// ever, should leave this `false`.
1041 pub pause_for_interrupts: bool,
1042 /// How many deputies `magi serve` runs at once. A deputy is the short-lived
1043 /// seat that waits on one open conductor question (see [`crate::deputy`]);
1044 /// each is a live agent conversation, so this is bounded - **two by
1045 /// default**, because the agent CLIs' quota is the scarce resource. A
1046 /// question over the limit keeps its place and starts when a deputy
1047 /// finishes; `0` runs none.
1048 pub max_deputies: usize,
1049 /// Minutes a release-bump pull request may make no progress before
1050 /// `magi serve` raises a notice and asks the owner (see
1051 /// [`crate::release_watch`]). Progress is a change of head commit or of any
1052 /// check's verdict. A required check that stays red after the one rerun the
1053 /// watcher is allowed escalates at once, whatever this says. **Sixty by
1054 /// default**; `0` turns the watcher off.
1055 pub release_stall_minutes: u64,
1056}
1057
1058impl Default for Daemon {
1059 fn default() -> Self {
1060 Self {
1061 max_concurrent_runs: 1,
1062 pause_for_interrupts: false,
1063 max_deputies: 2,
1064 release_stall_minutes: 60,
1065 }
1066 }
1067}
1068
1069/// Where `magi repos` and `GET /api/repos` look for local checkouts.
1070///
1071/// `roots` is one of the array keys [`array_merge_policy`] marks as
1072/// append-across-layers: which checkouts exist in general is a *machine*
1073/// fact in the same way the agent roster is - a repository's own `magi.toml`
1074/// cannot state where its siblings live before magi has resolved which
1075/// repository to read that file from in the first place - but a repository
1076/// that genuinely has an extra root worth scanning is not forced to choose
1077/// between an error and losing the machine's roots outright. Both layers'
1078/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
1079/// are still refused.
1080#[derive(Debug, Clone, Deserialize, Serialize)]
1081#[serde(deny_unknown_fields, default)]
1082pub struct Repos {
1083 /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
1084 /// with a `.git` directory. Empty by default - nothing is scanned unless
1085 /// asked to be.
1086 pub roots: Vec<PathBuf>,
1087 /// How long a scan is trusted before the next request re-scans it,
1088 /// seconds. `0` means never trust it: scan on every request. Defaults to
1089 /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
1090 /// the same reason - a checkout does not usually appear or vanish inside
1091 /// a session, so there is little to gain from scanning more often than
1092 /// that, and an explicit refresh exists for the moment one does.
1093 pub scan_ttl: u64,
1094 /// How often `magi serve` runs `git fetch origin` in every checkout under
1095 /// `roots`, seconds, so `origin/main` stays fresh whatever state the
1096 /// working tree is in. Fetch only: no branch, HEAD or working tree is
1097 /// touched. `0` disables it.
1098 pub fetch_interval: u64,
1099}
1100
1101impl Default for Repos {
1102 fn default() -> Self {
1103 Self {
1104 roots: Vec::new(),
1105 scan_ttl: 86_400,
1106 fetch_interval: 600,
1107 }
1108 }
1109}
1110
1111/// Project-specific text appended to each node's prompt.
1112///
1113/// **Additive by construction.** These fields cannot replace magi's prompts,
1114/// only extend them, and that restriction is the whole design. The built-in
1115/// prompts carry the invariants the competition rests on: a judging prompt
1116/// names no authors, every structured answer must arrive as one fenced `json`
1117/// block, and a judge is told not to speculate about who wrote what. A config
1118/// that could overwrite them would let a typo silently un-blind the panel or
1119/// break the parser, and the symptom would be "the judges got worse" rather
1120/// than an error.
1121///
1122/// Repository-wide context belongs in `AGENTS.md`, which every agent already
1123/// reads from the checkout. Use these fields for the things a *magi node*
1124/// needs to know and a repository file cannot say - for instance that
1125/// reviewers here should ignore formatting because a hook owns it.
1126#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1127#[serde(deny_unknown_fields, default)]
1128pub struct Prompts {
1129 /// Appended to every node's prompt.
1130 pub all: String,
1131 /// Appended for implementers.
1132 pub implement: String,
1133 /// Appended for judges, both ranking and voting.
1134 pub judge: String,
1135 /// Appended for reviewers.
1136 pub review: String,
1137 /// Appended for the fixer.
1138 pub fix: String,
1139}
1140
1141impl Prompts {
1142 /// The overlay for one node, or `None` when nothing is configured.
1143 ///
1144 /// `node` is the graph's own node name, so a new node gets no overlay
1145 /// rather than the wrong one.
1146 pub fn overlay(&self, node: &str) -> Option<String> {
1147 let specific = match node {
1148 "implement" => &self.implement,
1149 "judge" | "vote" | "deliberate" => &self.judge,
1150 "review" => &self.review,
1151 "fix" => &self.fix,
1152 _ => "",
1153 };
1154 let mut parts: Vec<&str> = Vec::new();
1155 for p in [self.all.trim(), specific.trim()] {
1156 if !p.is_empty() {
1157 parts.push(p);
1158 }
1159 }
1160 if parts.is_empty() {
1161 return None;
1162 }
1163 Some(parts.join("\n\n"))
1164 }
1165}
1166
1167/// How the operator is told that a run is waiting on them.
1168///
1169/// A command rather than a built-in integration: magi is one binary with no
1170/// network dependencies, and every operator's notification path is different -
1171/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
1172/// Shelling out keeps all of them possible and none of them magi's problem.
1173#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1174#[serde(deny_unknown_fields, default)]
1175pub struct Notify {
1176 /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
1177 /// Empty means no notification - the web UI is then the only surface.
1178 pub command: Vec<String>,
1179}
1180
1181/// Policy for [`crate::talk`], the standing conversation.
1182#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1183#[serde(deny_unknown_fields, default)]
1184pub struct Talk {
1185 /// Let the conversation's agent edit files in the repository instead of
1186 /// filing a task for one. **Off by default** - see
1187 /// [`crate::talk`]'s module doc for why an edit made mid-conversation is
1188 /// an edit no run and no review can be attributed to, which is exactly
1189 /// the property a repository entered in a competition depends on. A
1190 /// repository that is never judged - dotfiles, a personal config
1191 /// checkout - has nothing to lose by turning this on in its own
1192 /// `magi.toml`, and a one-line fix stops costing a queued task to get.
1193 pub allow_write: bool,
1194}
1195
1196/// Roles resolved to concrete agent specs for one run.
1197#[derive(Debug, Clone)]
1198pub struct ResolvedRoles {
1199 /// One per candidate.
1200 pub implementers: Vec<AgentSpec>,
1201 /// One per judge.
1202 pub judges: Vec<AgentSpec>,
1203 /// One per reviewer slot.
1204 pub reviewers: Vec<AgentSpec>,
1205 /// The configured fixer chain in order, if `[roles] fixer` is set
1206 /// (resolved like [`crate::agent::pick_chain`]: unknown or uninstalled ids
1207 /// skipped, duplicates keep their first place). `None` means the winner's
1208 /// own author.
1209 pub fixer: Option<Vec<AgentSpec>>,
1210 /// Queue conductor, explicitly selected or resolved by the standalone-seat fallback.
1211 pub conductor: AgentSpec,
1212 /// The full ordered implementer roster, in [`Roles::implementers`]'s own
1213 /// order — or `[[agents]]` in file order, when that list is empty. Unlike
1214 /// [`Self::implementers`], never truncated to `graph.implementers` and
1215 /// never `rotate`d/wrapped: a solo run (`implementers = 1`) resolves
1216 /// `implementers` down to a single slot, but `graph::Runner`'s per-seat
1217 /// quota fallback needs the *whole* list to walk forward through when
1218 /// that one slot's agent runs out of quota mid-run.
1219 pub implementer_roster: Vec<AgentSpec>,
1220 /// [`Self::implementer_roster`]'s counterpart for judge seats: the whole
1221 /// `[roles] judges` list (or every agent), untruncated and unrotated, for
1222 /// the per-seat handover when a judge's agent fails.
1223 pub judge_roster: Vec<AgentSpec>,
1224 /// Likewise for reviewer seats.
1225 pub reviewer_roster: Vec<AgentSpec>,
1226}
1227
1228/// Every array-valued key in a config table, as a dotted path.
1229///
1230/// Dotted so the error names `roles.implementers` rather than `implementers`:
1231/// an operator with three config files needs to know which key, not just that
1232/// there was one. `vars` is skipped because it is teravars' own input, merged
1233/// on purpose and never deserialised into `Config`.
1234fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1235 let mut out = Vec::new();
1236 for (k, v) in table {
1237 if prefix.is_empty() && k == "vars" {
1238 continue;
1239 }
1240 let path = if prefix.is_empty() {
1241 k.clone()
1242 } else {
1243 format!("{prefix}.{k}")
1244 };
1245 match v {
1246 toml::Value::Array(_) => out.push(path),
1247 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1248 _ => {}
1249 }
1250 }
1251 out
1252}
1253
1254/// How an array key behaves when two config layers both declare it.
1255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1256enum ArrayMerge {
1257 /// Two layers may both declare it; the composed value is the
1258 /// low-to-high-priority concatenation teravars already produces (see
1259 /// [`Config::load_layers`]'s doc for why that order and no dedup).
1260 Append,
1261 /// Two layers declaring it is refused; see
1262 /// [`Config::refuse_split_arrays`].
1263 Replace,
1264}
1265
1266/// The single place that decides, for a dotted array key (as returned by
1267/// [`array_keys`]), whether declaring it in two config layers is a
1268/// concatenation the operator asked for or a silent accident.
1269///
1270/// Kept as one match so the whole policy is visible in one place - the same
1271/// reason `claude_quota` and `dropped_stream` close their own classification
1272/// in one spot elsewhere in this codebase. Anything not listed defaults to
1273/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
1274/// reasoned about yet, and a new array key added later has to be added here
1275/// deliberately to become appendable.
1276///
1277/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
1278/// gate. Concatenating two of them is exactly the checks both layers
1279/// wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
1280/// live in a shared layer while a repository's own layer adds its own
1281/// command, instead of every repository copying the shared command into
1282/// its own file.
1283/// - `repos.roots` — a set of directories to scan for checkouts. A
1284/// repository adding its own root on top of the machine's is additive by
1285/// nature, not a replacement of where the machine looks; see
1286/// [`Repos::roots`].
1287///
1288/// Left on the refuse side, and why:
1289/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
1290/// list of *seats*, not a set. A machine's two implementers plus a
1291/// repository's one is three seats nobody asked for and nobody is paying
1292/// for on purpose.
1293/// - `notify.command` — an argv. Concatenating two argvs does not produce a
1294/// program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
1295/// - `blind.strip_lines` — technically safe to concatenate (each entry is
1296/// matched as an independent substring, so a longer list only strips
1297/// *more*), but left on the refuse side anyway: the same list also drives
1298/// `commit_msg_hook`'s generated `sed` addresses, where position matters,
1299/// and a silent three-layer merge is exactly the kind of surprise
1300/// `refuse_split_arrays` exists to catch rather than to reason about
1301/// case-by-case. A repository that wants one more stripped phrase restates
1302/// the whole list; that restatement is visible in review, an accidental
1303/// concatenation would not be.
1304fn array_merge_policy(key: &str) -> ArrayMerge {
1305 match key {
1306 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1307 _ => ArrayMerge::Replace,
1308 }
1309}
1310
1311impl Config {
1312 /// Load one file through teravars: Tera rendering, `[vars]` resolution,
1313 /// and the `include = [...]` directive.
1314 pub fn load(path: &Path) -> Result<Self> {
1315 Self::load_layers(&[path.to_path_buf()])
1316 }
1317
1318 /// The Tera render context shared by every layer: `system.*` (from
1319 /// teravars), `env` (magi's own addition - a config that names a shared
1320 /// build-cache directory or a machine-specific path needs
1321 /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
1322 /// derived from the last (highest-priority) path's parent directory.
1323 ///
1324 /// Factored out so [`Config::array_provenance`] can re-render a single
1325 /// layer under the exact same context [`Config::load_layers`] uses for
1326 /// the joint render, rather than drifting from it by accident.
1327 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1328 let mut ctx = teravars::system_context();
1329 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1330 ctx.insert("env", &env);
1331 if let Some(last) = paths.last()
1332 && let Some(dir) = last.parent()
1333 {
1334 // A layer extracted from `<remote>/<base>` records the checkout it
1335 // stands for beside itself; its own directory is a cache path.
1336 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1337 .map(|s| PathBuf::from(s.trim()))
1338 .unwrap_or_else(|_| dir.to_path_buf());
1339 ctx.insert("repo", &dir.to_string_lossy());
1340 ctx.insert(
1341 "repo_name",
1342 &dir.file_name().unwrap_or_default().to_string_lossy(),
1343 );
1344 }
1345 ctx
1346 }
1347
1348 /// Load and deep-merge a stack of config files, later files winning.
1349 ///
1350 /// This is why the config is TOML-through-teravars rather than plain serde:
1351 /// the roster is a *machine* fact (which CLIs and plans you pay for) while
1352 /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
1353 /// there). Picking one file and ignoring the other would force every repo
1354 /// to restate the roster.
1355 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1356 let mut engine = teravars::Engine::default();
1357 let ctx = Self::render_ctx(paths);
1358 if paths.len() > 1 {
1359 Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
1360 }
1361 let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
1362 format!(
1363 "rendering config via teravars: {}",
1364 paths
1365 .iter()
1366 .map(|p| p.display().to_string())
1367 .collect::<Vec<_>>()
1368 .join(", ")
1369 )
1370 })?;
1371 let mut table = merged.config;
1372 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1373 // `[vars]` is teravars' own input, already resolved into the render
1374 // context; `deny_unknown_fields` must not trip over it.
1375 table.remove("vars");
1376 // No layer says anything about `agents`: the roster is whatever is on
1377 // `PATH` now, exactly as when no layer exists at all. An explicit
1378 // `agents = []` is a statement and is kept.
1379 let detect_agents = !table.contains_key("agents");
1380 let mut cfg: Self = toml::Value::Table(table)
1381 .try_into()
1382 .context("deserializing magi config")?;
1383 if detect_agents {
1384 cfg.agents = Self::autodetected().agents;
1385 }
1386 Ok(cfg)
1387 }
1388
1389 /// `graph.candidates` was renamed `graph.implementers`. Both spellings are
1390 /// read, but the layers are merged into one table before serde sees it, so
1391 /// an old name in a lower layer and the new name in a higher one would
1392 /// arrive together and fail as a duplicate field instead of letting the
1393 /// higher layer win. Resolve it here: a single layer that writes both is
1394 /// refused (naming both keys and the file); otherwise the value from the
1395 /// last layer that wrote either key becomes `implementers`.
1396 fn normalize_renamed_keys(
1397 paths: &[PathBuf],
1398 engine: &mut teravars::Engine,
1399 ctx: &teravars::Context,
1400 table: &mut toml::map::Map<String, toml::Value>,
1401 ) -> Result<()> {
1402 let both = matches!(
1403 table.get("graph"),
1404 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1405 );
1406 if !both {
1407 return Ok(());
1408 }
1409 let mut winner: Option<toml::Value> = None;
1410 for path in paths {
1411 let one = teravars::load_merged([path], engine, ctx)
1412 .with_context(|| format!("rendering {}", path.display()))?;
1413 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1414 continue;
1415 };
1416 if g.contains_key("candidates") && g.contains_key("implementers") {
1417 bail!(
1418 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1419 path.display()
1420 );
1421 }
1422 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1423 winner = Some(v.clone());
1424 }
1425 }
1426 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1427 g.remove("candidates");
1428 if let Some(v) = winner {
1429 g.insert("implementers".to_owned(), v);
1430 }
1431 }
1432 Ok(())
1433 }
1434
1435 /// Refuse an array that two layers both declare, unless
1436 /// [`array_merge_policy`] says that key is meant to accumulate.
1437 ///
1438 /// teravars **appends** arrays when it merges layers, and that is wrong for
1439 /// most arrays magi has: `implementers` is an ordered list of seats,
1440 /// `notify.command` is an argv. Concatenating two of them yields something
1441 /// nobody wrote - three implementers out of a machine's two and a
1442 /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
1443 ///
1444 /// Replacing instead would be the right merge rule for those keys, but the
1445 /// rule lives in teravars, which several other projects depend on;
1446 /// changing it there is a decision for that crate, not something to fake
1447 /// here by re-reading the files with different semantics and hoping the
1448 /// two paths agree.
1449 ///
1450 /// So magi refuses the ambiguity rather than resolving it silently, for
1451 /// every array key except the short, deliberate list
1452 /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
1453 /// concatenation teravars already produces *is* what both files say, so
1454 /// there is nothing to refuse. The cost of guessing wrong on the refused
1455 /// keys is a roster the operator did not ask for and is paying for by the
1456 /// token; the append keys carry no such risk because every element runs
1457 /// (or every directory is scanned) regardless of order.
1458 fn refuse_split_arrays(
1459 paths: &[PathBuf],
1460 engine: &mut teravars::Engine,
1461 ctx: &teravars::Context,
1462 ) -> Result<()> {
1463 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1464 for path in paths {
1465 let one = teravars::load_merged([path], engine, ctx)
1466 .with_context(|| format!("rendering {}", path.display()))?;
1467 for key in array_keys(&one.config, "") {
1468 if array_merge_policy(&key) == ArrayMerge::Append {
1469 continue;
1470 }
1471 if let Some(first) = seen.get(&key) {
1472 bail!(
1473 "`{key}` is an array declared in two config layers:\n \
1474 {}\n {}\nteravars appends arrays when it merges, so \
1475 magi would run the concatenation of both - which is \
1476 not what either file says. Declare `{key}` in exactly \
1477 one of them.",
1478 first.display(),
1479 path.display()
1480 );
1481 }
1482 seen.insert(key, path.clone());
1483 }
1484 }
1485 Ok(())
1486 }
1487
1488 /// Which layers contributed to a composed, appendable array key (e.g.
1489 /// `"verify.gate"`), in the same low-to-high-priority order
1490 /// [`Config::load_layers`] concatenates them in. Layers that do not
1491 /// declare `key` at all are omitted.
1492 ///
1493 /// This is a **display aid for `magi doctor` only.** The command list
1494 /// that actually runs always comes from the one joint
1495 /// [`teravars::load_merged`] call in `load_layers`, never from this
1496 /// function - the exact hazard [`Config::refuse_split_arrays`] warns
1497 /// about is two merge paths that might disagree, so this function must
1498 /// never become a second source of the *composed* value, only of which
1499 /// file wrote which line in it.
1500 ///
1501 /// Re-rendering each layer alone can, in principle, resolve a
1502 /// `{{ vars.x }}` differently than the joint render would, if `x` is
1503 /// defined in one layer and referenced in another - the same caveat
1504 /// `refuse_split_arrays`'s structural, key-only check already lives with.
1505 /// None of magi's own gate commands cross that line, and a doctor listing
1506 /// is read by a human who can compare it against the joint one printed
1507 /// alongside it, so this is judged worth the simplicity of not
1508 /// threading provenance through the real load path.
1509 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1510 let mut engine = teravars::Engine::default();
1511 let ctx = Self::render_ctx(paths);
1512 let mut out = Vec::new();
1513 for path in paths {
1514 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1515 continue;
1516 };
1517 let mut cur = &one.config;
1518 let mut found = None;
1519 let parts: Vec<&str> = key.split('.').collect();
1520 for (i, part) in parts.iter().enumerate() {
1521 match cur.get(*part) {
1522 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1523 found = Some(a);
1524 break;
1525 }
1526 Some(toml::Value::Table(t)) => cur = t,
1527 _ => break,
1528 }
1529 }
1530 let Some(values) = found else { continue };
1531 let strings: Vec<String> = values
1532 .iter()
1533 .filter_map(|v| v.as_str().map(str::to_owned))
1534 .collect();
1535 if !strings.is_empty() {
1536 out.push((path.clone(), strings));
1537 }
1538 }
1539 out
1540 }
1541
1542 /// Each layer rendered on its own, with the outcome per file: the
1543 /// settings screen's way of saying which layer a value came from and which
1544 /// layer is the one that does not parse. A **display aid only**, for the
1545 /// same reason as [`Config::array_provenance`]: the effective config
1546 /// always comes from the one joint [`Config::load_layers`].
1547 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1548 let mut engine = teravars::Engine::default();
1549 let ctx = Self::render_ctx(paths);
1550 paths
1551 .iter()
1552 .map(|path| {
1553 let one = teravars::load_merged([path], &mut engine, &ctx)
1554 .map(|m| m.config)
1555 .with_context(|| format!("rendering {}", path.display()));
1556 (path.clone(), one)
1557 })
1558 .collect()
1559 }
1560
1561 /// Render a composed command list for `magi doctor`: the joined command
1562 /// line the run actually uses, plus - only when more than one layer
1563 /// contributed - which layer wrote which line.
1564 ///
1565 /// A single contributing layer (the common case today) stays the plain
1566 /// one-line summary magi has always printed, `empty` included: that
1567 /// honest "(none — ...)" is what caught a real gate-composition gap
1568 /// before this array could compose at all, and composition should not
1569 /// make the common case noisier.
1570 pub fn describe_composed(
1571 paths: &[PathBuf],
1572 commands: &[String],
1573 key: &str,
1574 empty: &str,
1575 ) -> String {
1576 if commands.is_empty() {
1577 return empty.to_owned();
1578 }
1579 let joined = commands.join(" && ");
1580 let provenance = Self::array_provenance(paths, key);
1581 if provenance.len() <= 1 {
1582 return joined;
1583 }
1584 let mut out = joined;
1585 for (path, cmds) in &provenance {
1586 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1587 }
1588 out
1589 }
1590
1591 /// Resolve the config for `repo`, honouring an explicit `--config` path.
1592 ///
1593 /// Returns the config and the layers it came from, empty for built-in
1594 /// defaults. The repository layers come from the remote-tracking ref as it
1595 /// stands (see the module doc); use [`Config::discover_fetched`] where a
1596 /// stale ref would matter.
1597 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1598 if let Some(p) = explicit {
1599 let paths = vec![p.to_path_buf()];
1600 return Ok((Self::load_layers(&paths)?, paths));
1601 }
1602 let paths = Self::layers_checked(repo)?;
1603 if paths.is_empty() {
1604 return Ok((Self::autodetected(), paths));
1605 }
1606 Ok((Self::load_layers(&paths)?, paths))
1607 }
1608
1609 /// [`Config::discover`] after `git fetch <remote> <base>`: for every path
1610 /// that is about to start work. A failed fetch is an error.
1611 pub async fn discover_fetched(
1612 repo: &Path,
1613 explicit: Option<&Path>,
1614 ) -> Result<(Self, Vec<PathBuf>)> {
1615 if explicit.is_none() && is_git_worktree(repo) {
1616 // A checkout that was never cloned from the remote has no
1617 // `<remote>/HEAD`; learn it here (refs/remotes only) so an
1618 // ordinary start recovers instead of failing in `discover`.
1619 let (remote, cfg_base) = probe_remote_base(repo);
1620 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref()).await?;
1621 let out = crate::git::fetch(repo, &remote, &base)
1622 .await
1623 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))?;
1624 if !out.ok() {
1625 bail!(
1626 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
1627 out.stderr.lines().next().unwrap_or("").trim()
1628 );
1629 }
1630 if cfg_base.is_none() {
1631 crate::git::ensure_remote_head(repo, &remote, &base).await;
1632 }
1633 }
1634 Self::discover(repo, explicit)
1635 }
1636
1637 /// [`Config::layers`], but an unreadable remote ref is an error.
1638 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
1639 if !is_git_worktree(repo) {
1640 return Ok(Self::layers(repo));
1641 }
1642 let mut paths: Vec<PathBuf> = Self::machine_layer()
1643 .into_iter()
1644 .filter(|p| p.is_file())
1645 .collect();
1646 paths.extend(Self::repo_layers(repo)?);
1647 Ok(paths)
1648 }
1649
1650 /// Only the repository layers (lowest first), from `<remote>/<base>` in a
1651 /// git working tree and from disk elsewhere.
1652 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
1653 if !is_git_worktree(repo) {
1654 return Ok([
1655 repo.join(".magi").join("config.toml"),
1656 repo.join("magi.toml"),
1657 ]
1658 .into_iter()
1659 .filter(|p| p.is_file())
1660 .collect());
1661 }
1662 remote_layers(repo)
1663 }
1664
1665 /// Environment variable that relocates the machine-wide config layer.
1666 ///
1667 /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
1668 /// of the one under [`dirs::config_dir`]; set it to the empty string and
1669 /// magi reads no machine layer at all.
1670 ///
1671 /// This exists because the machine layer is otherwise unavoidable, and a
1672 /// test that builds a config fixture is not asking for the operator's
1673 /// preferences to be merged into it. Adding `[repos] roots` to the real
1674 /// machine config on a development box turned two passing tests red -
1675 /// `repos_list_returns_name_and_path_for_every_configured_root` and
1676 /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
1677 /// declare `[repos] roots` of their own, which [`Config::layers`] then
1678 /// found in two layers and [`Config::refuse_split_arrays`] correctly
1679 /// refused. CI never saw it: a runner has no machine config, so the suite
1680 /// was green there and red only where somebody actually uses magi.
1681 ///
1682 /// An operator gets the same escape hatch for free: a second machine
1683 /// config, or none, without moving files about.
1684 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
1685
1686 /// Every config layer that applies to `repo`, in increasing precedence.
1687 ///
1688 /// The machine layer is whatever [`Config::machine_layer`] resolves to,
1689 /// which is nothing at all in a test build.
1690 pub fn layers(repo: &Path) -> Vec<PathBuf> {
1691 let mut paths = Vec::new();
1692 paths.extend(Self::machine_layer());
1693 paths.push(repo.join(".magi").join("config.toml"));
1694 paths.push(repo.join("magi.toml"));
1695 paths.retain(|p| p.is_file());
1696 paths
1697 }
1698
1699 /// The machine-wide layer's path, when there is one.
1700 ///
1701 /// **A test build has none unless it names one.** A fixture is a complete
1702 /// statement of the config under test, and the operator's own preferences
1703 /// have no business being merged into it - least of all silently, on one
1704 /// machine, in a suite that is green everywhere else.
1705 #[cfg(test)]
1706 pub(crate) fn machine_layer() -> Option<PathBuf> {
1707 std::env::var(Self::CONFIG_DIR_ENV)
1708 .ok()
1709 .filter(|dir| !dir.trim().is_empty())
1710 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
1711 }
1712
1713 /// The machine-wide layer's path, when there is one.
1714 #[cfg(not(test))]
1715 pub(crate) fn machine_layer() -> Option<PathBuf> {
1716 match std::env::var(Self::CONFIG_DIR_ENV) {
1717 // Named, and empty on purpose: no machine layer.
1718 Ok(dir) if dir.trim().is_empty() => None,
1719 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1720 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1721 }
1722 }
1723
1724 /// Built-in config whose roster is the agent CLIs found on `PATH`.
1725 pub fn autodetected() -> Self {
1726 let mut cfg = Self::default();
1727 for (kind, id, model) in [
1728 (AgentKind::Claude, "opus", Some("opus")),
1729 (AgentKind::Claude, "sonnet", Some("sonnet")),
1730 (AgentKind::Antigravity, "antigravity", None),
1731 (AgentKind::Opencode, "opencode", None),
1732 (AgentKind::Codex, "codex", None),
1733 (AgentKind::Omp, "omp", None),
1734 ] {
1735 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1736 cfg.agents.push(AgentSpec {
1737 id: id.to_owned(),
1738 kind,
1739 model: model.map(str::to_owned),
1740 command: Vec::new(),
1741 extra_args: Vec::new(),
1742 env: BTreeMap::new(),
1743 prompt_delivery: None,
1744 });
1745 }
1746 }
1747 cfg
1748 }
1749
1750 /// The shared build cache the verify commands and the agents both build
1751 /// into, when the config declares one. See [`Verify::cache_dir`].
1752 pub fn cache_dir(&self) -> Option<PathBuf> {
1753 self.verify.cache_dir()
1754 }
1755
1756 /// Look an agent up by id.
1757 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1758 self.agents
1759 .iter()
1760 .find(|a| a.id == id)
1761 .with_context(|| format!("no agent with id `{id}` in the roster"))
1762 }
1763
1764 /// Rotate `count` seats out of `ids`, or out of the whole roster at
1765 /// `offset` when `ids` is empty.
1766 ///
1767 /// The one rotation rule - explicit ids cycle, an empty list rotates the
1768 /// roster - shared by every seat count [`Config::resolve_roles`] fills in,
1769 /// rather than each seat reimplementing it and drifting apart.
1770 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
1771 let mut out = Vec::with_capacity(count);
1772 for i in 0..count {
1773 let spec = if ids.is_empty() {
1774 self.agents[(i + offset) % self.agents.len()].clone()
1775 } else {
1776 self.agent(&ids[i % ids.len()])?.clone()
1777 };
1778 out.push(spec);
1779 }
1780 Ok(out)
1781 }
1782
1783 /// `ids`, resolved to specs in the order named, or the whole `[[agents]]`
1784 /// roster in file order when `ids` is empty — the same "explicit ids
1785 /// stand alone, an empty list means the whole roster" rule [`Self::rotate`]
1786 /// applies, but with no `count` to truncate to and no `offset` to wrap by.
1787 /// See [`ResolvedRoles::implementer_roster`] for why a truncated, rotated
1788 /// list cannot answer the question this exists for.
1789 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
1790 if ids.is_empty() {
1791 Ok(self.agents.clone())
1792 } else {
1793 ids.iter().map(|id| self.agent(id).cloned()).collect()
1794 }
1795 }
1796
1797 /// Fill the roles out to the configured widths.
1798 ///
1799 /// An empty role list rotates through the whole roster, so a three-agent
1800 /// roster with `implementers = 3` gives one implementation per agent, and
1801 /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1802 /// author of candidate *i* whenever the roster has more than one agent.
1803 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1804 if self.agents.is_empty() {
1805 bail!(
1806 "agent roster is empty: no agent CLI found on PATH and no \
1807 [[agents]] in the config. Run `magi init` to write a starter \
1808 magi.toml."
1809 );
1810 }
1811 Ok(ResolvedRoles {
1812 implementers: self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
1813 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
1814 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
1815 fixer: match self.roles.fixer.as_ref() {
1816 // Ids are validated against the roster here; whether the CLI
1817 // is installed is left to invocation, like every other seat.
1818 Some(choice) => Some(crate::agent::pick_chain(
1819 &self.agents,
1820 Some(choice),
1821 &|_| true,
1822 "fixer",
1823 )?),
1824 None => None,
1825 },
1826 // Role resolution validates roster shape, but deliberately does
1827 // not preflight a CLI. The other graph seats have always deferred
1828 // that failure to invocation; doing it only for the conductor
1829 // made otherwise usable graph commands and `doctor` fail as one.
1830 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
1831 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
1832 // A fallback chain: the first id the roster knows. The rest
1833 // are `agent::pick_chain`'s business at invocation.
1834 Some(ids) if !ids.is_empty() => ids
1835 .iter()
1836 .find_map(|id| self.agent(id).ok())
1837 .cloned()
1838 .with_context(|| {
1839 format!("[roles] conductor names no agent in the roster: {ids:?}")
1840 })?,
1841 // Keep the normal standalone-seat preference when something
1842 // is installed, but retain a roster fallback when it is not.
1843 // Invocation then reports the unavailable CLI in the same
1844 // place it does for every other graph role.
1845 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
1846 .unwrap_or_else(|_| self.agents[0].clone()),
1847 },
1848 implementer_roster: self.full_roster(&self.roles.implementers)?,
1849 judge_roster: self.full_roster(&self.roles.judges)?,
1850 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
1851 })
1852 }
1853
1854 /// Advisor seats for the design-deliberation stage (see
1855 /// `graph::Runner::advise`): `[roles] advisors` when set, otherwise the
1856 /// judge roster - see [`Roles::advisors`] for why that fallback and not
1857 /// the whole roster.
1858 ///
1859 /// The fallback rotates with `offset = 1`, matching the judges line in
1860 /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
1861 /// `roles.judges`, which is empty whenever judges themselves are
1862 /// unconfigured and rotating the whole roster. Falling back with
1863 /// `offset = 0` there would silently hand the advisors a *different*
1864 /// agent set than the judges an unconfigured run would actually get,
1865 /// which is the one thing [`Roles::advisors`]'s doc promises will not
1866 /// happen.
1867 ///
1868 /// Called lazily from the graph node itself rather than folded into
1869 /// [`Config::resolve_roles`]: unlike the other roles, a failure here must
1870 /// not stop a run from starting at all - the deliberation stage is an
1871 /// enrichment `[graph] advise` can turn off, not a seat later nodes
1872 /// cannot proceed without - and at the point `resolve_roles` runs (before
1873 /// [`crate::run::RunState`] exists, on `Runner::start`) there would be no
1874 /// run yet for a resolution failure to be reported against.
1875 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
1876 if self.agents.is_empty() {
1877 bail!(
1878 "agent roster is empty: no agent CLI found on PATH and no \
1879 [[agents]] in the config. Run `magi init` to write a starter \
1880 magi.toml."
1881 );
1882 }
1883 if !self.roles.advisors.is_empty() {
1884 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
1885 }
1886 self.rotate(&self.roles.judges, self.graph.advisors, 1)
1887 }
1888
1889 /// The untruncated roster advisor seats hand over along: `[roles]
1890 /// advisors` when set, otherwise the judges' roster, exactly as
1891 /// [`Self::advisors`] chooses its own list.
1892 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
1893 if self.roles.advisors.is_empty() {
1894 self.full_roster(&self.roles.judges)
1895 } else {
1896 self.full_roster(&self.roles.advisors)
1897 }
1898 }
1899
1900 /// Shell prefix for [`Verify`] commands.
1901 pub fn shell(&self) -> Vec<String> {
1902 if let Some(s) = &self.verify.shell {
1903 return s.clone();
1904 }
1905 if which("sh") {
1906 vec!["sh".to_owned(), "-c".to_owned()]
1907 } else {
1908 vec!["cmd".to_owned(), "/C".to_owned()]
1909 }
1910 }
1911
1912 /// Starter config, as written by `magi init`.
1913 pub fn starter_toml() -> String {
1914 let detected = Self::autodetected();
1915 let mut s = String::from(
1916 "# magi — blind multi-agent implementation competition.\n\
1917 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
1918 # -> blind judging -> deliberation -> private final vote\n\
1919 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
1920 #\n\
1921 # Rendered by teravars: a `[vars]` table, env\n\
1922 # and system lookups, and `include = [...]` all work. Tera\n\
1923 # braces are live everywhere in this file, but comments are\n\
1924 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
1925 # may quote `{{ ... }}` freely.\n\
1926 #\n\
1927 # Layers deep-merge in increasing\n\
1928 # precedence, so the roster can live once per machine in\n\
1929 # <config_dir>/magi/config.toml and each repo only states its own\n\
1930 # gate:\n\
1931 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
1932 [vars]\n\
1933 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
1934 # Single quotes inside the braces: teravars renders the raw file\n\
1935 # text, so TOML's own \\\" escaping never reaches Tera.\n\
1936 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
1937 );
1938 if detected.agents.is_empty() {
1939 s.push_str(
1940 "# No agent CLI was found on PATH. Fill this in by hand.\n\
1941 # kind = claude | opencode | antigravity | codex | command\n\
1942 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
1943 );
1944 } else {
1945 for a in &detected.agents {
1946 s.push_str("[[agents]]\n");
1947 s.push_str(&format!("id = {:?}\n", a.id));
1948 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
1949 if let Some(m) = &a.model {
1950 s.push_str(&format!("model = {m:?}\n"));
1951 }
1952 s.push('\n');
1953 }
1954 }
1955 s.push_str(
1956 "# Leave a role list empty to rotate through the roster.\n\
1957 [roles]\n\
1958 implementers = []\n\
1959 judges = []\n\
1960 reviewers = []\n\
1961 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
1962 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
1963 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
1964 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
1965 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
1966 [graph]\n\
1967 implementers = 3\n\
1968 judges = 3\n\
1969 deliberate_rounds = 1\n\
1970 reviewers = 3\n\
1971 review_rounds = 6\n\
1972 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
1973 gate_fix_rounds = 1\n\
1974 max_parallel = 4\n\
1975 language = \"en\"\n\
1976 # One CLI conversation per seat: judges keep their own argument\n\
1977 # across deliberation, the fixer keeps its implementation context.\n\
1978 sessions = true\n\
1979 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
1980 # the final gate inherit this value for compatibility.\n\
1981 timeout_review = 1200\n\
1982 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
1983 # verification independent if timeout_review changes later.\n\
1984 # timeout_verify = 1200\n\n\
1985 [verify]\n\
1986 # Run once per review round in the winner's worktree; failures are\n\
1987 # fed back to the fixer.\n\
1988 e2e = []\n\
1989 # Final gate. Every command must exit 0 before a merge.\n\
1990 gate = []\n\
1991 # Mechanical fixers (formatters) run in the winner's worktree just\n\
1992 # before the gate; whatever they change becomes one commit. A failing\n\
1993 # command only warns - the gate stays the arbiter. Same timeout as the\n\
1994 # gate (timeout_verify). Keep it light and idempotent.\n\
1995 # pre_gate = []\n\n\
1996 [merge]\n\
1997 # none | local | pr\n\
1998 mode = \"none\"\n\
1999 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2000 [update]\n\
2001 # off | notify | install — checked in the background, throttled.\n\
2002 mode = \"notify\"\n\
2003 # interval = \"24h\"\n\n\
2004 [daemon]\n\
2005 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2006 # no new commit and no check changing state before `magi serve`\n\
2007 # notices and asks you. A failed check is rerun once on its own;\n\
2008 # still red after that escalates at once. 0 turns the watcher off.\n\
2009 # release_stall_minutes = 60\n\n\
2010 [release]\n\
2011 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2012 # Actions never run (private, no minutes): the release pull request\n\
2013 # does not wait for CI, you approve the merge in magi, and then\n\
2014 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2015 # runs `commands` from a clean checkout of the merge commit. A\n\
2016 # failure holds the release with a notice; it is never retried blind.\n\
2017 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2018 # mode = \"actions\"\n\
2019 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2020 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2021 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2022 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2023 # timeout_minutes = 30\n",
2024 );
2025 s
2026 }
2027}
2028
2029/// Is `program` on `PATH`?
2030pub fn which(program: &str) -> bool {
2031 find_program(program).is_some()
2032}
2033
2034/// The file a bare `program` name resolves to on `PATH`, the way the OS shell
2035/// would find it.
2036///
2037/// Spawn agents through this, not by bare name: on Windows Rust's std
2038/// only tries `name.exe`, so a CLI installed as an npm `.cmd` shim (codex
2039/// since its 2026-09-23 reinstall) is "not found" even though a shell runs it.
2040/// On Windows an extensionless file is never a match: npm writes an `sh`
2041/// script beside every `.cmd` shim, and spawning that fails with os error 193.
2042pub fn find_program(program: &str) -> Option<PathBuf> {
2043 find_program_on(program, &std::env::var_os("PATH")?)
2044}
2045
2046/// [`find_program`] against an explicit `PATH`, for a child whose environment
2047/// overrides it.
2048pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2049 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2050 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2051}
2052
2053fn find_program_in(
2054 program: &str,
2055 paths: &std::ffi::OsStr,
2056 pathext: Option<&str>,
2057) -> Option<PathBuf> {
2058 let p = Path::new(program);
2059 if p.components().count() > 1 {
2060 return p.is_file().then(|| p.to_path_buf());
2061 }
2062 std::env::split_paths(paths).find_map(|dir| match pathext {
2063 Some(exts) => {
2064 let bare = dir.join(program);
2065 if p.extension().is_some() && bare.is_file() {
2066 return Some(bare);
2067 }
2068 exts.split(';')
2069 .filter(|e| !e.is_empty())
2070 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2071 .find(|c| c.is_file())
2072 }
2073 None => Some(dir.join(program)).filter(|c| c.is_file()),
2074 })
2075}
2076
2077/// Sidecar naming the checkout an extracted layer stands for.
2078const REPO_MARKER: &str = ".magi-repo";
2079
2080fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2081 use crate::proc::Quiet as _;
2082 let out = std::process::Command::new("git")
2083 .args(args)
2084 .quiet()
2085 .current_dir(repo)
2086 .stdin(std::process::Stdio::null())
2087 .output()
2088 .ok()?;
2089 out.status
2090 .success()
2091 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2092}
2093
2094/// Is `repo` inside a git working tree? A directory that is not has no branch
2095/// to be stale against, so its files are read as they are.
2096fn is_git_worktree(repo: &Path) -> bool {
2097 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2098}
2099
2100#[derive(Deserialize, Default)]
2101struct ProbeMerge {
2102 base: Option<String>,
2103 remote: Option<String>,
2104}
2105
2106#[derive(Deserialize, Default)]
2107struct Probe {
2108 merge: Option<ProbeMerge>,
2109}
2110
2111/// `[merge]` base / remote from one file, nothing else. The file is rendered
2112/// (env templates, includes) exactly as a real load would, so a machine layer
2113/// saying `base = "{{ env.X }}"` locates the same ref; when rendering fails
2114/// (a checkout file that needs its own repo context) the plain TOML is read
2115/// instead. Unreadable is `None`: the real load reports it.
2116fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2117 if !path.is_file() {
2118 return None;
2119 }
2120 let paths = [path.to_path_buf()];
2121 let mut engine = teravars::Engine::default();
2122 let mut ctx = Config::render_ctx(&paths);
2123 // The layered load renders every layer for the checkout being resolved;
2124 // so does this, or `{{ repo_name }}` would name the file's own directory.
2125 ctx.insert("repo", &repo.to_string_lossy());
2126 ctx.insert(
2127 "repo_name",
2128 &repo.file_name().unwrap_or_default().to_string_lossy(),
2129 );
2130 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2131 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2132 {
2133 return probe.merge;
2134 }
2135 let text = std::fs::read_to_string(path).ok()?;
2136 toml::from_str::<Probe>(&text).ok()?.merge
2137}
2138
2139/// The `[merge] remote` / `base` the layers name, before any git lookup.
2140fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2141 let mut remote = None;
2142 let mut base = None;
2143 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2144 sources.push(repo.join("magi.toml"));
2145 sources.push(repo.join(".magi").join("config.toml"));
2146 for path in sources {
2147 if let Some(m) = probe_merge(&path, repo) {
2148 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2149 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2150 }
2151 }
2152 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2153}
2154
2155/// Where the remote ref is: see the module doc for the order.
2156fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2157 let (remote, base) = probe_remote_base(repo);
2158 let base = match base {
2159 Some(b) => b,
2160 None => {
2161 let head = format!("refs/remotes/{remote}/HEAD");
2162 git_out(repo, &["symbolic-ref", "--quiet", &head])
2163 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2164 .with_context(|| {
2165 format!(
2166 "cannot tell which branch of `{remote}` holds magi.toml: \
2167 set [merge] base, or run `git remote set-head {remote} -a`"
2168 )
2169 })?
2170 }
2171 };
2172 Ok((remote, base))
2173}
2174
2175fn fnv_hex(text: &str) -> String {
2176 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2177 for b in text.bytes() {
2178 hash ^= u64::from(b);
2179 hash = hash.wrapping_mul(0x0100_0000_01b3);
2180 }
2181 format!("{hash:016x}")
2182}
2183
2184/// Does the text declare an `include` directive in any form teravars accepts
2185/// (root `include`, bare or quoted, or `[teravars] include`, as a table or an
2186/// inline table)? Parsed as TOML when it parses; a templated file that does
2187/// not parse is judged by a plain search for the word, because over-detecting
2188/// only costs an extra extraction while missing one fails the load.
2189fn declares_include(text: &str) -> bool {
2190 match toml::from_str::<toml::Table>(text) {
2191 Ok(table) => {
2192 table.contains_key("include")
2193 || table
2194 .get("teravars")
2195 .and_then(toml::Value::as_table)
2196 .is_some_and(|t| t.contains_key("include"))
2197 }
2198 Err(_) => text.contains("include"),
2199 }
2200}
2201
2202/// Unpack the whole tree of `sha` into `dest`, so relative `include`s of a
2203/// repository layer resolve against the same commit.
2204fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2205 use crate::proc::Quiet as _;
2206 let mut archive = std::process::Command::new("git")
2207 .args(["archive", "--format=tar", sha])
2208 .quiet()
2209 .current_dir(repo)
2210 .stdin(std::process::Stdio::null())
2211 .stdout(std::process::Stdio::piped())
2212 .stderr(std::process::Stdio::null())
2213 .spawn()
2214 .context("running git archive")?;
2215 let tar = std::process::Command::new("tar")
2216 .arg("-x")
2217 .arg("-C")
2218 .arg(dest)
2219 .quiet()
2220 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2221 .output()
2222 .context("running tar")?;
2223 let status = archive.wait().context("waiting for git archive")?;
2224 if !status.success() || !tar.status.success() {
2225 bail!(
2226 "cannot unpack {sha} for the config's includes: {}",
2227 String::from_utf8_lossy(&tar.stderr).trim()
2228 );
2229 }
2230 Ok(())
2231}
2232
2233/// The repository layers (`.magi/config.toml`, `magi.toml`; lowest first) of
2234/// `<remote>/<base>`, extracted from one commit so both files agree.
2235fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2236 let (remote, base) = resolve_remote_base(repo)?;
2237 let tracking = format!("refs/remotes/{remote}/{base}");
2238 let spec = format!("{tracking}^{{commit}}");
2239 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2240 .map(|s| s.trim().to_owned())
2241 .filter(|s| !s.is_empty())
2242 .with_context(|| {
2243 format!(
2244 "`{remote}/{base}` does not exist in this checkout; fetch it \
2245 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2246 a possibly stale local magi.toml instead"
2247 )
2248 })?;
2249 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2250 let rels = [".magi/config.toml", "magi.toml"];
2251 let mut texts: Vec<(&str, String)> = Vec::new();
2252 for rel in rels {
2253 let object = format!("{sha}:{rel}");
2254 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2255 continue;
2256 }
2257 let Some(text) = git_out(repo, &["show", &object]) else {
2258 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2259 };
2260 texts.push((rel, text));
2261 }
2262 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2263 // Content-addressed and built beside the final name, then renamed in: a
2264 // concurrent `discover` sees the whole directory or none of it, never a
2265 // half-written file.
2266 let build = |root: &Path| -> Result<PathBuf> {
2267 let final_dir = root.join(&key);
2268 if !final_dir.is_dir() {
2269 std::fs::create_dir_all(root)?;
2270 let tmp = root.join(format!(
2271 "{key}.tmp-{}-{}",
2272 std::process::id(),
2273 std::time::SystemTime::now()
2274 .duration_since(std::time::UNIX_EPOCH)
2275 .map(|d| d.as_nanos())
2276 .unwrap_or_default()
2277 ));
2278 let filled = (|| -> Result<()> {
2279 std::fs::create_dir_all(&tmp)?;
2280 if wants_tree {
2281 extract_tree(repo, &sha, &tmp)?;
2282 }
2283 for (rel, text) in &texts {
2284 let file = tmp.join(rel);
2285 let parent = file.parent().unwrap_or(&tmp);
2286 std::fs::create_dir_all(parent)?;
2287 std::fs::write(&file, text)?;
2288 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2289 }
2290 Ok(())
2291 })();
2292 if let Err(e) = filled {
2293 let _ = std::fs::remove_dir_all(&tmp);
2294 return Err(e);
2295 }
2296 if std::fs::rename(&tmp, &final_dir).is_err() {
2297 // Lost the race to another process building the same commit.
2298 let _ = std::fs::remove_dir_all(&tmp);
2299 if !final_dir.is_dir() {
2300 bail!("cannot place {}", final_dir.display());
2301 }
2302 }
2303 }
2304 Ok(final_dir)
2305 };
2306 let common = git_out(
2307 repo,
2308 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2309 )
2310 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2311 let dir = match common.map(|c| build(&c)) {
2312 Some(Ok(d)) => d,
2313 _ => build(&std::env::temp_dir().join("magi-config"))
2314 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2315 };
2316 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2317}
2318
2319#[cfg(test)]
2320mod tests {
2321 #[test]
2322 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
2323 let mut cfg = Config::default();
2324 assert_eq!(
2325 cfg.context_window("claude-sonnet-4-5-20250929"),
2326 Some(200_000)
2327 );
2328 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
2329 assert_eq!(cfg.context_window("mystery-model"), None);
2330 cfg.context_windows
2331 .insert("claude-sonnet-4-5".into(), 1_000_000);
2332 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
2333 cfg.context_windows.insert("mystery".into(), 32_768);
2334 // Longest user prefix beats a shorter one and the built-in table.
2335 assert_eq!(
2336 cfg.context_window("claude-sonnet-4-5-20250929"),
2337 Some(1_000_000)
2338 );
2339 // An exact name beats any prefix.
2340 cfg.context_windows
2341 .insert("claude-sonnet-4-5-20250929".into(), 7);
2342 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
2343 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
2344 }
2345
2346 use super::*;
2347
2348 /// npm writes an extensionless `sh` script beside `codex.cmd`; on Windows
2349 /// the `.cmd` is the spawnable one (os error 193 otherwise, 2026-09-23).
2350 #[test]
2351 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
2352 let dir = tempfile::tempdir().unwrap();
2353 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
2354 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
2355 let paths = dir.path().as_os_str();
2356 assert_eq!(
2357 find_program_in("codex", paths, Some(".EXE;.CMD")),
2358 Some(dir.path().join("codex.cmd"))
2359 );
2360 assert_eq!(
2361 find_program_in("codex", paths, None),
2362 Some(dir.path().join("codex"))
2363 );
2364 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
2365 }
2366
2367 fn spec(id: &str) -> AgentSpec {
2368 AgentSpec {
2369 id: id.to_owned(),
2370 kind: AgentKind::Command,
2371 model: None,
2372 command: vec!["true".to_owned()],
2373 extra_args: Vec::new(),
2374 env: BTreeMap::new(),
2375 prompt_delivery: None,
2376 }
2377 }
2378
2379 #[test]
2380 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
2381 // `timeout_verify` used to not exist: `verify.e2e`/`verify.gate` ran
2382 // under `timeout_review`. A config written before this field existed
2383 // must run exactly as before, which means its default has to be the
2384 // same 1200s `timeout_review` has always defaulted to.
2385 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
2386 assert_eq!(g.timeout_verify, None);
2387 assert_eq!(g.verify_timeout(), 3600);
2388 }
2389
2390 #[test]
2391 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
2392 // The bug this field exists to close: `[graph] timeout_review = 45`
2393 // used to shrink the real-machine `verify.e2e`/`verify.gate` budget
2394 // along with the reviewer seats' own timeout, because both read the
2395 // same field.
2396 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
2397 assert_eq!(g.timeout_review, 45);
2398 assert_eq!(
2399 g.verify_timeout(),
2400 45,
2401 "an omitted legacy value follows review"
2402 );
2403 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
2404 .expect("parse explicit override");
2405 assert_eq!(explicit.verify_timeout(), 1200);
2406 }
2407
2408 #[test]
2409 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
2410 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
2411 assert_eq!(g.implementers, 4);
2412 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
2413 assert_eq!(g.implementers, 5);
2414 }
2415
2416 fn layered(lower: &str, upper: &str) -> Result<Config> {
2417 let dir = tempfile::tempdir().unwrap();
2418 let a = dir.path().join("a.toml");
2419 let b = dir.path().join("b.toml");
2420 std::fs::write(&a, lower).unwrap();
2421 std::fs::write(&b, upper).unwrap();
2422 Config::load_layers(&[a, b])
2423 }
2424
2425 #[test]
2426 fn graph_implementers_higher_layer_wins_across_spellings() {
2427 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
2428 assert_eq!(c.graph.implementers, 5);
2429 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
2430 assert_eq!(c.graph.implementers, 5);
2431 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
2432 assert_eq!(c.graph.implementers, 2);
2433 }
2434
2435 #[test]
2436 fn graph_implementers_both_keys_in_one_layer_is_refused() {
2437 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
2438 .unwrap_err()
2439 .to_string();
2440 assert!(
2441 err.contains("candidates") && err.contains("implementers"),
2442 "{err}"
2443 );
2444 assert!(err.contains("b.toml"), "{err}");
2445 }
2446
2447 #[test]
2448 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
2449 // `deny_unknown_fields` cuts both ways: a config from before
2450 // `timeout_verify`/`e2e_every_round` existed must still parse, with
2451 // both defaulted rather than refused as unknown-in-reverse.
2452 let g: Graph =
2453 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
2454 .expect("an old-shaped [graph] table must still parse");
2455 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
2456 assert!(
2457 !g.e2e_every_round,
2458 "off by default, same as before this field existed"
2459 );
2460 }
2461
2462 #[test]
2463 fn empty_roles_rotate_judges_off_their_own_candidate() {
2464 // Three seats, said out loud: this is a test about *rotation*, and it
2465 // has nothing to say about how many candidates a task buys by default.
2466 let cfg = Config {
2467 agents: vec![spec("a"), spec("b"), spec("c")],
2468 graph: Graph {
2469 implementers: 3,
2470 ..Graph::default()
2471 },
2472 ..Config::default()
2473 };
2474 let roles = cfg.resolve_roles().unwrap();
2475 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
2476 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
2477 assert_eq!(impls, ["a", "b", "c"]);
2478 assert_eq!(judges, ["b", "c", "a"]);
2479 for (i, j) in judges.iter().enumerate() {
2480 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
2481 }
2482 }
2483
2484 #[test]
2485 fn single_agent_roster_fills_every_seat() {
2486 let cfg = Config {
2487 agents: vec![spec("solo")],
2488 graph: Graph {
2489 implementers: 3,
2490 ..Graph::default()
2491 },
2492 ..Config::default()
2493 };
2494 let roles = cfg.resolve_roles().unwrap();
2495 assert_eq!(roles.implementers.len(), 3);
2496 assert!(roles.judges.iter().all(|a| a.id == "solo"));
2497 }
2498
2499 #[test]
2500 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
2501 // `implementers = 1` (a solo run) still resolves `implementers` down to
2502 // one slot, but `implementer_roster` must carry every agent in the
2503 // roster, in file order, for `graph::Runner`'s quota fallback to walk
2504 // forward through once that one slot's agent runs out of quota.
2505 let cfg = Config {
2506 agents: vec![spec("a"), spec("b"), spec("c")],
2507 graph: Graph {
2508 implementers: 1,
2509 ..Graph::default()
2510 },
2511 ..Config::default()
2512 };
2513 let roles = cfg.resolve_roles().unwrap();
2514 assert_eq!(roles.implementers.len(), 1);
2515 let roster: Vec<&str> = roles
2516 .implementer_roster
2517 .iter()
2518 .map(|a| a.id.as_str())
2519 .collect();
2520 assert_eq!(roster, ["a", "b", "c"]);
2521 }
2522
2523 #[test]
2524 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
2525 let cfg = Config {
2526 agents: vec![spec("a"), spec("b"), spec("c")],
2527 roles: Roles {
2528 implementers: vec!["c".to_owned(), "a".to_owned()],
2529 ..Roles::default()
2530 },
2531 graph: Graph {
2532 implementers: 1,
2533 ..Graph::default()
2534 },
2535 ..Config::default()
2536 };
2537 let roles = cfg.resolve_roles().unwrap();
2538 // Unaffected by the new field: still just the first named id.
2539 assert_eq!(roles.implementers.len(), 1);
2540 assert_eq!(roles.implementers[0].id, "c");
2541 let roster: Vec<&str> = roles
2542 .implementer_roster
2543 .iter()
2544 .map(|a| a.id.as_str())
2545 .collect();
2546 assert_eq!(roster, ["c", "a"]);
2547 }
2548
2549 #[test]
2550 fn explicit_roles_win() {
2551 let cfg = Config {
2552 agents: vec![spec("a"), spec("b")],
2553 roles: Roles {
2554 implementers: vec!["b".to_owned()],
2555 judges: vec!["a".to_owned()],
2556 reviewers: Vec::new(),
2557 fixer: Some("a".into()),
2558 ..Roles::default()
2559 },
2560 ..Config::default()
2561 };
2562 let roles = cfg.resolve_roles().unwrap();
2563 assert!(roles.implementers.iter().all(|a| a.id == "b"));
2564 assert!(roles.judges.iter().all(|a| a.id == "a"));
2565 let fixer = roles.fixer.unwrap();
2566 assert_eq!(fixer.len(), 1);
2567 assert_eq!(fixer[0].id, "a");
2568 assert_eq!(roles.conductor.id, "a");
2569 }
2570
2571 #[test]
2572 fn fixer_takes_a_string_or_an_ordered_chain() {
2573 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
2574 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
2575 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
2576 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
2577
2578 let resolve = |fixer: Option<AgentChoice>| {
2579 Config {
2580 agents: vec![spec("a"), spec("b"), spec("c")],
2581 roles: Roles {
2582 fixer,
2583 ..Roles::default()
2584 },
2585 ..Config::default()
2586 }
2587 .resolve_roles()
2588 };
2589 let ids = |r: &ResolvedRoles| -> Vec<String> {
2590 r.fixer
2591 .as_ref()
2592 .unwrap()
2593 .iter()
2594 .map(|s| s.id.clone())
2595 .collect()
2596 };
2597 // The string form is a chain of one; unset stays unset (the winner's author).
2598 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
2599 assert!(resolve(None).unwrap().fixer.is_none());
2600 // Order kept, an unknown id skipped, a duplicate keeps its first place.
2601 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
2602 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
2603 // Nothing resolving names the role.
2604 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
2605 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
2606 }
2607
2608 #[test]
2609 fn unknown_agent_id_is_an_error() {
2610 let cfg = Config {
2611 agents: vec![spec("a")],
2612 roles: Roles {
2613 judges: vec!["nope".to_owned()],
2614 ..Roles::default()
2615 },
2616 ..Config::default()
2617 };
2618 assert!(cfg.resolve_roles().is_err());
2619 }
2620
2621 #[test]
2622 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
2623 let mut cfg = Config {
2624 agents: vec![spec("a"), spec("b")],
2625 ..Config::default()
2626 };
2627 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
2628
2629 cfg.roles.conductor = Some("b".into());
2630 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
2631
2632 cfg.roles.conductor = Some("missing".into());
2633 assert!(cfg.resolve_roles().is_err());
2634 }
2635
2636 #[test]
2637 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
2638 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
2639 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
2640 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
2641
2642 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
2643 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
2644 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
2645
2646 for roles in [one, chain] {
2647 let text = toml::to_string(&roles).unwrap();
2648 let back: Roles = toml::from_str(&text).unwrap();
2649 assert_eq!(back.synthesizer, roles.synthesizer);
2650 assert_eq!(back.chatter, roles.chatter);
2651 }
2652 let text = toml::to_string(&Roles {
2653 conductor: Some("x".into()),
2654 ..Roles::default()
2655 })
2656 .unwrap();
2657 assert!(
2658 text.contains("conductor = \"x\""),
2659 "string stays a string: {text}"
2660 );
2661 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
2662 }
2663
2664 #[test]
2665 fn an_empty_choice_counts_as_unset() {
2666 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
2667 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
2668 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
2669 }
2670
2671 #[test]
2672 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
2673 // Unlike `conductor`, `synthesizer` is never validated by
2674 // `resolve_roles` — it is looked up lazily by
2675 // `graph::Runner::synthesize_brief` the same way `[roles] chatter`
2676 // is looked up by `talk::begin`, so this exercises `agent::pick`
2677 // directly instead of going through `resolve_roles`.
2678 let mut cfg = Config {
2679 agents: vec![spec("a"), spec("b")],
2680 ..Config::default()
2681 };
2682 let want = primary(cfg.roles.synthesizer.as_ref());
2683 assert_eq!(
2684 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
2685 .unwrap()
2686 .id,
2687 "a",
2688 "unset falls back to agent::pick's own default order"
2689 );
2690
2691 cfg.roles.synthesizer = Some("b".into());
2692 let want = primary(cfg.roles.synthesizer.as_ref());
2693 assert_eq!(
2694 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
2695 .unwrap()
2696 .id,
2697 "b",
2698 "the named agent wins over the default order"
2699 );
2700 }
2701
2702 #[test]
2703 fn empty_roster_is_an_error() {
2704 assert!(Config::default().resolve_roles().is_err());
2705 }
2706
2707 #[test]
2708 fn advise_defaults_to_on_with_three_proposals() {
2709 let g = Graph::default();
2710 assert!(g.advise);
2711 assert_eq!(g.advisors, 3);
2712 }
2713
2714 #[test]
2715 fn unset_advisors_falls_back_to_the_judge_roster() {
2716 let cfg = Config {
2717 agents: vec![spec("a"), spec("b")],
2718 roles: Roles {
2719 judges: vec!["b".to_owned()],
2720 ..Roles::default()
2721 },
2722 graph: Graph {
2723 advisors: 2,
2724 ..Graph::default()
2725 },
2726 ..Config::default()
2727 };
2728 let advisors = cfg.advisors().expect("advisors resolve");
2729 assert_eq!(advisors.len(), 2);
2730 assert!(
2731 advisors.iter().all(|a| a.id == "b"),
2732 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
2733 );
2734 }
2735
2736 #[test]
2737 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
2738 let cfg = Config {
2739 agents: vec![spec("a"), spec("b")],
2740 roles: Roles {
2741 judges: vec!["b".to_owned()],
2742 advisors: vec!["a".to_owned()],
2743 ..Roles::default()
2744 },
2745 graph: Graph {
2746 advisors: 2,
2747 ..Graph::default()
2748 },
2749 ..Config::default()
2750 };
2751 let advisors = cfg.advisors().expect("advisors resolve");
2752 assert!(advisors.iter().all(|a| a.id == "a"));
2753 }
2754
2755 /// Neither `[roles] advisors` nor `[roles] judges` set: an unconfigured
2756 /// advisor roster must resolve to the exact same agents an unconfigured
2757 /// judge panel would get - same ids, same rotation offset - or the
2758 /// promise in [`Roles::advisors`]'s doc ("advisor diversity for free")
2759 /// does not actually hold.
2760 #[test]
2761 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
2762 let cfg = Config {
2763 agents: vec![spec("a"), spec("b"), spec("c")],
2764 graph: Graph {
2765 advisors: 3,
2766 judges: 3,
2767 ..Graph::default()
2768 },
2769 ..Config::default()
2770 };
2771 let advisors = cfg.advisors().expect("advisors resolve");
2772 let judges = cfg.resolve_roles().expect("roles resolve").judges;
2773 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
2774 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
2775 assert_eq!(
2776 advisor_ids, judge_ids,
2777 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
2778 );
2779 }
2780
2781 #[test]
2782 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
2783 let cfg = Config {
2784 agents: vec![spec("a")],
2785 roles: Roles {
2786 advisors: vec!["nope".to_owned()],
2787 ..Roles::default()
2788 },
2789 graph: Graph {
2790 advisors: 1,
2791 ..Graph::default()
2792 },
2793 ..Config::default()
2794 };
2795 let err = cfg.advisors().expect_err("`nope` is not in the roster");
2796 assert!(format!("{err:#}").contains("nope"));
2797 }
2798
2799 #[test]
2800 fn repos_default_to_no_roots_and_a_day_of_trust() {
2801 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
2802 assert_eq!(Config::default().repos.scan_ttl, 86_400);
2803 assert_eq!(Config::default().repos.fetch_interval, 600);
2804 }
2805
2806 #[test]
2807 fn a_config_file_with_no_repos_table_still_loads() {
2808 let dir = tempfile::tempdir().unwrap();
2809 let path = dir.path().join("magi.toml");
2810 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
2811 let cfg = Config::load(&path).expect("must load without [repos]");
2812 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
2813 assert_eq!(cfg.repos.scan_ttl, 86_400);
2814 }
2815
2816 /// A fixture is the whole config under test.
2817 ///
2818 /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
2819 /// a machine where somebody had written `<config_dir>/magi/config.toml`
2820 /// the suite silently loaded it as the lowest layer. Adding `[repos]
2821 /// roots` there turned two web tests red - their fixtures declare
2822 /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
2823 /// array key spread across two layers. CI stayed green throughout,
2824 /// because a runner has no such file: the suite failed only where magi is
2825 /// actually used.
2826 ///
2827 /// So a test build has no machine layer unless it asks for one, and this
2828 /// is that promise. Written against a real file at the real location so
2829 /// it fails if `machine_layer` starts reading it again.
2830 #[test]
2831 fn a_test_build_does_not_read_the_operators_machine_config() {
2832 let repo = tempfile::tempdir().unwrap();
2833 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
2834
2835 let layers = Config::layers(repo.path());
2836 assert_eq!(
2837 layers,
2838 vec![repo.path().join("magi.toml")],
2839 "only the fixture's own file may be a layer"
2840 );
2841 if let Some(real) = dirs::config_dir() {
2842 let machine = real.join("magi").join("config.toml");
2843 assert!(
2844 !layers.contains(&machine),
2845 "the operator's {} must not be a layer in a test build",
2846 machine.display()
2847 );
2848 }
2849 }
2850
2851 #[test]
2852 fn starter_toml_loads_through_teravars() {
2853 let dir = tempfile::tempdir().unwrap();
2854 let path = dir.path().join("magi.toml");
2855 std::fs::write(&path, Config::starter_toml()).unwrap();
2856 let parsed = Config::load(&path).expect("starter config must load");
2857 assert_eq!(parsed.graph.implementers, 3);
2858 assert_eq!(parsed.merge.mode, MergeMode::None);
2859 assert_eq!(parsed.merge.style, MergeStyle::Merge);
2860 assert!(parsed.graph.sessions);
2861 assert_eq!(parsed.graph.timeout_review, 1200);
2862 assert_eq!(parsed.graph.verify_timeout(), 1200);
2863 assert_eq!(parsed.update.mode, UpdateMode::Notify);
2864 }
2865
2866 #[test]
2867 fn release_defaults_to_actions_and_the_starter_documents_it() {
2868 let dir = tempfile::tempdir().unwrap();
2869 let path = dir.path().join("magi.toml");
2870 std::fs::write(&path, Config::starter_toml()).unwrap();
2871 let r = Config::load(&path).unwrap().release;
2872 assert_eq!(r.mode, ReleaseMode::Actions);
2873 assert!(!r.is_local());
2874 assert!(r.commands.is_empty());
2875 assert_eq!(r.timeout_minutes, 30);
2876 assert!(Config::starter_toml().contains("# mode = \"actions\""));
2877 }
2878
2879 #[test]
2880 fn release_local_parses_and_unknown_keys_are_refused() {
2881 let dir = tempfile::tempdir().unwrap();
2882 let path = dir.path().join("magi.toml");
2883 std::fs::write(
2884 &path,
2885 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
2886 )
2887 .unwrap();
2888 let r = Config::load(&path).unwrap().release;
2889 assert!(r.is_local());
2890 assert_eq!(r.commands.len(), 2);
2891 assert_eq!(r.timeout_minutes, 5);
2892 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
2893 assert!(Config::load(&path).is_err());
2894 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
2895 assert!(Config::load(&path).is_err());
2896 }
2897
2898 #[test]
2899 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
2900 let dir = tempfile::tempdir().unwrap();
2901 let path = dir.path().join("magi.toml");
2902 std::fs::write(&path, Config::starter_toml()).unwrap();
2903 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
2904 assert!(Config::starter_toml().contains("# pre_gate = []"));
2905 }
2906
2907 #[test]
2908 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
2909 let starter = Config::starter_toml();
2910 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
2911 assert!(starter.contains("verification independent if timeout_review changes later"));
2912 assert!(starter.contains("# timeout_verify = 1200"));
2913 }
2914
2915 /// A repository whose ruleset forbids merge commits declares that once,
2916 /// here, rather than magi asking GitHub about it on every render (see
2917 /// [`MergeStyle`]'s own doc for why).
2918 #[test]
2919 fn a_repository_can_declare_a_linear_history_merge_style() {
2920 let dir = tempfile::tempdir().unwrap();
2921 let path = dir.path().join("magi.toml");
2922 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
2923 let parsed = Config::load(&path).expect("config must load");
2924 assert_eq!(parsed.merge.style, MergeStyle::Squash);
2925 }
2926
2927 #[test]
2928 fn later_layers_win_and_vars_render() {
2929 let dir = tempfile::tempdir().unwrap();
2930 let machine = dir.path().join("machine.toml");
2931 let project = dir.path().join("magi.toml");
2932 // The machine layer owns the roster...
2933 std::fs::write(
2934 &machine,
2935 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
2936 [graph]\ncandidates = 3\nmax_parallel = 8\n",
2937 )
2938 .unwrap();
2939 // ...and the project layer only states what is repo-specific, plus a
2940 // `[vars]` value interpolated into a command.
2941 std::fs::write(
2942 &project,
2943 "[vars]\ncache = \"/shared\"\n\n\
2944 [graph]\ncandidates = 2\n\n\
2945 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
2946 )
2947 .unwrap();
2948
2949 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
2950 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
2951 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
2952 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
2953 assert_eq!(
2954 cfg.verify.gate,
2955 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
2956 );
2957 // The rendered command is where the cache path is read back from.
2958 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
2959 }
2960
2961 #[test]
2962 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
2963 // An operator who writes no `[graph]` timeout keys at all must still
2964 // land on the hour, not on the five/fifteen minutes this turn used
2965 // to hardcode before it read from config.
2966 let g = Graph::default();
2967 assert_eq!(g.timeout_talk, 3600);
2968
2969 let dir = tempfile::tempdir().unwrap();
2970 let path = dir.path().join("magi.toml");
2971 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
2972 let cfg = Config::load(&path).expect("must load without timeout_talk set");
2973 assert_eq!(cfg.graph.timeout_talk, 3600);
2974 }
2975
2976 #[test]
2977 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
2978 let dir = tempfile::tempdir().unwrap();
2979 let path = dir.path().join("magi.toml");
2980 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
2981 let cfg = Config::load(&path).expect("must load");
2982 assert_eq!(cfg.graph.timeout_talk, 120);
2983 }
2984
2985 #[test]
2986 fn the_disk_defaults_are_the_measurements_made_up_front() {
2987 let cfg = Config::default();
2988 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
2989 assert!(cfg.disk.auto_fold);
2990 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
2991 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
2992 }
2993
2994 #[test]
2995 fn an_unset_disk_section_is_the_safe_default() {
2996 let dir = tempfile::tempdir().unwrap();
2997 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
2998 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
2999 assert_eq!(cfg.disk, Disk::default());
3000 }
3001
3002 #[test]
3003 fn env_is_available_to_templates_with_a_default() {
3004 let dir = tempfile::tempdir().unwrap();
3005 let path = dir.path().join("magi.toml");
3006 // teravars ships no `env`; magi adds it, and the `default` filter has
3007 // to cover the unset case or every machine would need the variable.
3008 //
3009 // Deliberately no named variable: `env` is keyed by the exact spelling
3010 // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
3011 // test asserting `env.PATH` passes on one runner and fails on another.
3012 // The map's non-emptiness is the platform-neutral claim.
3013 std::fs::write(
3014 &path,
3015 "[verify]\n\
3016 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
3017 \"populated={{ env | length > 0 }}\"]\n",
3018 )
3019 .unwrap();
3020 let cfg = Config::load(&path).expect("env lookup must render");
3021 assert_eq!(cfg.verify.gate[0], "cache=fallback");
3022 assert_eq!(cfg.verify.gate[1], "populated=true");
3023 }
3024
3025 #[test]
3026 fn a_broken_template_names_the_file() {
3027 let dir = tempfile::tempdir().unwrap();
3028 let path = dir.path().join("magi.toml");
3029 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
3030 let err = Config::load(&path).expect_err("must not silently ignore");
3031 assert!(err.to_string().contains("teravars"), "{err}");
3032 }
3033
3034 #[test]
3035 fn tera_syntax_in_comments_is_inert() {
3036 // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
3037 // comment may quote template syntax without rendering. Before 0.2.2 this
3038 // load failed: the commented-out braces reached the template parser.
3039 let dir = tempfile::tempdir().unwrap();
3040 let path = dir.path().join("magi.toml");
3041 std::fs::write(
3042 &path,
3043 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
3044 [graph]\ncandidates = 2\n",
3045 )
3046 .unwrap();
3047 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
3048 assert_eq!(cfg.graph.implementers, 2);
3049 }
3050
3051 #[test]
3052 fn opencode_defaults_to_file_delivery() {
3053 let mut s = spec("oc");
3054 s.kind = AgentKind::Opencode;
3055 assert_eq!(s.delivery(), Delivery::File);
3056 s.prompt_delivery = Some(Delivery::Argv);
3057 assert_eq!(s.delivery(), Delivery::Argv);
3058 }
3059 #[test]
3060 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
3061 // Both default on, and that pair is the safety property: `land` takes
3062 // over the watching an operator was doing by hand, `land_approval`
3063 // keeps the irreversible step a human decision. An unattended merge
3064 // needs BOTH flipped, which has to be chosen deliberately twice.
3065 let g = Graph::default();
3066 assert!(
3067 g.land,
3068 "stopping at an open PR left the watching to a human"
3069 );
3070 assert!(
3071 g.land_approval,
3072 "on-by-default land is only defensible while this is also on"
3073 );
3074 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
3075 assert!(
3076 g.hold_contested_merge,
3077 "a contested hand-off must still reach a human when approvals are off"
3078 );
3079 }
3080 #[test]
3081 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
3082 // teravars appends arrays. For an ordered list of seats, or an argv,
3083 // the concatenation is something neither file says - and the operator
3084 // pays for the extra seats by the token.
3085 let dir = tempfile::tempdir().unwrap();
3086 let machine = dir.path().join("machine.toml");
3087 let repo = dir.path().join("magi.toml");
3088 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
3089 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
3090
3091 let err = Config::load_layers(&[machine.clone(), repo.clone()])
3092 .expect_err("two layers naming one array must not merge silently")
3093 .to_string();
3094 assert!(err.contains("roles.implementers"), "{err}");
3095 // Both files are named: the fix is to delete one of them, and the
3096 // operator has to know which two to choose between.
3097 assert!(err.contains("machine.toml"), "{err}");
3098 assert!(err.contains("magi.toml"), "{err}");
3099 }
3100
3101 #[test]
3102 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
3103 // The split the layering exists for: state a preference machine-wide,
3104 // let the repository own its own lists.
3105 let dir = tempfile::tempdir().unwrap();
3106 let machine = dir.path().join("machine.toml");
3107 let repo = dir.path().join("magi.toml");
3108 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
3109 std::fs::write(
3110 &repo,
3111 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
3112 [roles]\nimplementers = [\"oc\"]\n",
3113 )
3114 .unwrap();
3115
3116 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
3117 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
3118 assert_eq!(cfg.roles.implementers, ["oc"]);
3119 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
3120 }
3121
3122 #[test]
3123 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
3124 // The `editorconfig-checker` distribution problem: a shared layer
3125 // wants to add a gate command without erasing the repository's own.
3126 let dir = tempfile::tempdir().unwrap();
3127 let machine = dir.path().join("machine.toml");
3128 let repo = dir.path().join("magi.toml");
3129 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
3130 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3131
3132 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3133 assert_eq!(
3134 cfg.verify.gate,
3135 [
3136 "editorconfig-checker".to_owned(),
3137 "cargo make check".to_owned()
3138 ],
3139 "low-priority (machine) command first, high-priority (repo) command after"
3140 );
3141 }
3142
3143 #[test]
3144 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
3145 let dir = tempfile::tempdir().unwrap();
3146 let machine = dir.path().join("machine.toml");
3147 let repo = dir.path().join("magi.toml");
3148 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
3149 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
3150
3151 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3152 assert_eq!(
3153 cfg.verify.e2e,
3154 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
3155 );
3156 }
3157
3158 #[test]
3159 fn two_layers_declaring_repos_roots_are_both_scanned() {
3160 let dir = tempfile::tempdir().unwrap();
3161 let machine = dir.path().join("machine.toml");
3162 let repo = dir.path().join("magi.toml");
3163 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
3164 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
3165
3166 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3167 assert_eq!(
3168 cfg.repos.roots,
3169 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
3170 );
3171 }
3172
3173 #[test]
3174 fn duplicate_gate_commands_across_layers_both_run() {
3175 // Dropping the duplicate would be a silent surprise; the operator
3176 // sees a slower gate, never a missing one.
3177 let dir = tempfile::tempdir().unwrap();
3178 let machine = dir.path().join("machine.toml");
3179 let repo = dir.path().join("magi.toml");
3180 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
3181 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
3182
3183 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3184 assert_eq!(
3185 cfg.verify.gate,
3186 ["same-command".to_owned(), "same-command".to_owned()]
3187 );
3188 }
3189
3190 #[test]
3191 fn notify_command_is_still_refused_across_two_layers() {
3192 // An argv, not a set: concatenating two of them is not a program.
3193 let dir = tempfile::tempdir().unwrap();
3194 let machine = dir.path().join("machine.toml");
3195 let repo = dir.path().join("magi.toml");
3196 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
3197 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
3198
3199 let err = Config::load_layers(&[machine.clone(), repo.clone()])
3200 .expect_err("an argv split across layers must not concatenate")
3201 .to_string();
3202 assert!(err.contains("notify.command"), "{err}");
3203 assert!(err.contains("machine.toml"), "{err}");
3204 assert!(err.contains("magi.toml"), "{err}");
3205 }
3206
3207 #[test]
3208 fn one_layer_declaring_verify_gate_runs_unchanged() {
3209 // The classification must not change behaviour for the configuration
3210 // this very repository has today: exactly one layer names the gate.
3211 let dir = tempfile::tempdir().unwrap();
3212 let path = dir.path().join("magi.toml");
3213 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3214
3215 let cfg = Config::load(&path).expect("single layer must still load");
3216 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
3217 }
3218
3219 #[test]
3220 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
3221 let dir = tempfile::tempdir().unwrap();
3222 let machine = dir.path().join("machine.toml");
3223 let repo = dir.path().join("magi.toml");
3224 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
3225 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3226 let paths = vec![machine.clone(), repo.clone()];
3227
3228 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
3229 let described =
3230 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
3231 assert!(described.contains("editorconfig-checker && cargo make check"));
3232 assert!(
3233 described.contains(&machine.display().to_string()),
3234 "{described}"
3235 );
3236 assert!(
3237 described.contains(&repo.display().to_string()),
3238 "{described}"
3239 );
3240
3241 // A single contributing layer stays the plain one-line summary.
3242 let single = vec![repo.clone()];
3243 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
3244 let solo_described =
3245 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
3246 assert_eq!(solo_described, "cargo make check");
3247 }
3248
3249 mod remote_layers {
3250 use super::*;
3251
3252 fn git(dir: &Path, args: &[&str]) {
3253 use crate::proc::Quiet as _;
3254 let out = std::process::Command::new("git")
3255 .args(args)
3256 .quiet()
3257 .current_dir(dir)
3258 .output()
3259 .unwrap();
3260 assert!(out.status.success(), "git {args:?}: {out:?}");
3261 }
3262
3263 /// A checkout whose origin/main carries `remote` as magi.toml and whose
3264 /// working tree carries `disk`.
3265 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
3266 let tmp = tempfile::tempdir().unwrap();
3267 let bare = tmp.path().join("o.git");
3268 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
3269 let repo = tmp.path().join("repo");
3270 std::fs::create_dir_all(&repo).unwrap();
3271 git(&repo, &["init", "-b", "trunk"]);
3272 git(&repo, &["config", "user.name", "t"]);
3273 git(&repo, &["config", "user.email", "t@example.com"]);
3274 std::fs::write(repo.join("magi.toml"), remote).unwrap();
3275 git(&repo, &["add", "-A"]);
3276 git(&repo, &["commit", "-m", "x"]);
3277 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
3278 git(&repo, &["push", "origin", "trunk"]);
3279 git(&repo, &["fetch", "origin"]);
3280 git(&repo, &["remote", "set-head", "origin", "trunk"]);
3281 std::fs::write(repo.join("magi.toml"), disk).unwrap();
3282 (tmp, repo)
3283 }
3284
3285 #[test]
3286 fn reads_the_remote_blob_not_the_working_tree() {
3287 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3288 let (cfg, _) = Config::discover(&repo, None).unwrap();
3289 assert_eq!(cfg.graph.implementers, 2);
3290 }
3291
3292 #[test]
3293 fn detached_head_still_reads_the_remote() {
3294 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3295 git(&repo, &["checkout", "--detach"]);
3296 let (cfg, _) = Config::discover(&repo, None).unwrap();
3297 assert_eq!(cfg.graph.implementers, 2);
3298 }
3299
3300 #[test]
3301 fn a_missing_ref_is_an_error_not_a_fallback() {
3302 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3303 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
3304 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
3305 assert!(err.contains("origin"), "{err}");
3306 }
3307
3308 #[test]
3309 fn merge_base_in_the_checkout_locates_the_ref() {
3310 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
3311 assert!(Config::discover(&repo, None).is_err());
3312 }
3313
3314 #[test]
3315 fn the_magi_dir_layer_is_read_too() {
3316 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3317 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3318 std::fs::create_dir_all(repo.join(".magi")).unwrap();
3319 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
3320 git(&repo, &["add", "-A"]);
3321 git(&repo, &["commit", "-m", "y"]);
3322 git(&repo, &["push", "origin", "trunk"]);
3323 git(&repo, &["fetch", "origin"]);
3324 let (cfg, layers) = Config::discover(&repo, None).unwrap();
3325 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
3326 assert_eq!(layers.len(), 2);
3327 }
3328
3329 #[test]
3330 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
3331 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
3332 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
3333 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
3334 git(&repo, &["add", "-A"]);
3335 git(&repo, &["commit", "-m", "inc"]);
3336 git(&repo, &["push", "origin", "trunk"]);
3337 git(&repo, &["fetch", "origin"]);
3338 // The working tree's copy differs and must not be used.
3339 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
3340 let (cfg, _) = Config::discover(&repo, None).unwrap();
3341 assert_eq!(cfg.graph.implementers, 2);
3342 }
3343
3344 #[test]
3345 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
3346 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
3347 let m = t.path().join("machine.toml");
3348 std::fs::write(
3349 &m,
3350 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
3351 )
3352 .unwrap();
3353 let (remote, base) = {
3354 let probe = probe_merge(&m, &repo).unwrap();
3355 (probe.remote, probe.base)
3356 };
3357 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
3358 }
3359
3360 #[test]
3361 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
3362 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3363 let m = t.path().join("machine.toml");
3364 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
3365 let probe = probe_merge(&m, &repo).unwrap();
3366 assert_eq!(probe.base.as_deref(), Some("repo"));
3367 }
3368
3369 #[test]
3370 fn every_include_form_is_recognised() {
3371 assert!(declares_include("include = [\"a.toml\"]\n"));
3372 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
3373 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
3374 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
3375 assert!(!declares_include("[graph]\ncandidates = 2\n"));
3376 }
3377
3378 #[test]
3379 fn an_explicit_config_is_read_as_named() {
3380 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3381 let own = t.path().join("own.toml");
3382 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
3383 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
3384 assert_eq!(cfg.graph.implementers, 4);
3385 }
3386
3387 #[test]
3388 fn discover_fetched_fails_when_the_fetch_does() {
3389 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3390 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
3391 let rt = tokio::runtime::Builder::new_current_thread()
3392 .enable_all()
3393 .build()
3394 .unwrap();
3395 let err = rt
3396 .block_on(Config::discover_fetched(&repo, None))
3397 .unwrap_err();
3398 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
3399 }
3400
3401 #[test]
3402 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
3403 // Never-fetched remote + followRemoteHEAD=never: fetch creates
3404 // origin/trunk but not origin/HEAD, which discovery then re-reads.
3405 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3406 git(&repo, &["remote", "set-head", "origin", "-d"]);
3407 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
3408 git(
3409 &repo,
3410 &["config", "remote.origin.followRemoteHEAD", "never"],
3411 );
3412 let rt = tokio::runtime::Builder::new_current_thread()
3413 .enable_all()
3414 .build()
3415 .unwrap();
3416 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
3417 assert_eq!(cfg.graph.implementers, 2);
3418 }
3419
3420 #[test]
3421 fn a_non_git_directory_reads_its_files() {
3422 let dir = tempfile::tempdir().unwrap();
3423 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
3424 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
3425 assert_eq!(cfg.graph.implementers, 4);
3426 }
3427 }
3428}