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