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