1use std::collections::BTreeMap;
42use std::path::{Path, PathBuf};
43
44use anyhow::{Context as _, Result, bail};
45use serde::{Deserialize, Serialize};
46
47#[derive(Debug, thiserror::Error)]
50#[error("{stage}: {target}")]
51pub(crate) struct ConfigFailure {
52 pub(crate) stage: &'static str,
53 pub(crate) target: String,
54}
55
56impl ConfigFailure {
57 fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
58 let stage = match error {
59 teravars::Error::Io(_) => "config-read",
60 teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
61 teravars::Error::Render(_) => "config-template",
62 teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
63 "config-include"
64 }
65 _ => "config-render",
66 };
67 Self::layers(stage, paths)
68 }
69
70 fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
71 let targets: Vec<_> = paths
72 .iter()
73 .map(|path| {
74 path.ancestors()
77 .find(|p| p.join(REPO_MARKER).is_file())
78 .and_then(|root| path.strip_prefix(root).ok())
79 .unwrap_or(path)
80 .to_string_lossy()
81 .into_owned()
82 })
83 .collect();
84 Self {
85 stage,
86 target: serde_json::to_string(&targets).expect("config paths"),
87 }
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
93#[serde(rename_all = "lowercase")]
94pub enum AgentKind {
95 Claude,
97 Opencode,
99 Antigravity,
103 Codex,
107 Omp,
113 Command,
115}
116
117impl AgentKind {
118 pub fn program(self) -> Option<&'static str> {
120 match self {
121 Self::Claude => Some("claude"),
122 Self::Opencode => Some("opencode"),
123 Self::Antigravity => Some("agy"),
124 Self::Codex => Some("codex"),
125 Self::Omp => Some("omp"),
126 Self::Command => None,
127 }
128 }
129
130 pub fn as_str(self) -> &'static str {
132 match self {
133 Self::Claude => "claude",
134 Self::Opencode => "opencode",
135 Self::Antigravity => "antigravity",
136 Self::Codex => "codex",
137 Self::Omp => "omp",
138 Self::Command => "command",
139 }
140 }
141
142 pub const ALL: [Self; 6] = [
150 Self::Claude,
151 Self::Opencode,
152 Self::Antigravity,
153 Self::Codex,
154 Self::Omp,
155 Self::Command,
156 ];
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
161#[serde(rename_all = "lowercase")]
162pub enum Delivery {
163 Stdin,
165 Argv,
167 File,
169}
170
171#[derive(Debug, Clone, Deserialize, Serialize)]
173#[serde(deny_unknown_fields)]
174pub struct AgentSpec {
175 pub id: String,
177 pub kind: AgentKind,
179 #[serde(default)]
181 pub model: Option<String>,
182 #[serde(default)]
185 pub command: Vec<String>,
186 #[serde(default)]
188 pub extra_args: Vec<String>,
189 #[serde(default)]
191 pub env: BTreeMap<String, String>,
192 #[serde(default)]
194 pub prompt_delivery: Option<Delivery>,
195}
196
197impl AgentSpec {
198 pub fn delivery(&self) -> Delivery {
204 self.prompt_delivery.unwrap_or(match self.kind {
205 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
206 AgentKind::Codex => Delivery::Stdin,
210 AgentKind::Omp => Delivery::Stdin,
214 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
215 })
216 }
217
218 pub fn display(&self) -> String {
220 match &self.model {
221 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
222 None => format!("{} ({})", self.id, self.kind.as_str()),
223 }
224 }
225}
226
227#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
234#[serde(untagged)]
235pub enum AgentChoice {
236 One(String),
238 Chain(Vec<String>),
240}
241
242impl AgentChoice {
243 pub fn ids(&self) -> Vec<&str> {
245 let all: Vec<&str> = match self {
246 Self::One(id) => vec![id.as_str()],
247 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
248 };
249 all.into_iter()
250 .map(str::trim)
251 .filter(|id| !id.is_empty())
252 .collect()
253 }
254
255 pub fn primary(&self) -> Option<&str> {
257 self.ids().into_iter().next()
258 }
259}
260
261impl From<&str> for AgentChoice {
262 fn from(id: &str) -> Self {
263 Self::One(id.to_owned())
264 }
265}
266
267pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
269 choice.and_then(AgentChoice::primary)
270}
271
272#[derive(Debug, Clone, Default, Deserialize, Serialize)]
275#[serde(deny_unknown_fields, default)]
276pub struct Roles {
277 pub implementers: Vec<String>,
279 pub judges: Vec<String>,
281 pub reviewers: Vec<String>,
283 pub fixer: Option<AgentChoice>,
292 pub chatter: Option<AgentChoice>,
306 pub dupes_judge: Option<AgentChoice>,
310 pub conductor: Option<AgentChoice>,
323 pub advisors: Vec<String>,
334 pub synthesizer: Option<AgentChoice>,
347 pub language_judge: Option<AgentChoice>,
356}
357
358#[derive(Debug, Clone, Deserialize, Serialize)]
360#[serde(deny_unknown_fields, default)]
361pub struct Graph {
362 pub github_text_guard: bool,
364 pub github_language: String,
370 #[serde(alias = "candidates")]
402 pub implementers: usize,
403 #[serde(default)]
405 pub selected_implementer: Option<String>,
406 pub judges: usize,
408 pub deliberate_rounds: usize,
410 pub reviewers: usize,
418 pub review_rounds: usize,
420 pub gate_fix_rounds: usize,
426 pub max_parallel: usize,
428 pub language: String,
430 pub sessions: bool,
438 pub timeout_implement: u64,
440 pub timeout_judge: u64,
442 pub timeout_review: u64,
444 pub timeout_verify: Option<u64>,
453 pub timeout_fix: u64,
455 pub timeout_talk: u64,
463 pub timeout_resource_wait: u64,
472 pub retries: usize,
474 pub worktree_root: Option<PathBuf>,
476 pub land: bool,
489 pub land_rounds: usize,
491 pub rerun_flaky_checks: bool,
499 pub land_approval: bool,
510 pub hold_contested_merge: bool,
524 pub file_followups: bool,
531 pub release_deputy_followups: bool,
539 pub answer_timeout: u64,
543 pub incomplete_review: IncompleteReviewPolicy,
546 pub e2e_every_round: bool,
564 pub advise: bool,
578 pub advisors: usize,
583 pub graft_runner_up: bool,
592}
593
594impl Default for Graph {
595 fn default() -> Self {
596 Self {
597 github_text_guard: true,
598 github_language: "en".into(),
599 implementers: 1,
600 selected_implementer: None,
601 judges: 3,
602 deliberate_rounds: 1,
603 reviewers: 3,
604 review_rounds: 6,
605 gate_fix_rounds: 1,
606 max_parallel: 4,
607 language: "en".to_owned(),
608 sessions: true,
609 timeout_implement: 3600,
610 timeout_judge: 1200,
611 timeout_review: 1200,
612 timeout_verify: None,
613 timeout_fix: 1800,
614 timeout_talk: 3600,
615 timeout_resource_wait: 1800,
616 retries: 1,
617 worktree_root: None,
618 land: true,
619 land_rounds: 4,
620 rerun_flaky_checks: true,
621 land_approval: true,
622 hold_contested_merge: true,
623 file_followups: true,
624 release_deputy_followups: true,
625 answer_timeout: 86_400,
626 incomplete_review: IncompleteReviewPolicy::Block,
627 e2e_every_round: false,
628 advise: true,
629 advisors: 3,
630 graft_runner_up: true,
631 }
632 }
633}
634
635impl Graph {
636 pub fn verify_timeout(&self) -> u64 {
640 self.timeout_verify.unwrap_or(self.timeout_review)
641 }
642
643 pub fn language_gate(&self) -> bool {
646 self.github_text_guard && self.github_english()
647 }
648
649 pub fn github_english(&self) -> bool {
651 crate::lang::is_english(&self.github_language)
652 }
653}
654
655#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
662#[serde(rename_all = "lowercase")]
663pub enum IncompleteReviewPolicy {
664 Block,
668 Warn,
673}
674
675#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
677#[serde(rename_all = "lowercase")]
678pub enum LeakPolicy {
679 Warn,
681 Redact,
683 Fail,
685}
686
687#[derive(Debug, Clone, Deserialize, Serialize)]
694#[serde(deny_unknown_fields, default)]
695pub struct Blind {
696 pub commit_msg_hook: bool,
699 pub strip_lines: Vec<String>,
703 pub vendor_tokens: Vec<String>,
705 pub on_leak: LeakPolicy,
707 pub seed: Option<u64>,
710}
711
712impl Default for Blind {
713 fn default() -> Self {
714 Self {
715 commit_msg_hook: true,
716 strip_lines: [
717 "Co-Authored-By:",
718 "Signed-off-by:",
719 "Assisted-by:",
720 "Generated-by:",
721 "Generated with",
722 "\u{1f916}",
723 ]
724 .iter()
725 .map(|s| (*s).to_owned())
726 .collect(),
727 vendor_tokens: [
728 "claude",
729 "anthropic",
730 "codex",
731 "openai",
732 "chatgpt",
733 "gemini",
734 "grok",
735 "xai",
736 "copilot",
737 "opencode",
738 "qoder",
739 "cursor",
740 "\u{1f916}",
741 ]
742 .iter()
743 .map(|s| (*s).to_owned())
744 .collect(),
745 on_leak: LeakPolicy::Warn,
746 seed: None,
747 }
748 }
749}
750
751#[derive(Debug, Clone, Default, Deserialize, Serialize)]
753#[serde(deny_unknown_fields, default)]
754pub struct Verify {
755 pub e2e: Vec<String>,
758 pub gate: Vec<String>,
760 #[serde(default)]
769 pub pre_gate: Vec<String>,
770 pub shell: Option<Vec<String>>,
773}
774
775impl Verify {
776 pub fn cache_dir(&self) -> Option<PathBuf> {
782 self.e2e
783 .iter()
784 .chain(self.gate.iter())
785 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
786 }
787
788 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
791 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
792 crate::cache::extract_manifest_paths(&all)
793 }
794}
795
796#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
798#[serde(deny_unknown_fields, default)]
799pub struct Worktree {
800 pub setup: Vec<SetupStep>,
803}
804
805#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
807#[serde(deny_unknown_fields, default)]
808pub struct SetupStep {
809 pub copy: Option<String>,
812 pub optional: bool,
814 pub run: Option<String>,
816 pub timeout_secs: Option<u64>,
819}
820
821impl Worktree {
822 pub fn validate(&self) -> Result<()> {
824 for (i, step) in self.setup.iter().enumerate() {
825 let n = i + 1;
826 match (&step.copy, &step.run) {
827 (Some(c), None) => {
828 if step.timeout_secs.is_some() {
829 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
830 }
831 crate::worktree_setup::validate_copy(c)
832 .with_context(|| format!("[worktree] setup step {n}"))?;
833 }
834 (None, Some(r)) => {
835 if r.trim().is_empty() {
836 bail!("[worktree] setup step {n}: `run` is empty");
837 }
838 if step.optional {
839 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
840 }
841 }
842 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
843 }
844 }
845 Ok(())
846 }
847}
848
849#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
859#[serde(deny_unknown_fields, default)]
860pub struct Disk {
861 pub min_free_bytes: u64,
870 pub auto_fold: bool,
876 pub fold_grace_secs: u64,
884 pub cache_limit_bytes: u64,
896}
897
898impl Default for Disk {
899 fn default() -> Self {
900 Self {
901 min_free_bytes: 8 * 1024 * 1024 * 1024,
902 auto_fold: true,
903 fold_grace_secs: 6 * 60 * 60,
904 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
905 }
906 }
907}
908
909#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
911#[serde(rename_all = "lowercase")]
912pub enum MergeMode {
913 None,
916 Local,
919 Pr,
923}
924
925#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
939#[serde(rename_all = "lowercase")]
940pub enum MergeStyle {
941 #[default]
946 Merge,
947 Squash,
953 Rebase,
959}
960
961#[derive(Debug, Clone, Deserialize, Serialize)]
963#[serde(deny_unknown_fields, default)]
964pub struct Merge {
965 pub mode: MergeMode,
968 pub base: Option<String>,
970 pub style: MergeStyle,
973 pub remote: String,
975 pub release_bump: bool,
988}
989
990impl Default for Merge {
991 fn default() -> Self {
992 Self {
993 mode: MergeMode::None,
994 base: None,
995 style: MergeStyle::default(),
996 remote: "origin".to_owned(),
997 release_bump: true,
998 }
999 }
1000}
1001
1002#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1004#[serde(rename_all = "lowercase")]
1005pub enum UpdateMode {
1006 Off,
1008 Notify,
1011 Install,
1013}
1014
1015#[derive(Debug, Clone, Deserialize, Serialize)]
1017#[serde(deny_unknown_fields, default)]
1018pub struct Update {
1019 pub mode: UpdateMode,
1021 pub interval: Option<String>,
1023}
1024
1025impl Default for Update {
1026 fn default() -> Self {
1027 Self {
1028 mode: UpdateMode::Notify,
1029 interval: None,
1030 }
1031 }
1032}
1033
1034#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1036#[serde(rename_all = "lowercase")]
1037pub enum ReleaseMode {
1038 #[default]
1041 Actions,
1042 Local,
1046}
1047
1048#[derive(Debug, Clone, Deserialize, Serialize)]
1050#[serde(deny_unknown_fields, default)]
1051pub struct Release {
1052 pub mode: ReleaseMode,
1055 pub commands: Vec<String>,
1062 pub timeout_minutes: u64,
1064}
1065
1066impl Default for Release {
1067 fn default() -> Self {
1068 Self {
1069 mode: ReleaseMode::Actions,
1070 commands: Vec::new(),
1071 timeout_minutes: 30,
1072 }
1073 }
1074}
1075
1076impl Release {
1077 pub fn is_local(&self) -> bool {
1079 self.mode == ReleaseMode::Local
1080 }
1081}
1082
1083#[derive(Debug, Clone, Deserialize, Serialize)]
1085#[serde(try_from = "CoordinationFields")]
1086pub struct Coordination {
1087 pub contract_file: String,
1089 pub contract_token: String,
1091 pub lock_file: String,
1093}
1094
1095#[derive(Deserialize, Default)]
1096#[serde(deny_unknown_fields, default)]
1097struct CoordinationFields {
1098 contract_file: String,
1099 contract_token: String,
1100 lock_file: String,
1101}
1102
1103impl TryFrom<CoordinationFields> for Coordination {
1104 type Error = anyhow::Error;
1105
1106 fn try_from(fields: CoordinationFields) -> Result<Self> {
1107 for (key, name) in [
1108 ("coordination.contract_file", &fields.contract_file),
1109 ("coordination.lock_file", &fields.lock_file),
1110 ] {
1111 if name.trim().is_empty()
1112 || name != name.trim()
1113 || name == "."
1114 || name.contains("..")
1115 || name.contains(['/', '\\', ':', '\0'])
1116 {
1117 bail!(
1118 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1119 );
1120 }
1121 }
1122 let token = &fields.contract_token;
1123 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1124 bail!(
1125 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1126 );
1127 }
1128 Ok(Self {
1129 contract_file: fields.contract_file,
1130 contract_token: fields.contract_token,
1131 lock_file: fields.lock_file,
1132 })
1133 }
1134}
1135
1136#[cfg(test)]
1137pub(crate) fn test_coordination() -> Option<Coordination> {
1138 Some(Coordination {
1139 contract_file: "updater.contract".into(),
1140 contract_token: "test-protocol-v1".into(),
1141 lock_file: "updater.lock".into(),
1142 })
1143}
1144
1145#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1147#[serde(deny_unknown_fields, default)]
1148pub struct Config {
1149 pub coordination: Option<Coordination>,
1151 pub agents: Vec<AgentSpec>,
1153 pub roles: Roles,
1155 pub graph: Graph,
1157 pub blind: Blind,
1159 pub verify: Verify,
1161 pub worktree: Worktree,
1163 pub disk: Disk,
1165 pub merge: Merge,
1167 pub update: Update,
1169 pub prompts: Prompts,
1171 pub notify: Notify,
1173 pub repos: Repos,
1176 pub talk: Talk,
1178 pub daemon: Daemon,
1180 pub release: Release,
1182 pub context_windows: BTreeMap<String, u64>,
1185}
1186
1187const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1197 ("claude-opus-4", 200_000),
1198 ("claude-sonnet-4", 200_000),
1199 ("claude-haiku-4", 200_000),
1200 ("claude-3", 200_000),
1201 ("opus", 200_000),
1202 ("sonnet", 200_000),
1203 ("haiku", 200_000),
1204 ("gpt-5", 400_000),
1205 ("gpt-4.1", 1_000_000),
1206 ("gpt-4o", 128_000),
1207 ("o3", 200_000),
1208 ("o4-mini", 200_000),
1209 ("gemini-2.5", 1_000_000),
1210 ("deepseek", 128_000),
1211];
1212
1213impl Config {
1214 pub fn context_window(&self, model: &str) -> Option<u64> {
1219 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1220 let mut best: Option<(usize, u64)> = None;
1221 for (key, window) in entries {
1222 if key == model {
1223 return Some(window);
1224 }
1225 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1226 best = Some((key.len(), window));
1227 }
1228 }
1229 best.map(|(_, w)| w)
1230 }
1231 lookup(
1232 model,
1233 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1234 )
1235 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1236 }
1237}
1238
1239#[derive(Debug, Clone, Deserialize, Serialize)]
1249#[serde(deny_unknown_fields, default)]
1250pub struct Daemon {
1251 pub max_concurrent_runs: usize,
1272 pub pause_for_interrupts: bool,
1288 pub max_deputies: usize,
1295 pub release_stall_minutes: u64,
1302}
1303
1304impl Default for Daemon {
1305 fn default() -> Self {
1306 Self {
1307 max_concurrent_runs: 1,
1308 pause_for_interrupts: false,
1309 max_deputies: 2,
1310 release_stall_minutes: 60,
1311 }
1312 }
1313}
1314
1315#[derive(Debug, Clone, Deserialize, Serialize)]
1327#[serde(deny_unknown_fields, default)]
1328pub struct Repos {
1329 pub roots: Vec<PathBuf>,
1333 pub scan_ttl: u64,
1340 pub fetch_interval: u64,
1345}
1346
1347impl Default for Repos {
1348 fn default() -> Self {
1349 Self {
1350 roots: Vec::new(),
1351 scan_ttl: 86_400,
1352 fetch_interval: 600,
1353 }
1354 }
1355}
1356
1357#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1373#[serde(deny_unknown_fields, default)]
1374pub struct Prompts {
1375 pub all: String,
1377 pub implement: String,
1379 pub judge: String,
1381 pub review: String,
1383 pub fix: String,
1385}
1386
1387impl Prompts {
1388 pub fn overlay(&self, node: &str) -> Option<String> {
1393 let specific = match node {
1394 "implement" => &self.implement,
1395 "judge" | "vote" | "deliberate" => &self.judge,
1396 "review" => &self.review,
1397 "fix" => &self.fix,
1398 _ => "",
1399 };
1400 let mut parts: Vec<&str> = Vec::new();
1401 for p in [self.all.trim(), specific.trim()] {
1402 if !p.is_empty() {
1403 parts.push(p);
1404 }
1405 }
1406 if parts.is_empty() {
1407 return None;
1408 }
1409 Some(parts.join("\n\n"))
1410 }
1411}
1412
1413#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1420#[serde(deny_unknown_fields, default)]
1421pub struct Notify {
1422 pub command: Vec<String>,
1425}
1426
1427#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1429#[serde(deny_unknown_fields, default)]
1430pub struct Talk {
1431 pub allow_write: bool,
1440 pub personas: Vec<PersonaSpec>,
1445 pub operator_name: Option<String>,
1449}
1450
1451pub const OPERATOR_NAME_MAX: usize = 64;
1453
1454impl Talk {
1455 pub fn operator_name(&self) -> Option<&str> {
1457 self.operator_name
1458 .as_deref()
1459 .map(str::trim)
1460 .filter(|n| !n.is_empty())
1461 }
1462}
1463
1464#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1466#[serde(deny_unknown_fields)]
1467pub struct PersonaSpec {
1468 pub id: String,
1470 #[serde(default)]
1473 pub name: String,
1474 #[serde(default)]
1477 pub prompt: String,
1478 #[serde(default, skip_serializing_if = "Option::is_none")]
1482 pub icon: Option<String>,
1483}
1484
1485#[derive(Debug, Clone)]
1487pub struct ResolvedRoles {
1488 pub implementers: Vec<AgentSpec>,
1490 pub judges: Vec<AgentSpec>,
1492 pub reviewers: Vec<AgentSpec>,
1494 pub fixer: Option<Vec<AgentSpec>>,
1499 pub conductor: AgentSpec,
1501 pub implementer_roster: Vec<AgentSpec>,
1509 pub judge_roster: Vec<AgentSpec>,
1513 pub reviewer_roster: Vec<AgentSpec>,
1515}
1516
1517fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1524 let mut out = Vec::new();
1525 for (k, v) in table {
1526 if prefix.is_empty() && k == "vars" {
1527 continue;
1528 }
1529 let path = if prefix.is_empty() {
1530 k.clone()
1531 } else {
1532 format!("{prefix}.{k}")
1533 };
1534 match v {
1535 toml::Value::Array(_) => out.push(path),
1536 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1537 _ => {}
1538 }
1539 }
1540 out
1541}
1542
1543#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1545enum ArrayMerge {
1546 Append,
1550 Replace,
1553}
1554
1555fn array_merge_policy(key: &str) -> ArrayMerge {
1594 match key {
1595 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1596 _ => ArrayMerge::Replace,
1597 }
1598}
1599
1600impl Config {
1601 pub fn load(path: &Path) -> Result<Self> {
1604 Self::load_layers(&[path.to_path_buf()])
1605 }
1606
1607 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1617 let mut ctx = teravars::system_context();
1618 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1619 ctx.insert("env", &env);
1620 if let Some(last) = paths.last()
1621 && let Some(dir) = last.parent()
1622 {
1623 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1626 .map(|s| PathBuf::from(s.trim()))
1627 .unwrap_or_else(|_| dir.to_path_buf());
1628 ctx.insert("repo", &dir.to_string_lossy());
1629 ctx.insert(
1630 "repo_name",
1631 &dir.file_name().unwrap_or_default().to_string_lossy(),
1632 );
1633 }
1634 ctx
1635 }
1636
1637 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1645 let mut engine = teravars::Engine::default();
1646 let ctx = Self::render_ctx(paths);
1647 if paths.len() > 1 {
1648 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1649 if error.downcast_ref::<ConfigFailure>().is_some() {
1650 error
1651 } else {
1652 let message = error.to_string();
1655 error
1656 .context(ConfigFailure::layers("config-merge", paths))
1657 .context(message)
1658 }
1659 })?;
1660 }
1661 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1662 .map_err(|error| {
1663 let cause = ConfigFailure::render(&error, paths);
1664 anyhow::Error::new(error).context(cause)
1665 })
1666 .with_context(|| {
1667 format!(
1668 "rendering config via teravars: {}",
1669 paths
1670 .iter()
1671 .map(|p| p.display().to_string())
1672 .collect::<Vec<_>>()
1673 .join(", ")
1674 )
1675 })?;
1676 let mut table = merged.config;
1677 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1678 table.remove("vars");
1681 let detect_agents = !table.contains_key("agents");
1685 let mut cfg: Self = toml::Value::Table(table)
1686 .try_into()
1687 .context("deserializing magi config")
1688 .context(ConfigFailure::layers("config-deserialize", paths))?;
1689 crate::persona::validate(&cfg.talk.personas)?;
1690 cfg.worktree.validate()?;
1691 if let Some(name) = cfg.talk.operator_name() {
1692 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1693 bail!(
1694 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1695 );
1696 }
1697 }
1698 if detect_agents {
1699 cfg.agents = Self::autodetected().agents;
1700 }
1701 Ok(cfg)
1702 }
1703
1704 fn normalize_renamed_keys(
1712 paths: &[PathBuf],
1713 engine: &mut teravars::Engine,
1714 ctx: &teravars::Context,
1715 table: &mut toml::map::Map<String, toml::Value>,
1716 ) -> Result<()> {
1717 let both = matches!(
1718 table.get("graph"),
1719 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1720 );
1721 if !both {
1722 return Ok(());
1723 }
1724 let mut winner: Option<toml::Value> = None;
1725 for path in paths {
1726 let one = teravars::load_merged([path], engine, ctx)
1727 .map_err(|error| {
1728 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1729 anyhow::Error::new(error).context(cause)
1730 })
1731 .with_context(|| format!("rendering {}", path.display()))?;
1732 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1733 continue;
1734 };
1735 if g.contains_key("candidates") && g.contains_key("implementers") {
1736 bail!(
1737 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1738 path.display()
1739 );
1740 }
1741 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1742 winner = Some(v.clone());
1743 }
1744 }
1745 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1746 g.remove("candidates");
1747 if let Some(v) = winner {
1748 g.insert("implementers".to_owned(), v);
1749 }
1750 }
1751 Ok(())
1752 }
1753
1754 fn refuse_split_arrays(
1778 paths: &[PathBuf],
1779 engine: &mut teravars::Engine,
1780 ctx: &teravars::Context,
1781 ) -> Result<()> {
1782 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1783 for path in paths {
1784 let one = teravars::load_merged([path], engine, ctx)
1785 .map_err(|error| {
1786 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1787 anyhow::Error::new(error).context(cause)
1788 })
1789 .with_context(|| format!("rendering {}", path.display()))?;
1790 for key in array_keys(&one.config, "") {
1791 if array_merge_policy(&key) == ArrayMerge::Append {
1792 continue;
1793 }
1794 if let Some(first) = seen.get(&key) {
1795 bail!(
1796 "`{key}` is an array declared in two config layers:\n \
1797 {}\n {}\nteravars appends arrays when it merges, so \
1798 magi would run the concatenation of both - which is \
1799 not what either file says. Declare `{key}` in exactly \
1800 one of them.",
1801 first.display(),
1802 path.display()
1803 );
1804 }
1805 seen.insert(key, path.clone());
1806 }
1807 }
1808 Ok(())
1809 }
1810
1811 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1833 let mut engine = teravars::Engine::default();
1834 let ctx = Self::render_ctx(paths);
1835 let mut out = Vec::new();
1836 for path in paths {
1837 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1838 continue;
1839 };
1840 let mut cur = &one.config;
1841 let mut found = None;
1842 let parts: Vec<&str> = key.split('.').collect();
1843 for (i, part) in parts.iter().enumerate() {
1844 match cur.get(*part) {
1845 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1846 found = Some(a);
1847 break;
1848 }
1849 Some(toml::Value::Table(t)) => cur = t,
1850 _ => break,
1851 }
1852 }
1853 let Some(values) = found else { continue };
1854 let strings: Vec<String> = values
1855 .iter()
1856 .filter_map(|v| v.as_str().map(str::to_owned))
1857 .collect();
1858 if !strings.is_empty() {
1859 out.push((path.clone(), strings));
1860 }
1861 }
1862 out
1863 }
1864
1865 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1871 let mut engine = teravars::Engine::default();
1872 let ctx = Self::render_ctx(paths);
1873 paths
1874 .iter()
1875 .map(|path| {
1876 let one = teravars::load_merged([path], &mut engine, &ctx)
1877 .map(|m| m.config)
1878 .with_context(|| format!("rendering {}", path.display()));
1879 (path.clone(), one)
1880 })
1881 .collect()
1882 }
1883
1884 pub fn describe_composed(
1894 paths: &[PathBuf],
1895 commands: &[String],
1896 key: &str,
1897 empty: &str,
1898 ) -> String {
1899 if commands.is_empty() {
1900 return empty.to_owned();
1901 }
1902 let joined = commands.join(" && ");
1903 let provenance = Self::array_provenance(paths, key);
1904 if provenance.len() <= 1 {
1905 return joined;
1906 }
1907 let mut out = joined;
1908 for (path, cmds) in &provenance {
1909 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1910 }
1911 out
1912 }
1913
1914 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1921 #[cfg(test)]
1922 crate::web::request_cost::discovery();
1923 if let Some(p) = explicit {
1924 let paths = vec![p.to_path_buf()];
1925 return Ok((Self::load_layers(&paths)?, paths));
1926 }
1927 let paths = Self::layers_checked(repo)?;
1928 if paths.is_empty() {
1929 return Ok((Self::autodetected(), paths));
1930 }
1931 Ok((Self::load_layers(&paths)?, paths))
1932 }
1933
1934 pub async fn discover_fetched(
1937 repo: &Path,
1938 explicit: Option<&Path>,
1939 ) -> Result<(Self, Vec<PathBuf>)> {
1940 if explicit.is_none() && is_git_worktree(repo) {
1941 let (remote, cfg_base) = probe_remote_base(repo);
1945 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
1946 .await
1947 .with_context(|| ConfigFailure {
1948 stage: "config-base",
1949 target: remote.clone(),
1950 })?;
1951 let out = crate::git::fetch(repo, &remote, &base)
1952 .await
1953 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
1954 .with_context(|| ConfigFailure {
1955 stage: "config-fetch",
1956 target: format!("{remote}/{base}"),
1957 })?;
1958 if !out.ok() {
1959 return Err(anyhow::anyhow!(
1960 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
1961 out.stderr.lines().next().unwrap_or("").trim()
1962 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
1963 }
1964 if cfg_base.is_none() {
1965 crate::git::ensure_remote_head(repo, &remote, &base).await;
1966 }
1967 }
1968 Self::discover(repo, explicit).map_err(|error| {
1969 if error.downcast_ref::<ConfigFailure>().is_some() {
1970 error
1971 } else {
1972 error.context(ConfigFailure {
1973 stage: "config-load",
1974 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
1975 })
1976 }
1977 })
1978 }
1979
1980 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
1982 if !is_git_worktree(repo) {
1983 return Ok(Self::layers(repo));
1984 }
1985 let mut paths: Vec<PathBuf> = Self::machine_layer()
1986 .into_iter()
1987 .filter(|p| p.is_file())
1988 .collect();
1989 paths.extend(Self::repo_layers(repo)?);
1990 Ok(paths)
1991 }
1992
1993 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
1995 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
1996 if let Some(root) = cached {
1997 let relative = path.strip_prefix(root).unwrap_or(path);
1998 let reference = resolve_remote_base(repo)
1999 .map(|(remote, base)| format!("{remote}/{base}"))
2000 .unwrap_or_else(|_| "remote base".to_owned());
2001 format!(
2002 "{} at {reference} (including its includes)",
2003 repo.join(relative).display()
2004 )
2005 } else {
2006 format!("{} (including its includes)", path.display())
2007 }
2008 }
2009
2010 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2013 if !is_git_worktree(repo) {
2014 return Ok([
2015 repo.join(".magi").join("config.toml"),
2016 repo.join("magi.toml"),
2017 ]
2018 .into_iter()
2019 .filter(|p| p.is_file())
2020 .collect());
2021 }
2022 remote_layers(repo)
2023 }
2024
2025 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2045
2046 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2051 let mut paths = Vec::new();
2052 paths.extend(Self::machine_layer());
2053 paths.push(repo.join(".magi").join("config.toml"));
2054 paths.push(repo.join("magi.toml"));
2055 paths.retain(|p| p.is_file());
2056 paths
2057 }
2058
2059 #[cfg(test)]
2066 pub(crate) fn machine_layer() -> Option<PathBuf> {
2067 std::env::var(Self::CONFIG_DIR_ENV)
2068 .ok()
2069 .filter(|dir| !dir.trim().is_empty())
2070 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2071 }
2072
2073 #[cfg(not(test))]
2075 pub(crate) fn machine_layer() -> Option<PathBuf> {
2076 match std::env::var(Self::CONFIG_DIR_ENV) {
2077 Ok(dir) if dir.trim().is_empty() => None,
2079 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2080 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2081 }
2082 }
2083
2084 pub fn autodetected() -> Self {
2086 let mut cfg = Self::default();
2087 for (kind, id, model) in [
2088 (AgentKind::Claude, "opus", Some("opus")),
2089 (AgentKind::Claude, "sonnet", Some("sonnet")),
2090 (AgentKind::Antigravity, "antigravity", None),
2091 (AgentKind::Opencode, "opencode", None),
2092 (AgentKind::Codex, "codex", None),
2093 (AgentKind::Omp, "omp", None),
2094 ] {
2095 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2096 cfg.agents.push(AgentSpec {
2097 id: id.to_owned(),
2098 kind,
2099 model: model.map(str::to_owned),
2100 command: Vec::new(),
2101 extra_args: Vec::new(),
2102 env: BTreeMap::new(),
2103 prompt_delivery: None,
2104 });
2105 }
2106 }
2107 cfg
2108 }
2109
2110 pub fn cache_dir(&self) -> Option<PathBuf> {
2113 self.verify.cache_dir()
2114 }
2115
2116 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2118 self.agents
2119 .iter()
2120 .find(|a| a.id == id)
2121 .with_context(|| format!("no agent with id `{id}` in the roster"))
2122 }
2123
2124 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2131 let mut out = Vec::with_capacity(count);
2132 for i in 0..count {
2133 let spec = if ids.is_empty() {
2134 self.agents[(i + offset) % self.agents.len()].clone()
2135 } else {
2136 self.agent(&ids[i % ids.len()])?.clone()
2137 };
2138 out.push(spec);
2139 }
2140 Ok(out)
2141 }
2142
2143 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2150 if ids.is_empty() {
2151 Ok(self.agents.clone())
2152 } else {
2153 ids.iter().map(|id| self.agent(id).cloned()).collect()
2154 }
2155 }
2156
2157 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2164 if self.agents.is_empty() {
2165 bail!(
2166 "agent roster is empty: no agent CLI found on PATH and no \
2167 [[agents]] in the config. Run `magi init` to write a starter \
2168 magi.toml."
2169 );
2170 }
2171 let pinned = self
2172 .graph
2173 .selected_implementer
2174 .as_ref()
2175 .map(|id| self.agent(id).cloned())
2176 .transpose()?;
2177 Ok(ResolvedRoles {
2178 implementers: match &pinned {
2179 Some(agent) => vec![agent.clone()],
2180 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2181 },
2182 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2183 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2184 fixer: match self.roles.fixer.as_ref() {
2185 Some(choice) => Some(crate::agent::pick_chain(
2188 &self.agents,
2189 Some(choice),
2190 &|_| true,
2191 "fixer",
2192 )?),
2193 None => None,
2194 },
2195 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2200 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2201 Some(ids) if !ids.is_empty() => ids
2204 .iter()
2205 .find_map(|id| self.agent(id).ok())
2206 .cloned()
2207 .with_context(|| {
2208 format!("[roles] conductor names no agent in the roster: {ids:?}")
2209 })?,
2210 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2215 .unwrap_or_else(|_| self.agents[0].clone()),
2216 },
2217 implementer_roster: match pinned {
2218 Some(agent) => vec![agent],
2219 None => self.full_roster(&self.roles.implementers)?,
2220 },
2221 judge_roster: self.full_roster(&self.roles.judges)?,
2222 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2223 })
2224 }
2225
2226 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2248 if self.agents.is_empty() {
2249 bail!(
2250 "agent roster is empty: no agent CLI found on PATH and no \
2251 [[agents]] in the config. Run `magi init` to write a starter \
2252 magi.toml."
2253 );
2254 }
2255 if !self.roles.advisors.is_empty() {
2256 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2257 }
2258 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2259 }
2260
2261 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2265 if self.roles.advisors.is_empty() {
2266 self.full_roster(&self.roles.judges)
2267 } else {
2268 self.full_roster(&self.roles.advisors)
2269 }
2270 }
2271
2272 pub fn shell(&self) -> Vec<String> {
2274 if let Some(s) = &self.verify.shell {
2275 return s.clone();
2276 }
2277 if which("sh") {
2278 vec!["sh".to_owned(), "-c".to_owned()]
2279 } else {
2280 vec!["cmd".to_owned(), "/C".to_owned()]
2281 }
2282 }
2283
2284 pub fn starter_toml() -> String {
2286 let detected = Self::autodetected();
2287 let mut s = String::from(
2288 "# magi — blind multi-agent implementation competition.\n\
2289 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2290 # -> blind judging -> deliberation -> private final vote\n\
2291 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2292 #\n\
2293 # Rendered by teravars: a `[vars]` table, env\n\
2294 # and system lookups, and `include = [...]` all work. Tera\n\
2295 # braces are live everywhere in this file, but comments are\n\
2296 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2297 # may quote `{{ ... }}` freely.\n\
2298 #\n\
2299 # Layers deep-merge in increasing\n\
2300 # precedence, so the roster can live once per machine in\n\
2301 # <config_dir>/magi/config.toml and each repo only states its own\n\
2302 # gate:\n\
2303 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2304 [vars]\n\
2305 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2306 # Single quotes inside the braces: teravars renders the raw file\n\
2307 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2308 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2309 );
2310 if detected.agents.is_empty() {
2311 s.push_str(
2312 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2313 # kind = claude | opencode | antigravity | codex | command\n\
2314 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2315 );
2316 } else {
2317 for a in &detected.agents {
2318 s.push_str("[[agents]]\n");
2319 s.push_str(&format!("id = {:?}\n", a.id));
2320 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2321 if let Some(m) = &a.model {
2322 s.push_str(&format!("model = {m:?}\n"));
2323 }
2324 s.push('\n');
2325 }
2326 }
2327 s.push_str(
2328 "# Leave a role list empty to rotate through the roster.\n\
2329 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2330 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2331 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2332 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2333 [roles]\n\
2334 implementers = []\n\
2335 judges = []\n\
2336 reviewers = []\n\
2337 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2338 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2339 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2340 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2341 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2342 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2343 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2344 [graph]\n\
2345 # Gate GitHub prose; secret redaction is always enabled.\n\
2346 github_text_guard = true\n\
2347 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2348 github_language = \"en\"\n\
2349 implementers = 3\n\
2350 judges = 3\n\
2351 deliberate_rounds = 1\n\
2352 reviewers = 3\n\
2353 review_rounds = 6\n\
2354 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2355 gate_fix_rounds = 1\n\
2356 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2357 rerun_flaky_checks = true\n\
2358 # Port the strengths judges named in the losing candidates onto the\n\
2359 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2360 graft_runner_up = true\n\
2361 max_parallel = 4\n\
2362 language = \"en\"\n\
2363 # One CLI conversation per seat: judges keep their own argument\n\
2364 # across deliberation, the fixer keeps its implementation context.\n\
2365 sessions = true\n\
2366 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2367 # the final gate inherit this value for compatibility.\n\
2368 timeout_review = 1200\n\
2369 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2370 # verification independent if timeout_review changes later.\n\
2371 # timeout_verify = 1200\n\
2372 # Longest a seat waits for the shared build cache before it is\n\
2373 # spawned. Never counted against an agent's own timeout; expiry\n\
2374 # holds the run (resumable) instead of failing the agent.\n\
2375 # timeout_resource_wait = 1800\n\n\
2376 # What the chat calls you (persona address and the Chat's turn label).\n\
2377 # [talk]\n\
2378 # operator_name = \"Commander\"\n\n\
2379 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2380 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2381 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2382 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2383 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2384 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2385 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2386 # [[talk.personas]]\n\
2387 # id = \"gendo\"\n\
2388 # name = \"Gendo Ikari\"\n\
2389 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2390 # icon = \"~/pictures/gendo.png\"\n\n\
2391 [verify]\n\
2392 # Run once per review round in the winner's worktree; failures are\n\
2393 # fed back to the fixer.\n\
2394 e2e = []\n\
2395 # Final gate. Every command must exit 0 before a merge.\n\
2396 gate = []\n\
2397 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2398 # before the gate; whatever they change becomes one commit. A failing\n\
2399 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2400 # gate (timeout_verify). Keep it light and idempotent.\n\
2401 # pre_gate = []\n\n\
2402 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2403 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2404 # before any agent or verify command touches it. `copy` reads from the\n\
2405 # primary checkout and never overwrites; `optional` skips a missing\n\
2406 # source. `run` goes through the shell with the worktree as cwd and\n\
2407 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2408 # the verify timeout). Setup must not edit tracked files, and what it\n\
2409 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2410 # layer only.\n\
2411 # [worktree]\n\
2412 # setup = [\n\
2413 # { copy = \".env.example -> .env\" },\n\
2414 # { copy = \".env.local\", optional = true },\n\
2415 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2416 # ]\n\n\
2417 [merge]\n\
2418 # none | local | pr\n\
2419 mode = \"none\"\n\
2420 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2421 [update]\n\
2422 # off | notify | install — checked in the background, throttled.\n\
2423 mode = \"notify\"\n\
2424 # interval = \"24h\"\n\n\
2425 [daemon]\n\
2426 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2427 # no new commit and no check changing state before `magi serve`\n\
2428 # notices and asks you. A failed check is rerun once on its own;\n\
2429 # still red after that escalates at once. 0 turns the watcher off.\n\
2430 # release_stall_minutes = 60\n\n\
2431 [release]\n\
2432 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2433 # Actions never run (private, no minutes): the release pull request\n\
2434 # does not wait for CI, you approve the merge in magi, and then\n\
2435 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2436 # runs `commands` from a clean checkout of the merge commit. A\n\
2437 # failure holds the release with a notice; it is never retried blind.\n\
2438 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2439 # mode = \"actions\"\n\
2440 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2441 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2442 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2443 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2444 # timeout_minutes = 30\n",
2445 );
2446 s
2447 }
2448}
2449
2450pub fn which(program: &str) -> bool {
2452 find_program(program).is_some()
2453}
2454
2455pub fn find_program(program: &str) -> Option<PathBuf> {
2464 find_program_on(program, &std::env::var_os("PATH")?)
2465}
2466
2467pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2470 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2471 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2472}
2473
2474fn find_program_in(
2475 program: &str,
2476 paths: &std::ffi::OsStr,
2477 pathext: Option<&str>,
2478) -> Option<PathBuf> {
2479 let p = Path::new(program);
2480 if p.components().count() > 1 {
2481 return p.is_file().then(|| p.to_path_buf());
2482 }
2483 std::env::split_paths(paths).find_map(|dir| match pathext {
2484 Some(exts) => {
2485 let bare = dir.join(program);
2486 if p.extension().is_some() && bare.is_file() {
2487 return Some(bare);
2488 }
2489 exts.split(';')
2490 .filter(|e| !e.is_empty())
2491 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2492 .find(|c| c.is_file())
2493 }
2494 None => Some(dir.join(program)).filter(|c| c.is_file()),
2495 })
2496}
2497
2498const REPO_MARKER: &str = ".magi-repo";
2500
2501fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2502 use crate::proc::Quiet as _;
2503 #[cfg(test)]
2504 crate::web::request_cost::git();
2505 let out = std::process::Command::new("git")
2506 .args(args)
2507 .quiet()
2508 .current_dir(repo)
2509 .stdin(std::process::Stdio::null())
2510 .output()
2511 .ok()?;
2512 out.status
2513 .success()
2514 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2515}
2516
2517fn is_git_worktree(repo: &Path) -> bool {
2520 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2521}
2522
2523#[derive(Deserialize, Default)]
2524struct ProbeMerge {
2525 base: Option<String>,
2526 remote: Option<String>,
2527}
2528
2529#[derive(Deserialize, Default)]
2530struct Probe {
2531 merge: Option<ProbeMerge>,
2532}
2533
2534fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2540 if !path.is_file() {
2541 return None;
2542 }
2543 let paths = [path.to_path_buf()];
2544 let mut engine = teravars::Engine::default();
2545 let mut ctx = Config::render_ctx(&paths);
2546 ctx.insert("repo", &repo.to_string_lossy());
2549 ctx.insert(
2550 "repo_name",
2551 &repo.file_name().unwrap_or_default().to_string_lossy(),
2552 );
2553 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2554 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2555 {
2556 return probe.merge;
2557 }
2558 let text = std::fs::read_to_string(path).ok()?;
2559 toml::from_str::<Probe>(&text).ok()?.merge
2560}
2561
2562fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2564 let mut remote = None;
2565 let mut base = None;
2566 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2567 sources.push(repo.join("magi.toml"));
2568 sources.push(repo.join(".magi").join("config.toml"));
2569 for path in sources {
2570 if let Some(m) = probe_merge(&path, repo) {
2571 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2572 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2573 }
2574 }
2575 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2576}
2577
2578fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2580 let (remote, base) = probe_remote_base(repo);
2581 let base = match base {
2582 Some(b) => b,
2583 None => {
2584 let head = format!("refs/remotes/{remote}/HEAD");
2585 git_out(repo, &["symbolic-ref", "--quiet", &head])
2586 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2587 .with_context(|| {
2588 format!(
2589 "cannot tell which branch of `{remote}` holds magi.toml: \
2590 set [merge] base, or run `git remote set-head {remote} -a`"
2591 )
2592 })?
2593 }
2594 };
2595 Ok((remote, base))
2596}
2597
2598fn fnv_hex(text: &str) -> String {
2599 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2600 for b in text.bytes() {
2601 hash ^= u64::from(b);
2602 hash = hash.wrapping_mul(0x0100_0000_01b3);
2603 }
2604 format!("{hash:016x}")
2605}
2606
2607fn declares_include(text: &str) -> bool {
2613 match toml::from_str::<toml::Table>(text) {
2614 Ok(table) => {
2615 table.contains_key("include")
2616 || table
2617 .get("teravars")
2618 .and_then(toml::Value::as_table)
2619 .is_some_and(|t| t.contains_key("include"))
2620 }
2621 Err(_) => text.contains("include"),
2622 }
2623}
2624
2625fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2628 use crate::proc::Quiet as _;
2629 #[cfg(test)]
2630 crate::web::request_cost::git();
2631 let mut archive = std::process::Command::new("git")
2632 .args(["archive", "--format=tar", sha])
2633 .quiet()
2634 .current_dir(repo)
2635 .stdin(std::process::Stdio::null())
2636 .stdout(std::process::Stdio::piped())
2637 .stderr(std::process::Stdio::null())
2638 .spawn()
2639 .context("running git archive")?;
2640 let tar = std::process::Command::new("tar")
2641 .arg("-x")
2642 .arg("-C")
2643 .arg(dest)
2644 .quiet()
2645 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2646 .output()
2647 .context("running tar")?;
2648 let status = archive.wait().context("waiting for git archive")?;
2649 if !status.success() || !tar.status.success() {
2650 bail!(
2651 "cannot unpack {sha} for the config's includes: {}",
2652 String::from_utf8_lossy(&tar.stderr).trim()
2653 );
2654 }
2655 Ok(())
2656}
2657
2658fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2661 let (remote, base) = resolve_remote_base(repo)?;
2662 let tracking = format!("refs/remotes/{remote}/{base}");
2663 let spec = format!("{tracking}^{{commit}}");
2664 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2665 .map(|s| s.trim().to_owned())
2666 .filter(|s| !s.is_empty())
2667 .with_context(|| {
2668 format!(
2669 "`{remote}/{base}` does not exist in this checkout; fetch it \
2670 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2671 a possibly stale local magi.toml instead"
2672 )
2673 })?;
2674 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2675 let rels = [".magi/config.toml", "magi.toml"];
2676 let mut texts: Vec<(&str, String)> = Vec::new();
2677 for rel in rels {
2678 let object = format!("{sha}:{rel}");
2679 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2680 continue;
2681 }
2682 let Some(text) = git_out(repo, &["show", &object]) else {
2683 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2684 };
2685 texts.push((rel, text));
2686 }
2687 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2688 let build = |root: &Path| -> Result<PathBuf> {
2692 let final_dir = root.join(&key);
2693 if !final_dir.is_dir() {
2694 std::fs::create_dir_all(root)?;
2695 let tmp = root.join(format!(
2696 "{key}.tmp-{}-{}",
2697 std::process::id(),
2698 std::time::SystemTime::now()
2699 .duration_since(std::time::UNIX_EPOCH)
2700 .map(|d| d.as_nanos())
2701 .unwrap_or_default()
2702 ));
2703 let filled = (|| -> Result<()> {
2704 std::fs::create_dir_all(&tmp)?;
2705 if wants_tree {
2706 extract_tree(repo, &sha, &tmp)?;
2707 }
2708 for (rel, text) in &texts {
2709 let file = tmp.join(rel);
2710 let parent = file.parent().unwrap_or(&tmp);
2711 std::fs::create_dir_all(parent)?;
2712 std::fs::write(&file, text)?;
2713 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2714 }
2715 Ok(())
2716 })();
2717 if let Err(e) = filled {
2718 let _ = std::fs::remove_dir_all(&tmp);
2719 return Err(e);
2720 }
2721 if std::fs::rename(&tmp, &final_dir).is_err() {
2722 let _ = std::fs::remove_dir_all(&tmp);
2724 if !final_dir.is_dir() {
2725 bail!("cannot place {}", final_dir.display());
2726 }
2727 }
2728 }
2729 Ok(final_dir)
2730 };
2731 let common = git_out(
2732 repo,
2733 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2734 )
2735 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2736 let dir = match common.map(|c| build(&c)) {
2737 Some(Ok(d)) => d,
2738 _ => build(&std::env::temp_dir().join("magi-config"))
2739 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2740 };
2741 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2742}
2743
2744#[cfg(test)]
2745mod tests {
2746 #[test]
2747 fn coordination_defaults_off_and_validates_rendered_layer_values() {
2748 let dir = tempfile::tempdir().unwrap();
2749 let machine = dir.path().join("machine.toml");
2750 let repo = dir.path().join("repo.toml");
2751 std::fs::write(&machine, "").unwrap();
2752 assert!(Config::default().coordination.is_none());
2753 assert!(Config::load(&machine).unwrap().coordination.is_none());
2754 std::fs::write(
2755 &machine,
2756 r#"
2757[vars]
2758contract = "updater.contract"
2759[coordination]
2760contract_file = "{{ vars.contract }}"
2761contract_token = "protocol-v1"
2762lock_file = "updater.lock"
2763"#,
2764 )
2765 .unwrap();
2766 let cfg = Config::load(&machine).unwrap();
2767 let policy = cfg.coordination.unwrap();
2768 assert_eq!(policy.contract_file, "updater.contract");
2769 assert_eq!(policy.contract_token, "protocol-v1");
2770 assert_eq!(policy.lock_file, "updater.lock");
2771 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
2772 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
2773 let policy = cfg.coordination.unwrap();
2774 assert_eq!(policy.contract_file, "updater.contract");
2775 assert_eq!(policy.lock_file, "repository.lock");
2776 std::fs::write(
2777 &repo,
2778 r#"
2779[vars]
2780bad = "../escape"
2781[coordination]
2782lock_file = "{{ vars.bad }}"
2783"#,
2784 )
2785 .unwrap();
2786 let error = Config::load_layers(&[machine, repo]).unwrap_err();
2787 assert!(format!("{error:#}").contains("coordination.lock_file"));
2788 }
2789
2790 #[test]
2791 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
2792 let dir = tempfile::tempdir().unwrap();
2793 let path = dir.path().join("config.toml");
2794 let valid = toml::toml! {
2795 [coordination]
2796 contract_file = "updater.contract"
2797 contract_token = "protocol-v1"
2798 lock_file = "updater.lock"
2799 };
2800 for key in ["contract_file", "lock_file"] {
2801 for bad in [
2802 "",
2803 " ",
2804 " file",
2805 "file ",
2806 "\tfile",
2807 "file\t",
2808 ".",
2809 "..",
2810 "file..name",
2811 "../escape",
2812 "a/b",
2813 "a\\b",
2814 "/absolute",
2815 "C:drive",
2816 "C:\\absolute",
2817 "nul\0name",
2818 ] {
2819 let mut table = valid.clone();
2820 table["coordination"][key] = bad.into();
2821 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2822 let error = Config::load(&path).unwrap_err();
2823 assert!(
2824 format!("{error:#}").contains(&format!("coordination.{key}")),
2825 "{bad:?}: {error:#}"
2826 );
2827 }
2828 }
2829 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
2830 let mut table = valid.clone();
2831 table["coordination"]["contract_token"] = bad.into();
2832 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2833 let error = Config::load(&path).unwrap_err();
2834 assert!(
2835 format!("{error:#}").contains("coordination.contract_token"),
2836 "{error:#}"
2837 );
2838 }
2839 for key in ["contract_file", "contract_token", "lock_file"] {
2840 let mut table = valid.clone();
2841 table["coordination"].as_table_mut().unwrap().remove(key);
2842 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2843 let error = Config::load(&path).unwrap_err();
2844 assert!(
2845 format!("{error:#}").contains(&format!("coordination.{key}")),
2846 "{error:#}"
2847 );
2848 }
2849 let mut table = valid;
2850 table["coordination"]
2851 .as_table_mut()
2852 .unwrap()
2853 .insert("typo".into(), "value".into());
2854 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2855 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
2856 }
2857
2858 #[test]
2859 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
2860 let mut cfg = Config::default();
2861 assert_eq!(
2862 cfg.context_window("claude-sonnet-4-5-20250929"),
2863 Some(200_000)
2864 );
2865 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
2866 assert_eq!(cfg.context_window("mystery-model"), None);
2867 cfg.context_windows
2868 .insert("claude-sonnet-4-5".into(), 1_000_000);
2869 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
2870 cfg.context_windows.insert("mystery".into(), 32_768);
2871 assert_eq!(
2873 cfg.context_window("claude-sonnet-4-5-20250929"),
2874 Some(1_000_000)
2875 );
2876 cfg.context_windows
2878 .insert("claude-sonnet-4-5-20250929".into(), 7);
2879 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
2880 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
2881 }
2882
2883 use super::*;
2884
2885 #[test]
2888 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
2889 let dir = tempfile::tempdir().unwrap();
2890 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
2891 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
2892 let paths = dir.path().as_os_str();
2893 assert_eq!(
2894 find_program_in("codex", paths, Some(".EXE;.CMD")),
2895 Some(dir.path().join("codex.cmd"))
2896 );
2897 assert_eq!(
2898 find_program_in("codex", paths, None),
2899 Some(dir.path().join("codex"))
2900 );
2901 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
2902 }
2903
2904 fn spec(id: &str) -> AgentSpec {
2905 AgentSpec {
2906 id: id.to_owned(),
2907 kind: AgentKind::Command,
2908 model: None,
2909 command: vec!["true".to_owned()],
2910 extra_args: Vec::new(),
2911 env: BTreeMap::new(),
2912 prompt_delivery: None,
2913 }
2914 }
2915
2916 #[test]
2917 fn github_text_guard_defaults_on_and_can_be_disabled() {
2918 let default: Graph = toml::from_str("").unwrap();
2919 assert!(default.github_text_guard);
2920 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
2921 assert!(!disabled.github_text_guard);
2922 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
2923 assert!(!config.graph.github_text_guard);
2924 assert!(Config::starter_toml().contains("github_text_guard = true"));
2925 }
2926
2927 #[test]
2928 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
2929 assert!(Graph::default().rerun_flaky_checks);
2930 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
2931 assert!(!off.rerun_flaky_checks);
2932 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
2933 }
2934
2935 #[test]
2936 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
2937 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
2942 assert_eq!(g.timeout_verify, None);
2943 assert_eq!(g.verify_timeout(), 3600);
2944 }
2945
2946 #[test]
2947 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
2948 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
2953 assert_eq!(g.timeout_review, 45);
2954 assert_eq!(
2955 g.verify_timeout(),
2956 45,
2957 "an omitted legacy value follows review"
2958 );
2959 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
2960 .expect("parse explicit override");
2961 assert_eq!(explicit.verify_timeout(), 1200);
2962 }
2963
2964 #[test]
2965 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
2966 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
2967 assert_eq!(g.implementers, 4);
2968 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
2969 assert_eq!(g.implementers, 5);
2970 }
2971
2972 fn layered(lower: &str, upper: &str) -> Result<Config> {
2973 let dir = tempfile::tempdir().unwrap();
2974 let a = dir.path().join("a.toml");
2975 let b = dir.path().join("b.toml");
2976 std::fs::write(&a, lower).unwrap();
2977 std::fs::write(&b, upper).unwrap();
2978 Config::load_layers(&[a, b])
2979 }
2980
2981 #[test]
2982 fn graph_implementers_higher_layer_wins_across_spellings() {
2983 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
2984 assert_eq!(c.graph.implementers, 5);
2985 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
2986 assert_eq!(c.graph.implementers, 5);
2987 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
2988 assert_eq!(c.graph.implementers, 2);
2989 }
2990
2991 #[test]
2992 fn graph_implementers_both_keys_in_one_layer_is_refused() {
2993 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
2994 .unwrap_err()
2995 .to_string();
2996 assert!(
2997 err.contains("candidates") && err.contains("implementers"),
2998 "{err}"
2999 );
3000 assert!(err.contains("b.toml"), "{err}");
3001 }
3002
3003 #[test]
3004 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3005 let g: Graph =
3009 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3010 .expect("an old-shaped [graph] table must still parse");
3011 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3012 assert!(
3013 !g.e2e_every_round,
3014 "off by default, same as before this field existed"
3015 );
3016 }
3017
3018 #[test]
3019 fn empty_roles_rotate_judges_off_their_own_candidate() {
3020 let cfg = Config {
3023 agents: vec![spec("a"), spec("b"), spec("c")],
3024 graph: Graph {
3025 implementers: 3,
3026 ..Graph::default()
3027 },
3028 ..Config::default()
3029 };
3030 let roles = cfg.resolve_roles().unwrap();
3031 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3032 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3033 assert_eq!(impls, ["a", "b", "c"]);
3034 assert_eq!(judges, ["b", "c", "a"]);
3035 for (i, j) in judges.iter().enumerate() {
3036 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3037 }
3038 }
3039
3040 #[test]
3041 fn single_agent_roster_fills_every_seat() {
3042 let cfg = Config {
3043 agents: vec![spec("solo")],
3044 graph: Graph {
3045 implementers: 3,
3046 ..Graph::default()
3047 },
3048 ..Config::default()
3049 };
3050 let roles = cfg.resolve_roles().unwrap();
3051 assert_eq!(roles.implementers.len(), 3);
3052 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3053 }
3054
3055 #[test]
3056 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3057 let cfg = Config {
3062 agents: vec![spec("a"), spec("b"), spec("c")],
3063 graph: Graph {
3064 implementers: 1,
3065 ..Graph::default()
3066 },
3067 ..Config::default()
3068 };
3069 let roles = cfg.resolve_roles().unwrap();
3070 assert_eq!(roles.implementers.len(), 1);
3071 let roster: Vec<&str> = roles
3072 .implementer_roster
3073 .iter()
3074 .map(|a| a.id.as_str())
3075 .collect();
3076 assert_eq!(roster, ["a", "b", "c"]);
3077 }
3078
3079 #[test]
3080 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3081 let cfg = Config {
3082 agents: vec![spec("a"), spec("b"), spec("c")],
3083 roles: Roles {
3084 implementers: vec!["c".to_owned(), "a".to_owned()],
3085 ..Roles::default()
3086 },
3087 graph: Graph {
3088 implementers: 1,
3089 ..Graph::default()
3090 },
3091 ..Config::default()
3092 };
3093 let roles = cfg.resolve_roles().unwrap();
3094 assert_eq!(roles.implementers.len(), 1);
3096 assert_eq!(roles.implementers[0].id, "c");
3097 let roster: Vec<&str> = roles
3098 .implementer_roster
3099 .iter()
3100 .map(|a| a.id.as_str())
3101 .collect();
3102 assert_eq!(roster, ["c", "a"]);
3103 }
3104
3105 #[test]
3106 fn explicit_roles_win() {
3107 let cfg = Config {
3108 agents: vec![spec("a"), spec("b")],
3109 roles: Roles {
3110 implementers: vec!["b".to_owned()],
3111 judges: vec!["a".to_owned()],
3112 reviewers: Vec::new(),
3113 fixer: Some("a".into()),
3114 ..Roles::default()
3115 },
3116 ..Config::default()
3117 };
3118 let roles = cfg.resolve_roles().unwrap();
3119 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3120 assert!(roles.judges.iter().all(|a| a.id == "a"));
3121 let fixer = roles.fixer.unwrap();
3122 assert_eq!(fixer.len(), 1);
3123 assert_eq!(fixer[0].id, "a");
3124 assert_eq!(roles.conductor.id, "a");
3125 }
3126
3127 #[test]
3128 fn fixer_takes_a_string_or_an_ordered_chain() {
3129 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3130 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3131 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3132 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3133
3134 let resolve = |fixer: Option<AgentChoice>| {
3135 Config {
3136 agents: vec![spec("a"), spec("b"), spec("c")],
3137 roles: Roles {
3138 fixer,
3139 ..Roles::default()
3140 },
3141 ..Config::default()
3142 }
3143 .resolve_roles()
3144 };
3145 let ids = |r: &ResolvedRoles| -> Vec<String> {
3146 r.fixer
3147 .as_ref()
3148 .unwrap()
3149 .iter()
3150 .map(|s| s.id.clone())
3151 .collect()
3152 };
3153 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3155 assert!(resolve(None).unwrap().fixer.is_none());
3156 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3158 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3159 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3161 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3162 }
3163
3164 #[test]
3165 fn unknown_agent_id_is_an_error() {
3166 let cfg = Config {
3167 agents: vec![spec("a")],
3168 roles: Roles {
3169 judges: vec!["nope".to_owned()],
3170 ..Roles::default()
3171 },
3172 ..Config::default()
3173 };
3174 assert!(cfg.resolve_roles().is_err());
3175 }
3176
3177 #[test]
3178 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3179 let mut cfg = Config {
3180 agents: vec![spec("a"), spec("b")],
3181 ..Config::default()
3182 };
3183 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3184
3185 cfg.roles.conductor = Some("b".into());
3186 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3187
3188 cfg.roles.conductor = Some("missing".into());
3189 assert!(cfg.resolve_roles().is_err());
3190 }
3191
3192 #[test]
3193 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3194 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3195 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3196 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3197
3198 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3199 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3200 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3201
3202 for roles in [one, chain] {
3203 let text = toml::to_string(&roles).unwrap();
3204 let back: Roles = toml::from_str(&text).unwrap();
3205 assert_eq!(back.synthesizer, roles.synthesizer);
3206 assert_eq!(back.chatter, roles.chatter);
3207 }
3208 let text = toml::to_string(&Roles {
3209 conductor: Some("x".into()),
3210 ..Roles::default()
3211 })
3212 .unwrap();
3213 assert!(
3214 text.contains("conductor = \"x\""),
3215 "string stays a string: {text}"
3216 );
3217 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3218 }
3219
3220 #[test]
3221 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3222 for (text, ids) in [
3223 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3224 (
3225 r#"dupes_judge = ["first", "second"]"#,
3226 vec!["first", "second"],
3227 ),
3228 ("dupes_judge = []", vec![]),
3229 ] {
3230 let roles: Roles = toml::from_str(text).unwrap();
3231 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3232 let serialized = toml::to_string(&roles).unwrap();
3233 let back: Roles = toml::from_str(&serialized).unwrap();
3234 assert_eq!(back.dupes_judge, roles.dupes_judge);
3235 assert!(serialized.contains(text));
3236 }
3237 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3238 assert!(Roles::default().dupes_judge.is_none());
3239 assert!(Config::starter_toml().contains("# dupes_judge ="));
3240
3241 let mut cfg = Config {
3243 agents: vec![spec("a")],
3244 ..Config::default()
3245 };
3246 cfg.roles.dupes_judge = Some("missing".into());
3247 assert!(cfg.resolve_roles().is_ok());
3248 }
3249
3250 #[test]
3251 fn an_empty_choice_counts_as_unset() {
3252 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3253 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3254 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3255 }
3256
3257 #[test]
3258 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3259 let mut cfg = Config {
3265 agents: vec![spec("a"), spec("b")],
3266 ..Config::default()
3267 };
3268 let want = primary(cfg.roles.synthesizer.as_ref());
3269 assert_eq!(
3270 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3271 .unwrap()
3272 .id,
3273 "a",
3274 "unset falls back to agent::pick's own default order"
3275 );
3276
3277 cfg.roles.synthesizer = Some("b".into());
3278 let want = primary(cfg.roles.synthesizer.as_ref());
3279 assert_eq!(
3280 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3281 .unwrap()
3282 .id,
3283 "b",
3284 "the named agent wins over the default order"
3285 );
3286 }
3287
3288 #[test]
3289 fn empty_roster_is_an_error() {
3290 assert!(Config::default().resolve_roles().is_err());
3291 }
3292
3293 #[test]
3294 fn advise_defaults_to_on_with_three_proposals() {
3295 let g = Graph::default();
3296 assert!(g.advise);
3297 assert!(g.graft_runner_up, "graft is on by default");
3298 assert_eq!(g.advisors, 3);
3299 }
3300
3301 #[test]
3302 fn unset_advisors_falls_back_to_the_judge_roster() {
3303 let cfg = Config {
3304 agents: vec![spec("a"), spec("b")],
3305 roles: Roles {
3306 judges: vec!["b".to_owned()],
3307 ..Roles::default()
3308 },
3309 graph: Graph {
3310 advisors: 2,
3311 ..Graph::default()
3312 },
3313 ..Config::default()
3314 };
3315 let advisors = cfg.advisors().expect("advisors resolve");
3316 assert_eq!(advisors.len(), 2);
3317 assert!(
3318 advisors.iter().all(|a| a.id == "b"),
3319 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3320 );
3321 }
3322
3323 #[test]
3324 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3325 let cfg = Config {
3326 agents: vec![spec("a"), spec("b")],
3327 roles: Roles {
3328 judges: vec!["b".to_owned()],
3329 advisors: vec!["a".to_owned()],
3330 ..Roles::default()
3331 },
3332 graph: Graph {
3333 advisors: 2,
3334 ..Graph::default()
3335 },
3336 ..Config::default()
3337 };
3338 let advisors = cfg.advisors().expect("advisors resolve");
3339 assert!(advisors.iter().all(|a| a.id == "a"));
3340 }
3341
3342 #[test]
3348 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3349 let cfg = Config {
3350 agents: vec![spec("a"), spec("b"), spec("c")],
3351 graph: Graph {
3352 advisors: 3,
3353 judges: 3,
3354 ..Graph::default()
3355 },
3356 ..Config::default()
3357 };
3358 let advisors = cfg.advisors().expect("advisors resolve");
3359 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3360 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3361 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3362 assert_eq!(
3363 advisor_ids, judge_ids,
3364 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3365 );
3366 }
3367
3368 #[test]
3369 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3370 let cfg = Config {
3371 agents: vec![spec("a")],
3372 roles: Roles {
3373 advisors: vec!["nope".to_owned()],
3374 ..Roles::default()
3375 },
3376 graph: Graph {
3377 advisors: 1,
3378 ..Graph::default()
3379 },
3380 ..Config::default()
3381 };
3382 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3383 assert!(format!("{err:#}").contains("nope"));
3384 }
3385
3386 #[test]
3387 fn repos_default_to_no_roots_and_a_day_of_trust() {
3388 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3389 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3390 assert_eq!(Config::default().repos.fetch_interval, 600);
3391 }
3392
3393 #[test]
3394 fn a_config_file_with_no_repos_table_still_loads() {
3395 let dir = tempfile::tempdir().unwrap();
3396 let path = dir.path().join("magi.toml");
3397 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3398 let cfg = Config::load(&path).expect("must load without [repos]");
3399 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3400 assert_eq!(cfg.repos.scan_ttl, 86_400);
3401 }
3402
3403 #[test]
3418 fn a_test_build_does_not_read_the_operators_machine_config() {
3419 let repo = tempfile::tempdir().unwrap();
3420 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3421
3422 let layers = Config::layers(repo.path());
3423 assert_eq!(
3424 layers,
3425 vec![repo.path().join("magi.toml")],
3426 "only the fixture's own file may be a layer"
3427 );
3428 if let Some(real) = dirs::config_dir() {
3429 let machine = real.join("magi").join("config.toml");
3430 assert!(
3431 !layers.contains(&machine),
3432 "the operator's {} must not be a layer in a test build",
3433 machine.display()
3434 );
3435 }
3436 }
3437
3438 #[test]
3439 fn starter_toml_loads_through_teravars() {
3440 let dir = tempfile::tempdir().unwrap();
3441 let path = dir.path().join("magi.toml");
3442 std::fs::write(&path, Config::starter_toml()).unwrap();
3443 let parsed = Config::load(&path).expect("starter config must load");
3444 assert_eq!(parsed.graph.implementers, 3);
3445 assert_eq!(parsed.merge.mode, MergeMode::None);
3446 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3447 assert!(parsed.graph.sessions);
3448 assert!(parsed.graph.github_text_guard);
3449 assert_eq!(parsed.graph.timeout_review, 1200);
3450 assert_eq!(parsed.graph.verify_timeout(), 1200);
3451 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3452 }
3453
3454 #[test]
3455 fn release_defaults_to_actions_and_the_starter_documents_it() {
3456 let dir = tempfile::tempdir().unwrap();
3457 let path = dir.path().join("magi.toml");
3458 std::fs::write(&path, Config::starter_toml()).unwrap();
3459 let r = Config::load(&path).unwrap().release;
3460 assert_eq!(r.mode, ReleaseMode::Actions);
3461 assert!(!r.is_local());
3462 assert!(r.commands.is_empty());
3463 assert_eq!(r.timeout_minutes, 30);
3464 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3465 }
3466
3467 #[test]
3468 fn release_local_parses_and_unknown_keys_are_refused() {
3469 let dir = tempfile::tempdir().unwrap();
3470 let path = dir.path().join("magi.toml");
3471 std::fs::write(
3472 &path,
3473 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3474 )
3475 .unwrap();
3476 let r = Config::load(&path).unwrap().release;
3477 assert!(r.is_local());
3478 assert_eq!(r.commands.len(), 2);
3479 assert_eq!(r.timeout_minutes, 5);
3480 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3481 assert!(Config::load(&path).is_err());
3482 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3483 assert!(Config::load(&path).is_err());
3484 }
3485
3486 #[test]
3487 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3488 let dir = tempfile::tempdir().unwrap();
3489 let path = dir.path().join("magi.toml");
3490 std::fs::write(&path, Config::starter_toml()).unwrap();
3491 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3492 assert!(Config::starter_toml().contains("# pre_gate = []"));
3493 }
3494
3495 #[test]
3496 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3497 let starter = Config::starter_toml();
3498 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3499 assert!(starter.contains("verification independent if timeout_review changes later"));
3500 assert!(starter.contains("# timeout_verify = 1200"));
3501 }
3502
3503 #[test]
3504 fn starter_toml_documents_chat_personas() {
3505 let starter = Config::starter_toml();
3506 assert!(starter.contains("# [[talk.personas]]"));
3507 assert!(starter.contains("tone only"));
3508 }
3509
3510 #[test]
3511 fn talk_personas_parse_and_are_validated() {
3512 let dir = tempfile::tempdir().unwrap();
3513 let path = dir.path().join("magi.toml");
3514 std::fs::write(
3515 &path,
3516 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3517 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3518 )
3519 .unwrap();
3520 let cfg = Config::load(&path).expect("loads");
3521 assert_eq!(cfg.talk.personas.len(), 2);
3522 let catalog = crate::persona::catalog(&cfg.talk.personas);
3523 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3524 assert_eq!(
3525 (rei.name.as_str(), rei.prompt.as_str()),
3526 ("Quiet", "Be brief.")
3527 );
3528 assert_eq!(catalog.last().unwrap().id, "gendo");
3529
3530 for (body, needle) in [
3531 (
3532 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3533 "empty `id`",
3534 ),
3535 (
3536 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3537 "empty `prompt`",
3538 ),
3539 (
3540 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3541 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3542 "more than once",
3543 ),
3544 (
3545 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3546 "cannot be redefined",
3547 ),
3548 ] {
3549 std::fs::write(&path, body).unwrap();
3550 let err = format!("{:#}", Config::load(&path).unwrap_err());
3551 assert!(err.contains(needle), "{needle}: {err}");
3552 }
3553 }
3554
3555 #[test]
3556 fn talk_operator_name_is_trimmed_and_validated() {
3557 let dir = tempfile::tempdir().unwrap();
3558 let path = dir.path().join("magi.toml");
3559 let load = |body: &str| {
3560 std::fs::write(&path, body).unwrap();
3561 Config::load(&path)
3562 };
3563 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3564 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3565 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3566 assert_eq!(blank.talk.operator_name(), None);
3567 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3568 let long = "x".repeat(65);
3569 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3570 }
3571
3572 #[test]
3573 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3574 let dir = tempfile::tempdir().unwrap();
3575 let load = |body: &str| {
3576 let path = dir.path().join("c.toml");
3577 std::fs::write(&path, body).unwrap();
3578 Config::load(&path)
3579 };
3580 let ok = load(
3581 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3582 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3583 )
3584 .unwrap();
3585 let c = crate::persona::catalog(&ok.talk.personas);
3586 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3587 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3588 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3589 let oversized = format!(
3590 "data:image/png;base64,{}",
3591 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3592 );
3593 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3594 for (id, fields) in [
3595 ("rei", ""),
3596 ("default", ""),
3597 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3598 ] {
3599 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3600 let cfg = load(&body).expect("bad icon must not invalidate config");
3601 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3602 assert_eq!(persona.id, id);
3603 assert!(crate::persona_icon::load(bad).is_err());
3604 }
3605 }
3606 let doc = Config::starter_toml();
3607 assert!(doc.contains("# icon = "));
3608 }
3609
3610 #[test]
3611 fn talk_personas_in_two_layers_are_refused() {
3612 let dir = tempfile::tempdir().unwrap();
3613 let machine = dir.path().join("machine.toml");
3614 let repo = dir.path().join("repo.toml");
3615 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3616 std::fs::write(&machine, one).unwrap();
3617 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3618 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3619 assert!(err.contains("talk.personas"), "{err}");
3620 }
3621
3622 #[test]
3623 fn starter_toml_documents_role_lists_as_backup_order() {
3624 let starter = Config::starter_toml();
3625 assert!(starter.contains("also an ordered backup list"));
3626 assert!(starter.contains("codex then sonnet are spares"));
3627 }
3628
3629 #[test]
3633 fn a_repository_can_declare_a_linear_history_merge_style() {
3634 let dir = tempfile::tempdir().unwrap();
3635 let path = dir.path().join("magi.toml");
3636 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3637 let parsed = Config::load(&path).expect("config must load");
3638 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3639 }
3640
3641 #[test]
3642 fn later_layers_win_and_vars_render() {
3643 let dir = tempfile::tempdir().unwrap();
3644 let machine = dir.path().join("machine.toml");
3645 let project = dir.path().join("magi.toml");
3646 std::fs::write(
3648 &machine,
3649 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3650 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3651 )
3652 .unwrap();
3653 std::fs::write(
3656 &project,
3657 "[vars]\ncache = \"/shared\"\n\n\
3658 [graph]\ncandidates = 2\n\n\
3659 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3660 )
3661 .unwrap();
3662
3663 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3664 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3665 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3666 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3667 assert_eq!(
3668 cfg.verify.gate,
3669 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3670 );
3671 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3673 }
3674
3675 #[test]
3676 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3677 let g = Graph::default();
3681 assert_eq!(g.timeout_talk, 3600);
3682
3683 let dir = tempfile::tempdir().unwrap();
3684 let path = dir.path().join("magi.toml");
3685 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3686 let cfg = Config::load(&path).expect("must load without timeout_talk set");
3687 assert_eq!(cfg.graph.timeout_talk, 3600);
3688 }
3689
3690 #[test]
3691 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
3692 let dir = tempfile::tempdir().unwrap();
3693 let path = dir.path().join("magi.toml");
3694 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
3695 let cfg = Config::load(&path).expect("must load");
3696 assert_eq!(cfg.graph.timeout_talk, 120);
3697 }
3698
3699 #[test]
3700 fn the_disk_defaults_are_the_measurements_made_up_front() {
3701 let cfg = Config::default();
3702 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
3703 assert!(cfg.disk.auto_fold);
3704 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
3705 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
3706 }
3707
3708 #[test]
3709 fn an_unset_disk_section_is_the_safe_default() {
3710 let dir = tempfile::tempdir().unwrap();
3711 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
3712 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
3713 assert_eq!(cfg.disk, Disk::default());
3714 }
3715
3716 #[test]
3717 fn env_is_available_to_templates_with_a_default() {
3718 let dir = tempfile::tempdir().unwrap();
3719 let path = dir.path().join("magi.toml");
3720 std::fs::write(
3728 &path,
3729 "[verify]\n\
3730 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
3731 \"populated={{ env | length > 0 }}\"]\n",
3732 )
3733 .unwrap();
3734 let cfg = Config::load(&path).expect("env lookup must render");
3735 assert_eq!(cfg.verify.gate[0], "cache=fallback");
3736 assert_eq!(cfg.verify.gate[1], "populated=true");
3737 }
3738
3739 #[test]
3740 fn a_broken_template_names_the_file() {
3741 let dir = tempfile::tempdir().unwrap();
3742 let path = dir.path().join("magi.toml");
3743 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
3744 let err = Config::load(&path).expect_err("must not silently ignore");
3745 assert!(err.to_string().contains("teravars"), "{err}");
3746 }
3747
3748 #[test]
3749 fn tera_syntax_in_comments_is_inert() {
3750 let dir = tempfile::tempdir().unwrap();
3754 let path = dir.path().join("magi.toml");
3755 std::fs::write(
3756 &path,
3757 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
3758 [graph]\ncandidates = 2\n",
3759 )
3760 .unwrap();
3761 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
3762 assert_eq!(cfg.graph.implementers, 2);
3763 }
3764
3765 #[test]
3766 fn opencode_defaults_to_file_delivery() {
3767 let mut s = spec("oc");
3768 s.kind = AgentKind::Opencode;
3769 assert_eq!(s.delivery(), Delivery::File);
3770 s.prompt_delivery = Some(Delivery::Argv);
3771 assert_eq!(s.delivery(), Delivery::Argv);
3772 }
3773 #[test]
3774 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
3775 let g = Graph::default();
3780 assert!(
3781 g.land,
3782 "stopping at an open PR left the watching to a human"
3783 );
3784 assert!(
3785 g.land_approval,
3786 "on-by-default land is only defensible while this is also on"
3787 );
3788 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
3789 assert!(
3790 g.hold_contested_merge,
3791 "a contested hand-off must still reach a human when approvals are off"
3792 );
3793 }
3794 #[test]
3795 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
3796 let dir = tempfile::tempdir().unwrap();
3800 let machine = dir.path().join("machine.toml");
3801 let repo = dir.path().join("magi.toml");
3802 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
3803 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
3804
3805 let err = Config::load_layers(&[machine.clone(), repo.clone()])
3806 .expect_err("two layers naming one array must not merge silently");
3807 assert_eq!(
3808 err.downcast_ref::<ConfigFailure>().unwrap().stage,
3809 "config-merge"
3810 );
3811 let err = err.to_string();
3812 assert!(err.contains("roles.implementers"), "{err}");
3813 assert!(err.contains("machine.toml"), "{err}");
3816 assert!(err.contains("magi.toml"), "{err}");
3817 }
3818
3819 #[test]
3820 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
3821 let dir = tempfile::tempdir().unwrap();
3824 let machine = dir.path().join("machine.toml");
3825 let repo = dir.path().join("magi.toml");
3826 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
3827 std::fs::write(
3828 &repo,
3829 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
3830 [roles]\nimplementers = [\"oc\"]\n",
3831 )
3832 .unwrap();
3833
3834 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
3835 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
3836 assert_eq!(cfg.roles.implementers, ["oc"]);
3837 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
3838 }
3839
3840 #[test]
3841 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
3842 let dir = tempfile::tempdir().unwrap();
3845 let machine = dir.path().join("machine.toml");
3846 let repo = dir.path().join("magi.toml");
3847 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
3848 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3849
3850 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3851 assert_eq!(
3852 cfg.verify.gate,
3853 [
3854 "editorconfig-checker".to_owned(),
3855 "cargo make check".to_owned()
3856 ],
3857 "low-priority (machine) command first, high-priority (repo) command after"
3858 );
3859 }
3860
3861 fn load_one(body: &str) -> Result<Config> {
3862 let dir = tempfile::tempdir().unwrap();
3863 let path = dir.path().join("magi.toml");
3864 std::fs::write(&path, body).unwrap();
3865 Config::load_layers(&[path])
3866 }
3867
3868 #[test]
3869 fn worktree_setup_defaults_to_empty_and_parses_steps() {
3870 assert!(Config::default().worktree.setup.is_empty());
3871 let cfg = load_one(
3872 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
3873 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
3874 )
3875 .unwrap();
3876 assert_eq!(cfg.worktree.setup.len(), 3);
3877 assert!(cfg.worktree.setup[1].optional);
3878 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
3879 }
3880
3881 #[test]
3882 fn worktree_setup_rejects_malformed_steps() {
3883 for bad in [
3884 "{ copy = \"a\", run = \"b\" }",
3885 "{ optional = true }",
3886 "{ copy = \"a -> ../b\" }",
3887 "{ copy = \"a -> /abs\" }",
3888 "{ copy = \"a -> .git/config\" }",
3889 "{ run = \"b\", optional = true }",
3890 "{ copy = \"a\", timeout_secs = 3 }",
3891 "{ run = \"b\", bogus = 1 }",
3892 ] {
3893 let body = format!("[worktree]\nsetup = [{bad}]\n");
3894 assert!(load_one(&body).is_err(), "{bad}");
3895 }
3896 }
3897
3898 #[test]
3899 fn worktree_setup_in_two_layers_is_refused() {
3900 let dir = tempfile::tempdir().unwrap();
3901 let machine = dir.path().join("machine.toml");
3902 let repo = dir.path().join("magi.toml");
3903 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
3904 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
3905 assert!(Config::load_layers(&[machine, repo]).is_err());
3906 }
3907
3908 #[test]
3909 fn starter_toml_documents_worktree_setup() {
3910 let starter = Config::starter_toml();
3911 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
3912 let body = starter.replace("# [worktree]", "[worktree]");
3914 let mut out = String::new();
3915 let mut live = false;
3916 for line in body.lines() {
3917 if line == "[worktree]" {
3918 live = true;
3919 } else if live && !line.starts_with("# ") {
3920 live = false;
3921 }
3922 out.push_str(&if live {
3923 line.replacen("# ", "", 1)
3924 } else {
3925 line.to_owned()
3926 });
3927 out.push('\n');
3928 }
3929 let cfg = load_one(&out).expect("uncommented example loads");
3930 assert_eq!(cfg.worktree.setup.len(), 3);
3931 }
3932
3933 #[test]
3934 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
3935 let dir = tempfile::tempdir().unwrap();
3936 let machine = dir.path().join("machine.toml");
3937 let repo = dir.path().join("magi.toml");
3938 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
3939 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
3940
3941 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3942 assert_eq!(
3943 cfg.verify.e2e,
3944 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
3945 );
3946 }
3947
3948 #[test]
3949 fn two_layers_declaring_repos_roots_are_both_scanned() {
3950 let dir = tempfile::tempdir().unwrap();
3951 let machine = dir.path().join("machine.toml");
3952 let repo = dir.path().join("magi.toml");
3953 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
3954 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
3955
3956 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3957 assert_eq!(
3958 cfg.repos.roots,
3959 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
3960 );
3961 }
3962
3963 #[test]
3964 fn duplicate_gate_commands_across_layers_both_run() {
3965 let dir = tempfile::tempdir().unwrap();
3968 let machine = dir.path().join("machine.toml");
3969 let repo = dir.path().join("magi.toml");
3970 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
3971 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
3972
3973 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3974 assert_eq!(
3975 cfg.verify.gate,
3976 ["same-command".to_owned(), "same-command".to_owned()]
3977 );
3978 }
3979
3980 #[test]
3981 fn notify_command_is_still_refused_across_two_layers() {
3982 let dir = tempfile::tempdir().unwrap();
3984 let machine = dir.path().join("machine.toml");
3985 let repo = dir.path().join("magi.toml");
3986 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
3987 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
3988
3989 let err = Config::load_layers(&[machine.clone(), repo.clone()])
3990 .expect_err("an argv split across layers must not concatenate");
3991 assert_eq!(
3992 err.downcast_ref::<ConfigFailure>().unwrap().stage,
3993 "config-merge"
3994 );
3995 let err = err.to_string();
3996 assert!(err.contains("notify.command"), "{err}");
3997 assert!(err.contains("machine.toml"), "{err}");
3998 assert!(err.contains("magi.toml"), "{err}");
3999 }
4000
4001 #[test]
4002 fn one_layer_declaring_verify_gate_runs_unchanged() {
4003 let dir = tempfile::tempdir().unwrap();
4006 let path = dir.path().join("magi.toml");
4007 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4008
4009 let cfg = Config::load(&path).expect("single layer must still load");
4010 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4011 }
4012
4013 #[test]
4014 fn layered_parse_failures_name_the_failing_input() {
4015 let dir = tempfile::tempdir().unwrap();
4016 let a = dir.path().join("a.toml");
4017 let b = dir.path().join("b.toml");
4018 std::fs::write(&a, "[graph").unwrap();
4019 std::fs::write(&b, "[verify").unwrap();
4020 let paths = [a.clone(), b.clone()];
4021 let first = Config::load_layers(&paths).unwrap_err();
4022 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4023 assert_eq!(first_cause.stage, "config-parse");
4024 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4025 std::fs::write(&a, "").unwrap();
4026 let second = Config::load_layers(&paths).unwrap_err();
4027 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4028 assert_eq!(second_cause.stage, "config-parse");
4029 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4030 assert_ne!(first_cause.target, second_cause.target);
4031 }
4032
4033 #[test]
4034 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4035 let dir = tempfile::tempdir().unwrap();
4036 let machine = dir.path().join("machine.toml");
4037 let repo = dir.path().join("magi.toml");
4038 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4039 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4040 let paths = vec![machine.clone(), repo.clone()];
4041
4042 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4043 let described =
4044 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4045 assert!(described.contains("editorconfig-checker && cargo make check"));
4046 assert!(
4047 described.contains(&machine.display().to_string()),
4048 "{described}"
4049 );
4050 assert!(
4051 described.contains(&repo.display().to_string()),
4052 "{described}"
4053 );
4054
4055 let single = vec![repo.clone()];
4057 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4058 let solo_described =
4059 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4060 assert_eq!(solo_described, "cargo make check");
4061 }
4062
4063 mod remote_layers {
4064 use super::*;
4065
4066 fn git(dir: &Path, args: &[&str]) {
4067 use crate::proc::Quiet as _;
4068 let out = std::process::Command::new("git")
4069 .args(args)
4070 .quiet()
4071 .current_dir(dir)
4072 .output()
4073 .unwrap();
4074 assert!(out.status.success(), "git {args:?}: {out:?}");
4075 }
4076
4077 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4080 let tmp = tempfile::tempdir().unwrap();
4081 let bare = tmp.path().join("o.git");
4082 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4083 let repo = tmp.path().join("repo");
4084 std::fs::create_dir_all(&repo).unwrap();
4085 git(&repo, &["init", "-b", "trunk"]);
4086 git(&repo, &["config", "user.name", "t"]);
4087 git(&repo, &["config", "user.email", "t@example.com"]);
4088 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4089 git(&repo, &["add", "-A"]);
4090 git(&repo, &["commit", "-m", "x"]);
4091 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4092 git(&repo, &["push", "origin", "trunk"]);
4093 git(&repo, &["fetch", "origin"]);
4094 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4095 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4096 (tmp, repo)
4097 }
4098
4099 #[test]
4100 fn reads_the_remote_blob_not_the_working_tree() {
4101 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4102 let (cfg, _) = Config::discover(&repo, None).unwrap();
4103 assert_eq!(cfg.graph.implementers, 2);
4104 }
4105
4106 #[test]
4107 fn detached_head_still_reads_the_remote() {
4108 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4109 git(&repo, &["checkout", "--detach"]);
4110 let (cfg, _) = Config::discover(&repo, None).unwrap();
4111 assert_eq!(cfg.graph.implementers, 2);
4112 }
4113
4114 #[test]
4115 fn a_missing_ref_is_an_error_not_a_fallback() {
4116 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4117 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4118 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4119 assert!(err.contains("origin"), "{err}");
4120 }
4121
4122 #[test]
4123 fn merge_base_in_the_checkout_locates_the_ref() {
4124 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4125 assert!(Config::discover(&repo, None).is_err());
4126 }
4127
4128 #[test]
4129 fn the_magi_dir_layer_is_read_too() {
4130 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4131 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4132 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4133 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4134 git(&repo, &["add", "-A"]);
4135 git(&repo, &["commit", "-m", "y"]);
4136 git(&repo, &["push", "origin", "trunk"]);
4137 git(&repo, &["fetch", "origin"]);
4138 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4139 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4140 assert_eq!(layers.len(), 2);
4141 }
4142
4143 #[test]
4144 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4145 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4146 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4147 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4148 git(&repo, &["add", "-A"]);
4149 git(&repo, &["commit", "-m", "inc"]);
4150 git(&repo, &["push", "origin", "trunk"]);
4151 git(&repo, &["fetch", "origin"]);
4152 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4154 let (cfg, _) = Config::discover(&repo, None).unwrap();
4155 assert_eq!(cfg.graph.implementers, 2);
4156 }
4157
4158 #[test]
4159 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4160 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4161 let m = t.path().join("machine.toml");
4162 std::fs::write(
4163 &m,
4164 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4165 )
4166 .unwrap();
4167 let (remote, base) = {
4168 let probe = probe_merge(&m, &repo).unwrap();
4169 (probe.remote, probe.base)
4170 };
4171 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4172 }
4173
4174 #[test]
4175 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4176 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4177 let m = t.path().join("machine.toml");
4178 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4179 let probe = probe_merge(&m, &repo).unwrap();
4180 assert_eq!(probe.base.as_deref(), Some("repo"));
4181 }
4182
4183 #[test]
4184 fn every_include_form_is_recognised() {
4185 assert!(declares_include("include = [\"a.toml\"]\n"));
4186 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4187 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4188 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4189 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4190 }
4191
4192 #[test]
4193 fn an_explicit_config_is_read_as_named() {
4194 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4195 let own = t.path().join("own.toml");
4196 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4197 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4198 assert_eq!(cfg.graph.implementers, 4);
4199 }
4200
4201 #[test]
4202 fn discover_fetched_fails_when_the_fetch_does() {
4203 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4204 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4205 let rt = tokio::runtime::Builder::new_current_thread()
4206 .enable_all()
4207 .build()
4208 .unwrap();
4209 let err = rt
4210 .block_on(Config::discover_fetched(&repo, None))
4211 .unwrap_err();
4212 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4213 }
4214
4215 #[test]
4216 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4217 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4218 let remote = tmp.path().join("o.git");
4219 let offline = tmp.path().join("offline.git");
4220 std::fs::rename(&remote, &offline).unwrap();
4221 let rt = tokio::runtime::Builder::new_current_thread()
4222 .enable_all()
4223 .build()
4224 .unwrap();
4225 let fetch = rt
4226 .block_on(Config::discover_fetched(&repo, None))
4227 .unwrap_err();
4228 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4229 assert_eq!(fetch_cause.stage, "config-fetch");
4230 assert_eq!(fetch_cause.target, "origin/trunk");
4231
4232 std::fs::rename(&offline, &remote).unwrap();
4233 let parse = rt
4234 .block_on(Config::discover_fetched(&repo, None))
4235 .unwrap_err();
4236 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4237 assert_eq!(parse_cause.stage, "config-parse");
4238 assert!(parse_cause.target.contains("magi.toml"));
4239 assert!(
4240 !parse_cause.target.contains("/magi/config/"),
4241 "cache commit paths are incidental"
4242 );
4243 assert_ne!(fetch_cause.stage, parse_cause.stage);
4244 }
4245
4246 #[test]
4247 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4248 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4251 git(&repo, &["remote", "set-head", "origin", "-d"]);
4252 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4253 git(
4254 &repo,
4255 &["config", "remote.origin.followRemoteHEAD", "never"],
4256 );
4257 let rt = tokio::runtime::Builder::new_current_thread()
4258 .enable_all()
4259 .build()
4260 .unwrap();
4261 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4262 assert_eq!(cfg.graph.implementers, 2);
4263 }
4264
4265 #[test]
4266 fn a_non_git_directory_reads_its_files() {
4267 let dir = tempfile::tempdir().unwrap();
4268 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4269 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4270 assert_eq!(cfg.graph.implementers, 4);
4271 }
4272 }
4273
4274 #[test]
4275 fn github_language_defaults_to_english_and_accepts_japanese() {
4276 let default: Graph = toml::from_str("").unwrap();
4277 assert_eq!(default.github_language, "en");
4278 assert!(default.github_english() && default.language_gate());
4279 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4280 assert!(!ja.github_english() && !ja.language_gate());
4281 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4283 assert!(only_ops.language_gate());
4284 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4285 assert!(!off.language_gate() && off.github_english());
4286 assert!(Config::starter_toml().contains("github_language = \"en\""));
4287 }
4288}