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