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