1use std::collections::BTreeMap;
44use std::path::{Path, PathBuf};
45
46use anyhow::{Context as _, Result, bail};
47use serde::{Deserialize, Serialize};
48
49#[derive(Debug, thiserror::Error)]
52#[error("{stage}: {target}")]
53pub(crate) struct ConfigFailure {
54 pub(crate) stage: &'static str,
55 pub(crate) target: String,
56}
57
58impl ConfigFailure {
59 fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
60 let stage = match error {
61 teravars::Error::Io(_) => "config-read",
62 teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
63 teravars::Error::Render(_) => "config-template",
64 teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
65 "config-include"
66 }
67 _ => "config-render",
68 };
69 Self::layers(stage, paths)
70 }
71
72 fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
73 let targets: Vec<_> = paths
74 .iter()
75 .map(|path| {
76 path.ancestors()
79 .find(|p| p.join(REPO_MARKER).is_file())
80 .and_then(|root| path.strip_prefix(root).ok())
81 .unwrap_or(path)
82 .to_string_lossy()
83 .into_owned()
84 })
85 .collect();
86 Self {
87 stage,
88 target: serde_json::to_string(&targets).expect("config paths"),
89 }
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
95#[serde(rename_all = "lowercase")]
96pub enum AgentKind {
97 Claude,
99 Opencode,
101 Antigravity,
105 Codex,
109 Omp,
115 Command,
117}
118
119impl AgentKind {
120 pub fn program(self) -> Option<&'static str> {
122 match self {
123 Self::Claude => Some("claude"),
124 Self::Opencode => Some("opencode"),
125 Self::Antigravity => Some("agy"),
126 Self::Codex => Some("codex"),
127 Self::Omp => Some("omp"),
128 Self::Command => None,
129 }
130 }
131
132 pub fn as_str(self) -> &'static str {
134 match self {
135 Self::Claude => "claude",
136 Self::Opencode => "opencode",
137 Self::Antigravity => "antigravity",
138 Self::Codex => "codex",
139 Self::Omp => "omp",
140 Self::Command => "command",
141 }
142 }
143
144 pub const ALL: [Self; 6] = [
152 Self::Claude,
153 Self::Opencode,
154 Self::Antigravity,
155 Self::Codex,
156 Self::Omp,
157 Self::Command,
158 ];
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
163#[serde(rename_all = "lowercase")]
164pub enum Delivery {
165 Stdin,
167 Argv,
169 File,
171}
172
173#[derive(Debug, Clone, Deserialize, Serialize)]
175#[serde(deny_unknown_fields)]
176pub struct AgentSpec {
177 pub id: String,
179 pub kind: AgentKind,
181 #[serde(default)]
183 pub model: Option<String>,
184 #[serde(default)]
187 pub command: Vec<String>,
188 #[serde(default)]
190 pub extra_args: Vec<String>,
191 #[serde(default)]
193 pub env: BTreeMap<String, String>,
194 #[serde(default)]
196 pub prompt_delivery: Option<Delivery>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub max_turn_secs: Option<u64>,
201}
202
203impl AgentSpec {
204 pub fn turn_timeout(&self, budget: std::time::Duration) -> std::time::Duration {
206 self.max_turn_secs.map_or(budget, |secs| {
207 budget.min(std::time::Duration::from_secs(secs))
208 })
209 }
210
211 pub fn delivery(&self) -> Delivery {
217 self.prompt_delivery.unwrap_or(match self.kind {
218 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
219 AgentKind::Codex => Delivery::Stdin,
223 AgentKind::Omp => Delivery::Stdin,
227 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
228 })
229 }
230
231 pub fn display(&self) -> String {
233 match &self.model {
234 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
235 None => format!("{} ({})", self.id, self.kind.as_str()),
236 }
237 }
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
247#[serde(untagged)]
248pub enum AgentChoice {
249 One(String),
251 Chain(Vec<String>),
253}
254
255impl AgentChoice {
256 pub fn ids(&self) -> Vec<&str> {
258 let all: Vec<&str> = match self {
259 Self::One(id) => vec![id.as_str()],
260 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
261 };
262 all.into_iter()
263 .map(str::trim)
264 .filter(|id| !id.is_empty())
265 .collect()
266 }
267
268 pub fn primary(&self) -> Option<&str> {
270 self.ids().into_iter().next()
271 }
272}
273
274impl From<&str> for AgentChoice {
275 fn from(id: &str) -> Self {
276 Self::One(id.to_owned())
277 }
278}
279
280pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
282 choice.and_then(AgentChoice::primary)
283}
284
285#[derive(Debug, Clone, Default, Deserialize, Serialize)]
288#[serde(deny_unknown_fields, default)]
289pub struct Roles {
290 pub implementers: Vec<String>,
292 pub judges: Vec<String>,
294 pub reviewers: Vec<String>,
296 pub fixer: Option<AgentChoice>,
305 pub chatter: Option<AgentChoice>,
319 pub dupes_judge: Option<AgentChoice>,
323 pub conductor: Option<AgentChoice>,
336 pub advisors: Vec<String>,
347 pub synthesizer: Option<AgentChoice>,
360 pub language_judge: Option<AgentChoice>,
369}
370
371#[derive(Debug, Clone, Deserialize, Serialize)]
373#[serde(deny_unknown_fields, default)]
374pub struct Graph {
375 #[serde(rename = "editing_network", skip_serializing)]
379 pub retired_editing_network: Option<serde::de::IgnoredAny>,
380 pub github_text_guard: bool,
382 pub github_language: String,
388 #[serde(alias = "candidates")]
420 pub implementers: usize,
421 #[serde(default)]
423 pub selected_implementer: Option<String>,
424 pub judges: usize,
426 pub deliberate_rounds: usize,
428 pub reviewers: usize,
436 pub review_rounds: usize,
438 pub gate_fix_rounds: usize,
444 pub max_parallel: usize,
446 pub language: String,
448 pub sessions: bool,
456 pub timeout_implement: u64,
458 pub timeout_judge: u64,
460 pub timeout_review: u64,
462 pub timeout_verify: Option<u64>,
471 pub timeout_fix: u64,
473 pub timeout_talk: u64,
481 pub timeout_resource_wait: u64,
490 pub retries: usize,
492 pub worktree_root: Option<PathBuf>,
494 pub land: bool,
507 pub land_rounds: usize,
509 pub rerun_flaky_checks: bool,
517 pub land_approval: bool,
528 pub hold_contested_merge: bool,
539 pub question_routing: bool,
542 pub file_followups: bool,
549 pub release_deputy_followups: bool,
557 pub answer_timeout: u64,
561 pub incomplete_review: IncompleteReviewPolicy,
564 pub e2e_every_round: bool,
582 pub advise: bool,
596 pub advisors: usize,
601 pub graft_runner_up: bool,
610}
611
612impl Default for Graph {
613 fn default() -> Self {
614 Self {
615 github_text_guard: true,
616 github_language: "en".into(),
617 implementers: 1,
618 selected_implementer: None,
619 retired_editing_network: None,
620 judges: 3,
621 deliberate_rounds: 1,
622 reviewers: 3,
623 review_rounds: 6,
624 gate_fix_rounds: 1,
625 max_parallel: 4,
626 language: "en".to_owned(),
627 sessions: true,
628 timeout_implement: 3600,
629 timeout_judge: 1200,
630 timeout_review: 1200,
631 timeout_verify: None,
632 timeout_fix: 1800,
633 timeout_talk: 3600,
634 timeout_resource_wait: 1800,
635 retries: 1,
636 worktree_root: None,
637 land: true,
638 land_rounds: 4,
639 rerun_flaky_checks: true,
640 land_approval: true,
641 hold_contested_merge: true,
642 question_routing: true,
643 file_followups: true,
644 release_deputy_followups: true,
645 answer_timeout: 86_400,
646 incomplete_review: IncompleteReviewPolicy::Block,
647 e2e_every_round: false,
648 advise: true,
649 advisors: 3,
650 graft_runner_up: true,
651 }
652 }
653}
654
655impl Graph {
656 pub fn verify_timeout(&self) -> u64 {
660 self.timeout_verify.unwrap_or(self.timeout_review)
661 }
662
663 pub fn language_gate(&self) -> bool {
666 self.github_text_guard && self.github_english()
667 }
668
669 pub fn github_english(&self) -> bool {
671 crate::lang::is_english(&self.github_language)
672 }
673}
674
675#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
682#[serde(rename_all = "lowercase")]
683pub enum IncompleteReviewPolicy {
684 Block,
688 Warn,
693}
694
695#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
697#[serde(rename_all = "lowercase")]
698pub enum LeakPolicy {
699 Warn,
701 Redact,
703 Fail,
705}
706
707#[derive(Debug, Clone, Deserialize, Serialize)]
714#[serde(deny_unknown_fields, default)]
715pub struct Blind {
716 pub commit_msg_hook: bool,
719 pub strip_lines: Vec<String>,
723 pub vendor_tokens: Vec<String>,
725 pub on_leak: LeakPolicy,
727 pub seed: Option<u64>,
730}
731
732impl Default for Blind {
733 fn default() -> Self {
734 Self {
735 commit_msg_hook: true,
736 strip_lines: [
737 "Co-Authored-By:",
738 "Signed-off-by:",
739 "Assisted-by:",
740 "Generated-by:",
741 "Generated with",
742 "\u{1f916}",
743 ]
744 .iter()
745 .map(|s| (*s).to_owned())
746 .collect(),
747 vendor_tokens: [
748 "claude",
749 "anthropic",
750 "codex",
751 "openai",
752 "chatgpt",
753 "gemini",
754 "grok",
755 "xai",
756 "copilot",
757 "opencode",
758 "qoder",
759 "cursor",
760 "\u{1f916}",
761 ]
762 .iter()
763 .map(|s| (*s).to_owned())
764 .collect(),
765 on_leak: LeakPolicy::Warn,
766 seed: None,
767 }
768 }
769}
770
771#[derive(Debug, Clone, Default, Deserialize, Serialize)]
773#[serde(deny_unknown_fields, default)]
774pub struct Verify {
775 pub e2e: Vec<String>,
778 pub gate: Vec<String>,
780 #[serde(default)]
789 pub pre_gate: Vec<String>,
790 pub shell: Option<Vec<String>>,
793}
794
795impl Verify {
796 pub fn cache_dir(&self) -> Option<PathBuf> {
802 self.e2e
803 .iter()
804 .chain(self.gate.iter())
805 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
806 }
807
808 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
811 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
812 crate::cache::extract_manifest_paths(&all)
813 }
814}
815
816#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
818#[serde(deny_unknown_fields, default)]
819pub struct Worktree {
820 pub setup: Vec<SetupStep>,
823 pub pre_clean: Vec<PreCleanStep>,
825}
826
827#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
829#[serde(deny_unknown_fields)]
830pub struct PreCleanStep {
831 pub run: String,
833 pub timeout_secs: Option<u64>,
835}
836
837#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
839#[serde(deny_unknown_fields, default)]
840pub struct SetupStep {
841 pub copy: Option<String>,
844 pub optional: bool,
846 pub run: Option<String>,
848 pub timeout_secs: Option<u64>,
851}
852
853impl Worktree {
854 pub fn validate(&self) -> Result<()> {
856 for (i, step) in self.pre_clean.iter().enumerate() {
857 if step.run.trim().is_empty() || step.timeout_secs == Some(0) {
858 bail!(
859 "[worktree] pre_clean step {} requires a nonempty run and positive timeout",
860 i + 1
861 );
862 }
863 }
864 for (i, step) in self.setup.iter().enumerate() {
865 let n = i + 1;
866 match (&step.copy, &step.run) {
867 (Some(c), None) => {
868 if step.timeout_secs.is_some() {
869 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
870 }
871 crate::worktree_setup::validate_copy(c)
872 .with_context(|| format!("[worktree] setup step {n}"))?;
873 }
874 (None, Some(r)) => {
875 if r.trim().is_empty() {
876 bail!("[worktree] setup step {n}: `run` is empty");
877 }
878 if step.optional {
879 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
880 }
881 }
882 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
883 }
884 }
885 Ok(())
886 }
887}
888
889#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
899#[serde(deny_unknown_fields, default)]
900pub struct Disk {
901 pub min_free_bytes: u64,
910 pub auto_fold: bool,
916 pub fold_grace_secs: u64,
924 pub cache_limit_bytes: u64,
936 pub worktree_limit_bytes: u64,
938 pub worktree_reclaim_bytes: u64,
942 pub retained_attempt_limit: usize,
946}
947
948impl Default for Disk {
949 fn default() -> Self {
950 Self {
951 min_free_bytes: 8 * 1024 * 1024 * 1024,
952 auto_fold: true,
953 fold_grace_secs: 6 * 60 * 60,
954 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
955 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
956 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
957 retained_attempt_limit: 8,
958 }
959 }
960}
961
962#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
964#[serde(rename_all = "lowercase")]
965pub enum MergeMode {
966 None,
969 Local,
972 Pr,
976}
977
978#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
992#[serde(rename_all = "lowercase")]
993pub enum MergeStyle {
994 #[default]
999 Merge,
1000 Squash,
1006 Rebase,
1012}
1013
1014#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1016#[serde(rename_all = "lowercase")]
1017pub enum MergeCi {
1018 #[default]
1020 Expected,
1021 None,
1023}
1024
1025impl MergeCi {
1026 pub fn expectation(self) -> crate::land::CiExpectation {
1028 match self {
1029 Self::Expected => crate::land::CiExpectation::Expected,
1030 Self::None => crate::land::CiExpectation::Absent,
1031 }
1032 }
1033}
1034
1035#[derive(Debug, Clone, Deserialize, Serialize)]
1037#[serde(deny_unknown_fields, default)]
1038pub struct Merge {
1039 pub mode: MergeMode,
1042 pub ci: MergeCi,
1044 pub base: Option<String>,
1046 pub style: MergeStyle,
1049 pub remote: String,
1051 pub release_bump: bool,
1064}
1065
1066impl Default for Merge {
1067 fn default() -> Self {
1068 Self {
1069 mode: MergeMode::None,
1070 ci: MergeCi::Expected,
1071 base: None,
1072 style: MergeStyle::default(),
1073 remote: "origin".to_owned(),
1074 release_bump: true,
1075 }
1076 }
1077}
1078
1079#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1081#[serde(rename_all = "lowercase")]
1082pub enum UpdateMode {
1083 Off,
1085 Notify,
1088 Install,
1090}
1091
1092#[derive(Debug, Clone, Deserialize, Serialize)]
1094#[serde(deny_unknown_fields, default)]
1095pub struct Update {
1096 pub mode: UpdateMode,
1098 pub interval: Option<String>,
1100 pub auto_restart: bool,
1102}
1103
1104impl Default for Update {
1105 fn default() -> Self {
1106 Self {
1107 mode: UpdateMode::Notify,
1108 interval: None,
1109 auto_restart: false,
1110 }
1111 }
1112}
1113
1114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1116#[serde(rename_all = "lowercase")]
1117pub enum ReleaseMode {
1118 #[default]
1121 Actions,
1122 Local,
1127}
1128
1129#[derive(Debug, Clone, Deserialize, Serialize)]
1131#[serde(deny_unknown_fields, default)]
1132pub struct Release {
1133 pub mode: ReleaseMode,
1136 pub commands: Vec<String>,
1143 pub timeout_minutes: u64,
1145 pub version_files: Vec<VersionFile>,
1153}
1154
1155#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1157#[serde(rename_all = "lowercase")]
1158pub enum VersionKind {
1159 Cargo,
1161 Json,
1163}
1164
1165#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1167#[serde(deny_unknown_fields)]
1168pub struct VersionFile {
1169 pub path: String,
1171 pub kind: VersionKind,
1173}
1174
1175impl Default for Release {
1176 fn default() -> Self {
1177 Self {
1178 mode: ReleaseMode::Actions,
1179 commands: Vec::new(),
1180 timeout_minutes: 30,
1181 version_files: Vec::new(),
1182 }
1183 }
1184}
1185
1186impl Release {
1187 pub fn validate(&self) -> Result<()> {
1189 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1190 }
1191
1192 pub fn is_local(&self) -> bool {
1194 self.mode == ReleaseMode::Local
1195 }
1196}
1197
1198#[derive(Debug, Clone, Deserialize, Serialize)]
1200#[serde(try_from = "CoordinationFields")]
1201pub struct Coordination {
1202 pub contract_file: String,
1204 pub contract_token: String,
1206 pub lock_file: String,
1208}
1209
1210#[derive(Deserialize, Default)]
1211#[serde(deny_unknown_fields, default)]
1212struct CoordinationFields {
1213 contract_file: String,
1214 contract_token: String,
1215 lock_file: String,
1216}
1217
1218impl TryFrom<CoordinationFields> for Coordination {
1219 type Error = anyhow::Error;
1220
1221 fn try_from(fields: CoordinationFields) -> Result<Self> {
1222 for (key, name) in [
1223 ("coordination.contract_file", &fields.contract_file),
1224 ("coordination.lock_file", &fields.lock_file),
1225 ] {
1226 if name.trim().is_empty()
1227 || name != name.trim()
1228 || name == "."
1229 || name.contains("..")
1230 || name.contains(['/', '\\', ':', '\0'])
1231 {
1232 bail!(
1233 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1234 );
1235 }
1236 }
1237 let token = &fields.contract_token;
1238 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1239 bail!(
1240 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1241 );
1242 }
1243 Ok(Self {
1244 contract_file: fields.contract_file,
1245 contract_token: fields.contract_token,
1246 lock_file: fields.lock_file,
1247 })
1248 }
1249}
1250
1251#[cfg(test)]
1252pub(crate) fn test_coordination() -> Option<Coordination> {
1253 Some(Coordination {
1254 contract_file: "updater.contract".into(),
1255 contract_token: "test-protocol-v1".into(),
1256 lock_file: "updater.lock".into(),
1257 })
1258}
1259
1260#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1262#[serde(deny_unknown_fields, default)]
1263pub struct Config {
1264 pub coordination: Option<Coordination>,
1266 pub agents: Vec<AgentSpec>,
1268 pub roles: Roles,
1270 pub graph: Graph,
1272 pub blind: Blind,
1274 pub verify: Verify,
1276 pub worktree: Worktree,
1278 pub disk: Disk,
1280 pub merge: Merge,
1282 pub update: Update,
1284 pub prompts: Prompts,
1286 pub notify: Notify,
1288 pub repos: Repos,
1291 pub talk: Talk,
1293 pub daemon: Daemon,
1295 pub release: Release,
1297 pub context_windows: BTreeMap<String, u64>,
1300}
1301
1302const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1312 ("claude-opus-4", 200_000),
1313 ("claude-sonnet-4", 200_000),
1314 ("claude-haiku-4", 200_000),
1315 ("claude-3", 200_000),
1316 ("opus", 200_000),
1317 ("sonnet", 200_000),
1318 ("haiku", 200_000),
1319 ("gpt-5", 400_000),
1320 ("gpt-4.1", 1_000_000),
1321 ("gpt-4o", 128_000),
1322 ("o3", 200_000),
1323 ("o4-mini", 200_000),
1324 ("gemini-2.5", 1_000_000),
1325 ("deepseek", 128_000),
1326];
1327
1328impl Config {
1329 pub fn context_window(&self, model: &str) -> Option<u64> {
1334 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1335 let mut best: Option<(usize, u64)> = None;
1336 for (key, window) in entries {
1337 if key == model {
1338 return Some(window);
1339 }
1340 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1341 best = Some((key.len(), window));
1342 }
1343 }
1344 best.map(|(_, w)| w)
1345 }
1346 lookup(
1347 model,
1348 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1349 )
1350 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1351 }
1352}
1353
1354#[derive(Debug, Clone, Deserialize, Serialize)]
1364#[serde(deny_unknown_fields, default)]
1365pub struct Daemon {
1366 pub max_concurrent_runs: usize,
1387 pub pause_for_interrupts: bool,
1403 pub max_deputies: usize,
1410 pub release_stall_minutes: u64,
1417}
1418
1419impl Default for Daemon {
1420 fn default() -> Self {
1421 Self {
1422 max_concurrent_runs: 1,
1423 pause_for_interrupts: false,
1424 max_deputies: 2,
1425 release_stall_minutes: 60,
1426 }
1427 }
1428}
1429
1430#[derive(Debug, Clone, Deserialize, Serialize)]
1442#[serde(deny_unknown_fields, default)]
1443pub struct Repos {
1444 pub roots: Vec<PathBuf>,
1448 pub auto_clone: bool,
1450 pub clone_command: Option<Vec<String>>,
1454 pub scan_ttl: u64,
1461 pub fetch_interval: u64,
1466}
1467
1468impl Default for Repos {
1469 fn default() -> Self {
1470 Self {
1471 roots: Vec::new(),
1472 auto_clone: false,
1473 clone_command: None,
1474 scan_ttl: 86_400,
1475 fetch_interval: 600,
1476 }
1477 }
1478}
1479
1480#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1496#[serde(deny_unknown_fields, default)]
1497pub struct Prompts {
1498 pub all: String,
1500 pub implement: String,
1502 pub judge: String,
1504 pub review: String,
1506 pub fix: String,
1508}
1509
1510impl Prompts {
1511 pub fn overlay(&self, node: &str) -> Option<String> {
1516 let specific = match node {
1517 "implement" => &self.implement,
1518 "judge" | "vote" | "deliberate" => &self.judge,
1519 "review" => &self.review,
1520 "fix" => &self.fix,
1521 _ => "",
1522 };
1523 let mut parts: Vec<&str> = Vec::new();
1524 for p in [self.all.trim(), specific.trim()] {
1525 if !p.is_empty() {
1526 parts.push(p);
1527 }
1528 }
1529 if parts.is_empty() {
1530 return None;
1531 }
1532 Some(parts.join("\n\n"))
1533 }
1534}
1535
1536#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1543#[serde(deny_unknown_fields, default)]
1544pub struct Notify {
1545 pub command: Vec<String>,
1548}
1549
1550#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1552#[serde(deny_unknown_fields, default)]
1553pub struct Talk {
1554 pub allow_write: bool,
1563 pub personas: Vec<PersonaSpec>,
1568 pub operator_name: Option<String>,
1572}
1573
1574pub const OPERATOR_NAME_MAX: usize = 64;
1576
1577impl Talk {
1578 pub fn operator_name(&self) -> Option<&str> {
1580 self.operator_name
1581 .as_deref()
1582 .map(str::trim)
1583 .filter(|n| !n.is_empty())
1584 }
1585}
1586
1587#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1589#[serde(deny_unknown_fields)]
1590pub struct PersonaSpec {
1591 pub id: String,
1593 #[serde(default)]
1596 pub name: String,
1597 #[serde(default)]
1600 pub prompt: String,
1601 #[serde(default, skip_serializing_if = "Option::is_none")]
1605 pub icon: Option<String>,
1606}
1607
1608#[derive(Debug, Clone)]
1610pub struct ResolvedRoles {
1611 pub implementers: Vec<AgentSpec>,
1613 pub judges: Vec<AgentSpec>,
1615 pub reviewers: Vec<AgentSpec>,
1617 pub fixer: Option<Vec<AgentSpec>>,
1622 pub conductor: AgentSpec,
1624 pub implementer_roster: Vec<AgentSpec>,
1632 pub judge_roster: Vec<AgentSpec>,
1636 pub reviewer_roster: Vec<AgentSpec>,
1638}
1639
1640fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1647 let mut out = Vec::new();
1648 for (k, v) in table {
1649 if prefix.is_empty() && k == "vars" {
1650 continue;
1651 }
1652 let path = if prefix.is_empty() {
1653 k.clone()
1654 } else {
1655 format!("{prefix}.{k}")
1656 };
1657 match v {
1658 toml::Value::Array(_) => out.push(path),
1659 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1660 _ => {}
1661 }
1662 }
1663 out
1664}
1665
1666#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1668enum ArrayMerge {
1669 Append,
1673 Replace,
1676}
1677
1678fn array_merge_policy(key: &str) -> ArrayMerge {
1717 match key {
1718 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1719 _ => ArrayMerge::Replace,
1720 }
1721}
1722
1723impl Config {
1724 pub fn load(path: &Path) -> Result<Self> {
1727 Self::load_layers(&[path.to_path_buf()])
1728 }
1729
1730 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1740 let mut ctx = teravars::system_context();
1741 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1742 ctx.insert("env", &env);
1743 if let Some(last) = paths.last()
1744 && let Some(dir) = last.parent()
1745 {
1746 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1749 .map(|s| PathBuf::from(s.trim()))
1750 .unwrap_or_else(|_| dir.to_path_buf());
1751 ctx.insert("repo", &dir.to_string_lossy());
1752 ctx.insert(
1753 "repo_name",
1754 &dir.file_name().unwrap_or_default().to_string_lossy(),
1755 );
1756 }
1757 ctx
1758 }
1759
1760 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1768 let mut engine = teravars::Engine::default();
1769 let ctx = Self::render_ctx(paths);
1770 if paths.len() > 1 {
1771 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1772 if error.downcast_ref::<ConfigFailure>().is_some() {
1773 error
1774 } else {
1775 let message = error.to_string();
1778 error
1779 .context(ConfigFailure::layers("config-merge", paths))
1780 .context(message)
1781 }
1782 })?;
1783 }
1784 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1785 .map_err(|error| {
1786 let cause = ConfigFailure::render(&error, paths);
1787 anyhow::Error::new(error).context(cause)
1788 })
1789 .with_context(|| {
1790 format!(
1791 "rendering config via teravars: {}",
1792 paths
1793 .iter()
1794 .map(|p| p.display().to_string())
1795 .collect::<Vec<_>>()
1796 .join(", ")
1797 )
1798 })?;
1799 let mut table = merged.config;
1800 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1801 table.remove("vars");
1804 let detect_agents = !table.contains_key("agents");
1808 let mut cfg: Self = toml::Value::Table(table)
1809 .try_into()
1810 .context("deserializing magi config")
1811 .context(ConfigFailure::layers("config-deserialize", paths))?;
1812 if !cfg.graph.question_routing {
1813 tracing::warn!(
1814 "[graph] question_routing is retired and ignored; task inquiries always use their chat"
1815 );
1816 }
1817 crate::persona::validate(&cfg.talk.personas)?;
1818 cfg.worktree.validate()?;
1819 cfg.release.validate()?;
1820 if let Some(name) = cfg.talk.operator_name() {
1821 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1822 bail!(
1823 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1824 );
1825 }
1826 }
1827 if detect_agents {
1828 cfg.agents = Self::autodetected().agents;
1829 }
1830 Ok(cfg)
1831 }
1832
1833 fn normalize_renamed_keys(
1841 paths: &[PathBuf],
1842 engine: &mut teravars::Engine,
1843 ctx: &teravars::Context,
1844 table: &mut toml::map::Map<String, toml::Value>,
1845 ) -> Result<()> {
1846 let both = matches!(
1847 table.get("graph"),
1848 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1849 );
1850 if !both {
1851 return Ok(());
1852 }
1853 let mut winner: Option<toml::Value> = None;
1854 for path in paths {
1855 let one = teravars::load_merged([path], engine, ctx)
1856 .map_err(|error| {
1857 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1858 anyhow::Error::new(error).context(cause)
1859 })
1860 .with_context(|| format!("rendering {}", path.display()))?;
1861 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1862 continue;
1863 };
1864 if g.contains_key("candidates") && g.contains_key("implementers") {
1865 bail!(
1866 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1867 path.display()
1868 );
1869 }
1870 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1871 winner = Some(v.clone());
1872 }
1873 }
1874 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1875 g.remove("candidates");
1876 if let Some(v) = winner {
1877 g.insert("implementers".to_owned(), v);
1878 }
1879 }
1880 Ok(())
1881 }
1882
1883 fn refuse_split_arrays(
1907 paths: &[PathBuf],
1908 engine: &mut teravars::Engine,
1909 ctx: &teravars::Context,
1910 ) -> Result<()> {
1911 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1912 for path in paths {
1913 let one = teravars::load_merged([path], engine, ctx)
1914 .map_err(|error| {
1915 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1916 anyhow::Error::new(error).context(cause)
1917 })
1918 .with_context(|| format!("rendering {}", path.display()))?;
1919 for key in array_keys(&one.config, "") {
1920 if array_merge_policy(&key) == ArrayMerge::Append {
1921 continue;
1922 }
1923 if let Some(first) = seen.get(&key) {
1924 bail!(
1925 "`{key}` is an array declared in two config layers:\n \
1926 {}\n {}\nteravars appends arrays when it merges, so \
1927 magi would run the concatenation of both - which is \
1928 not what either file says. Declare `{key}` in exactly \
1929 one of them.",
1930 first.display(),
1931 path.display()
1932 );
1933 }
1934 seen.insert(key, path.clone());
1935 }
1936 }
1937 Ok(())
1938 }
1939
1940 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1962 let mut engine = teravars::Engine::default();
1963 let ctx = Self::render_ctx(paths);
1964 let mut out = Vec::new();
1965 for path in paths {
1966 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1967 continue;
1968 };
1969 let mut cur = &one.config;
1970 let mut found = None;
1971 let parts: Vec<&str> = key.split('.').collect();
1972 for (i, part) in parts.iter().enumerate() {
1973 match cur.get(*part) {
1974 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1975 found = Some(a);
1976 break;
1977 }
1978 Some(toml::Value::Table(t)) => cur = t,
1979 _ => break,
1980 }
1981 }
1982 let Some(values) = found else { continue };
1983 let strings: Vec<String> = values
1984 .iter()
1985 .filter_map(|v| v.as_str().map(str::to_owned))
1986 .collect();
1987 if !strings.is_empty() {
1988 out.push((path.clone(), strings));
1989 }
1990 }
1991 out
1992 }
1993
1994 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
2000 let mut engine = teravars::Engine::default();
2001 let ctx = Self::render_ctx(paths);
2002 paths
2003 .iter()
2004 .map(|path| {
2005 let one = teravars::load_merged([path], &mut engine, &ctx)
2006 .map(|m| m.config)
2007 .with_context(|| format!("rendering {}", path.display()));
2008 (path.clone(), one)
2009 })
2010 .collect()
2011 }
2012
2013 pub fn describe_composed(
2023 paths: &[PathBuf],
2024 commands: &[String],
2025 key: &str,
2026 empty: &str,
2027 ) -> String {
2028 if commands.is_empty() {
2029 return empty.to_owned();
2030 }
2031 let joined = commands.join(" && ");
2032 let provenance = Self::array_provenance(paths, key);
2033 if provenance.len() <= 1 {
2034 return joined;
2035 }
2036 let mut out = joined;
2037 for (path, cmds) in &provenance {
2038 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2039 }
2040 out
2041 }
2042
2043 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2050 #[cfg(test)]
2051 crate::web::request_cost::discovery();
2052 if let Some(p) = explicit {
2053 let paths = vec![p.to_path_buf()];
2054 return Ok((Self::load_layers(&paths)?, paths));
2055 }
2056 let paths = Self::layers_checked(repo)?;
2057 if paths.is_empty() {
2058 return Ok((Self::autodetected(), paths));
2059 }
2060 Ok((Self::load_layers(&paths)?, paths))
2061 }
2062
2063 pub async fn discover_fetched(
2066 repo: &Path,
2067 explicit: Option<&Path>,
2068 ) -> Result<(Self, Vec<PathBuf>)> {
2069 if explicit.is_none() && is_git_worktree(repo) {
2070 let (remote, cfg_base) = probe_remote_base(repo);
2074 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2075 .await
2076 .with_context(|| ConfigFailure {
2077 stage: "config-base",
2078 target: remote.clone(),
2079 })?;
2080 let out = crate::git::fetch(repo, &remote, &base)
2081 .await
2082 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2083 .with_context(|| ConfigFailure {
2084 stage: "config-fetch",
2085 target: format!("{remote}/{base}"),
2086 })?;
2087 if !out.ok() {
2088 return Err(anyhow::anyhow!(
2089 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2090 out.stderr.lines().next().unwrap_or("").trim()
2091 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2092 }
2093 if cfg_base.is_none() {
2094 crate::git::ensure_remote_head(repo, &remote, &base).await;
2095 }
2096 }
2097 Self::discover(repo, explicit).map_err(|error| {
2098 if error.downcast_ref::<ConfigFailure>().is_some() {
2099 error
2100 } else {
2101 error.context(ConfigFailure {
2102 stage: "config-load",
2103 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2104 })
2105 }
2106 })
2107 }
2108
2109 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2111 if !is_git_worktree(repo) {
2112 return Ok(Self::layers(repo));
2113 }
2114 let mut paths: Vec<PathBuf> = Self::machine_layer()
2115 .into_iter()
2116 .filter(|p| p.is_file())
2117 .collect();
2118 paths.extend(Self::repo_layers(repo)?);
2119 Ok(paths)
2120 }
2121
2122 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2124 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2125 if let Some(root) = cached {
2126 let relative = path.strip_prefix(root).unwrap_or(path);
2127 let reference = resolve_remote_base(repo)
2128 .map(|(remote, base)| format!("{remote}/{base}"))
2129 .unwrap_or_else(|_| "remote base".to_owned());
2130 format!(
2131 "{} at {reference} (including its includes)",
2132 repo.join(relative).display()
2133 )
2134 } else {
2135 format!("{} (including its includes)", path.display())
2136 }
2137 }
2138
2139 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2142 if !is_git_worktree(repo) {
2143 return Ok([
2144 repo.join(".magi").join("config.toml"),
2145 repo.join("magi.toml"),
2146 ]
2147 .into_iter()
2148 .filter(|p| p.is_file())
2149 .collect());
2150 }
2151 remote_layers(repo)
2152 }
2153
2154 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2174
2175 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2180 let mut paths = Vec::new();
2181 paths.extend(Self::machine_layer());
2182 paths.push(repo.join(".magi").join("config.toml"));
2183 paths.push(repo.join("magi.toml"));
2184 paths.retain(|p| p.is_file());
2185 paths
2186 }
2187
2188 #[cfg(test)]
2195 pub(crate) fn machine_layer() -> Option<PathBuf> {
2196 std::env::var(Self::CONFIG_DIR_ENV)
2197 .ok()
2198 .filter(|dir| !dir.trim().is_empty())
2199 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2200 }
2201
2202 #[cfg(not(test))]
2204 pub(crate) fn machine_layer() -> Option<PathBuf> {
2205 match std::env::var(Self::CONFIG_DIR_ENV) {
2206 Ok(dir) if dir.trim().is_empty() => None,
2208 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2209 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2210 }
2211 }
2212
2213 pub fn autodetected() -> Self {
2215 let mut cfg = Self::default();
2216 for (kind, id, model) in [
2217 (AgentKind::Claude, "opus", Some("opus")),
2218 (AgentKind::Claude, "sonnet", Some("sonnet")),
2219 (AgentKind::Antigravity, "antigravity", None),
2220 (AgentKind::Opencode, "opencode", None),
2221 (AgentKind::Codex, "codex", None),
2222 (AgentKind::Omp, "omp", None),
2223 ] {
2224 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2225 cfg.agents.push(AgentSpec {
2226 id: id.to_owned(),
2227 kind,
2228 model: model.map(str::to_owned),
2229 command: Vec::new(),
2230 extra_args: Vec::new(),
2231 env: BTreeMap::new(),
2232 prompt_delivery: None,
2233 max_turn_secs: None,
2234 });
2235 }
2236 }
2237 cfg
2238 }
2239
2240 pub fn cache_dir(&self) -> Option<PathBuf> {
2243 self.verify.cache_dir()
2244 }
2245
2246 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2248 self.agents
2249 .iter()
2250 .find(|a| a.id == id)
2251 .with_context(|| format!("no agent with id `{id}` in the roster"))
2252 }
2253
2254 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2261 let mut out = Vec::with_capacity(count);
2262 for i in 0..count {
2263 let spec = if ids.is_empty() {
2264 self.agents[(i + offset) % self.agents.len()].clone()
2265 } else {
2266 self.agent(&ids[i % ids.len()])?.clone()
2267 };
2268 out.push(spec);
2269 }
2270 Ok(out)
2271 }
2272
2273 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2280 if ids.is_empty() {
2281 Ok(self.agents.clone())
2282 } else {
2283 ids.iter().map(|id| self.agent(id).cloned()).collect()
2284 }
2285 }
2286
2287 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2294 if self.agents.is_empty() {
2295 bail!(
2296 "agent roster is empty: no agent CLI found on PATH and no \
2297 [[agents]] in the config. Run `magi init` to write a starter \
2298 magi.toml."
2299 );
2300 }
2301 let pinned = self
2302 .graph
2303 .selected_implementer
2304 .as_ref()
2305 .map(|id| self.agent(id).cloned())
2306 .transpose()?;
2307 Ok(ResolvedRoles {
2308 implementers: match &pinned {
2309 Some(agent) => vec![agent.clone()],
2310 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2311 },
2312 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2313 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2314 fixer: match self.roles.fixer.as_ref() {
2315 Some(choice) => Some(crate::agent::pick_chain(
2318 &self.agents,
2319 Some(choice),
2320 &|_| true,
2321 "fixer",
2322 )?),
2323 None => None,
2324 },
2325 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2330 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2331 Some(ids) if !ids.is_empty() => ids
2334 .iter()
2335 .find_map(|id| self.agent(id).ok())
2336 .cloned()
2337 .with_context(|| {
2338 format!("[roles] conductor names no agent in the roster: {ids:?}")
2339 })?,
2340 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2345 .unwrap_or_else(|_| self.agents[0].clone()),
2346 },
2347 implementer_roster: match pinned {
2348 Some(agent) => vec![agent],
2349 None => self.full_roster(&self.roles.implementers)?,
2350 },
2351 judge_roster: self.full_roster(&self.roles.judges)?,
2352 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2353 })
2354 }
2355
2356 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2378 if self.agents.is_empty() {
2379 bail!(
2380 "agent roster is empty: no agent CLI found on PATH and no \
2381 [[agents]] in the config. Run `magi init` to write a starter \
2382 magi.toml."
2383 );
2384 }
2385 if !self.roles.advisors.is_empty() {
2386 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2387 }
2388 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2389 }
2390
2391 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2395 if self.roles.advisors.is_empty() {
2396 self.full_roster(&self.roles.judges)
2397 } else {
2398 self.full_roster(&self.roles.advisors)
2399 }
2400 }
2401
2402 pub fn shell(&self) -> Vec<String> {
2404 if let Some(s) = &self.verify.shell {
2405 return s.clone();
2406 }
2407 if which("sh") {
2408 vec!["sh".to_owned(), "-c".to_owned()]
2409 } else {
2410 vec!["cmd".to_owned(), "/C".to_owned()]
2411 }
2412 }
2413
2414 pub fn starter_toml() -> String {
2416 let detected = Self::autodetected();
2417 let mut s = String::from(
2418 "# magi — blind multi-agent implementation competition.\n\
2419 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2420 # -> blind judging -> deliberation -> private final vote\n\
2421 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2422 #\n\
2423 # Rendered by teravars: a `[vars]` table, env\n\
2424 # and system lookups, and `include = [...]` all work. Tera\n\
2425 # braces are live everywhere in this file, but comments are\n\
2426 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2427 # may quote `{{ ... }}` freely.\n\
2428 #\n\
2429 # Layers deep-merge in increasing\n\
2430 # precedence, so the roster can live once per machine in\n\
2431 # <config_dir>/magi/config.toml and each repo only states its own\n\
2432 # gate:\n\
2433 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2434 [vars]\n\
2435 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2436 # Single quotes inside the braces: teravars renders the raw file\n\
2437 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2438 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2439 );
2440 if detected.agents.is_empty() {
2441 s.push_str(
2442 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2443 # kind = claude | opencode | antigravity | codex | command\n\
2444 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2445 );
2446 } else {
2447 for a in &detected.agents {
2448 s.push_str("[[agents]]\n");
2449 s.push_str(&format!("id = {:?}\n", a.id));
2450 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2451 if let Some(m) = &a.model {
2452 s.push_str(&format!("model = {m:?}\n"));
2453 }
2454 s.push('\n');
2455 }
2456 }
2457 s.push_str(
2458 "# Leave a role list empty to rotate through the roster.\n\
2459 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2460 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2461 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2462 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2463 [roles]\n\
2464 implementers = []\n\
2465 judges = []\n\
2466 reviewers = []\n\
2467 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2468 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2469 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2470 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2471 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2472 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2473 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2474 [graph]\n\
2475 # Gate GitHub prose; secret redaction is always enabled.\n\
2476 github_text_guard = true\n\
2477 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2478 github_language = \"en\"\n\
2479 implementers = 3\n\
2480 judges = 3\n\
2481 deliberate_rounds = 1\n\
2482 reviewers = 3\n\
2483 review_rounds = 6\n\
2484 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2485 gate_fix_rounds = 1\n\
2486 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2487 rerun_flaky_checks = true\n\
2488 # Port the strengths judges named in the losing candidates onto the\n\
2489 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2490 graft_runner_up = true\n\
2491 max_parallel = 4\n\
2492 language = \"en\"\n\
2493 # One CLI conversation per seat: judges keep their own argument\n\
2494 # across deliberation, the fixer keeps its implementation context.\n\
2495 sessions = true\n\
2496 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2497 # the final gate inherit this value for compatibility.\n\
2498 timeout_review = 1200\n\
2499 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2500 # verification independent if timeout_review changes later.\n\
2501 # timeout_verify = 1200\n\
2502 # Longest a seat waits for the shared build cache before it is\n\
2503 # spawned. Never counted against an agent's own timeout; expiry\n\
2504 # holds the run (resumable) instead of failing the agent.\n\
2505 # timeout_resource_wait = 1800\n\n\
2506 # What the chat calls you (persona address and the Chat's turn label).\n\
2507 # [talk]\n\
2508 # operator_name = \"Commander\"\n\n\
2509 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2510 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2511 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2512 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2513 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2514 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2515 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2516 # [[talk.personas]]\n\
2517 # id = \"gendo\"\n\
2518 # name = \"Gendo Ikari\"\n\
2519 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2520 # icon = \"~/pictures/gendo.png\"\n\n\
2521 [verify]\n\
2522 # Run once per review round in the winner's worktree; failures are\n\
2523 # fed back to the fixer.\n\
2524 e2e = []\n\
2525 # Final gate. Every command must exit 0 before a merge.\n\
2526 gate = []\n\
2527 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2528 # before the gate; whatever they change becomes one commit. A failing\n\
2529 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2530 # gate (timeout_verify). Keep it light and idempotent.\n\
2531 # pre_gate = []\n\n\
2532 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2533 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2534 # before any agent or verify command touches it. `copy` reads from the\n\
2535 # primary checkout and never overwrites; `optional` skips a missing\n\
2536 # source. `run` goes through the shell with the worktree as cwd and\n\
2537 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2538 # the verify timeout). Setup must not edit tracked files, and what it\n\
2539 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2540 # layer only.\n\
2541 # [worktree]\n\
2542 # setup = [\n\
2543 # { copy = \".env.example -> .env\" },\n\
2544 # { copy = \".env.local\", optional = true },\n\
2545 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2546 # ]\n\
2547 # pre_clean = [] # Repeatable cleanup before owned clean -fdx.\n\n\
2548 [merge]\n\
2549 # none | local | pr\n\
2550 mode = \"none\"\n\
2551 # expected (default) | none. Set none only in repository config without CI.\n\
2552 # Ignores all check statuses; reviews and approval still apply.\n\
2553 # ci = \"expected\"\n\
2554 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2555 [update]\n\
2556 # off | notify | install — checked in the background, throttled.\n\
2557 mode = \"notify\"\n\
2558 # interval = \"24h\"\n\n\
2559 # Opt-in: magi web updates and restarts only after runs/chats finish.\n\
2560 # auto_restart = false\n\
2561 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2562 # Standalone magi serve cannot restart. Busy work waits indefinitely.\n\
2563 # Failed tags are skipped until process restart or a different tag.\n\
2564 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2565 [daemon]\n\
2566 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2567 # no new commit and no check changing state before `magi serve`\n\
2568 # notices and asks you. A failed check is rerun once on its own;\n\
2569 # still red after that escalates at once. 0 turns the watcher off.\n\
2570 # release_stall_minutes = 60\n\n\
2571 [release]\n\
2572 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2573 # Actions never run (private, no minutes): the release pull request\n\
2574 # does not wait for CI, you approve the merge in magi, and then\n\
2575 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2576 # runs `commands` from a clean checkout of the merge commit. A\n\
2577 # failure holds the release with a notice; it is never retried blind.\n\
2578 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2579 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2580 # mode = \"actions\"\n\
2581 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2582 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2583 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2584 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2585 # timeout_minutes = 30\n\
2586 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2587 # The first entry is the version of record and must be the file the\n\
2588 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2589 # rewritten to the same version. Paths are relative to the repository\n\
2590 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2591 # is not touched.\n\
2592 # version_files = [\n\
2593 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2594 # { path = \"package.json\", kind = \"json\" },\n\
2595 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2596 # ]\n",
2597 );
2598 s
2599 }
2600}
2601
2602pub fn which(program: &str) -> bool {
2604 find_program(program).is_some()
2605}
2606
2607pub fn find_program(program: &str) -> Option<PathBuf> {
2616 find_program_on(program, &std::env::var_os("PATH")?)
2617}
2618
2619pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2622 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2623 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2624}
2625
2626fn find_program_in(
2627 program: &str,
2628 paths: &std::ffi::OsStr,
2629 pathext: Option<&str>,
2630) -> Option<PathBuf> {
2631 let p = Path::new(program);
2632 if p.components().count() > 1 {
2633 return p.is_file().then(|| p.to_path_buf());
2634 }
2635 std::env::split_paths(paths).find_map(|dir| match pathext {
2636 Some(exts) => {
2637 let bare = dir.join(program);
2638 if p.extension().is_some() && bare.is_file() {
2639 return Some(bare);
2640 }
2641 exts.split(';')
2642 .filter(|e| !e.is_empty())
2643 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2644 .find(|c| c.is_file())
2645 }
2646 None => Some(dir.join(program)).filter(|c| c.is_file()),
2647 })
2648}
2649
2650const REPO_MARKER: &str = ".magi-repo";
2652
2653fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2654 use crate::proc::Quiet as _;
2655 #[cfg(test)]
2656 crate::web::request_cost::git();
2657 let out = std::process::Command::new("git")
2658 .args(args)
2659 .quiet()
2660 .current_dir(repo)
2661 .stdin(std::process::Stdio::null())
2662 .output()
2663 .ok()?;
2664 out.status
2665 .success()
2666 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2667}
2668
2669fn is_git_worktree(repo: &Path) -> bool {
2672 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2673}
2674
2675#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2678pub enum OwnerHold {
2679 LandApproval,
2681 HoldContestedMerge,
2683}
2684
2685impl OwnerHold {
2686 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2688
2689 pub fn key(self) -> &'static str {
2691 match self {
2692 Self::LandApproval => "land_approval",
2693 Self::HoldContestedMerge => "hold_contested_merge",
2694 }
2695 }
2696
2697 pub fn base_value(self, graph: &Graph) -> bool {
2699 match self {
2700 Self::LandApproval => graph.land_approval,
2701 Self::HoldContestedMerge => graph.hold_contested_merge,
2702 }
2703 }
2704}
2705
2706pub async fn branch_owner_holds(
2709 repo: &Path,
2710 head: &str,
2711) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2712 let mut holds = Vec::new();
2713 let mut diagnostics = Vec::new();
2714 if let Err(error) =
2717 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2718 {
2719 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2720 return (holds, diagnostics);
2721 }
2722 for file in ["magi.toml", ".magi/config.toml"] {
2723 let object = format!("{head}:{file}");
2724 let text = match crate::git::git(repo, &["show", &object]).await {
2725 Ok(text) => text,
2726 Err(error) => {
2727 let error = format!("{error:#}");
2729 if !error.contains("does not exist in")
2730 && !error.contains("exists on disk, but not in")
2731 {
2732 diagnostics.push(format!(
2733 "cannot read reviewed branch {file} at {head}: {error}"
2734 ));
2735 }
2736 continue;
2737 }
2738 };
2739 let value = match toml::from_str::<toml::Value>(&text) {
2740 Ok(value) => value,
2741 Err(error) => {
2742 diagnostics.push(format!(
2743 "cannot parse reviewed branch {file} at {head}: {error}"
2744 ));
2745 continue;
2746 }
2747 };
2748 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2749 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2750 }
2751 for hold in OwnerHold::ALL {
2752 if value
2753 .get("graph")
2754 .and_then(|g| g.get(hold.key()))
2755 .and_then(toml::Value::as_bool)
2756 == Some(true)
2757 {
2758 holds.push((hold, file.to_owned()));
2759 }
2760 }
2761 }
2762 (holds, diagnostics)
2763}
2764
2765#[derive(Deserialize, Default)]
2766struct ProbeMerge {
2767 base: Option<String>,
2768 remote: Option<String>,
2769}
2770
2771#[derive(Deserialize, Default)]
2772struct Probe {
2773 merge: Option<ProbeMerge>,
2774}
2775
2776fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2782 if !path.is_file() {
2783 return None;
2784 }
2785 let paths = [path.to_path_buf()];
2786 let mut engine = teravars::Engine::default();
2787 let mut ctx = Config::render_ctx(&paths);
2788 ctx.insert("repo", &repo.to_string_lossy());
2791 ctx.insert(
2792 "repo_name",
2793 &repo.file_name().unwrap_or_default().to_string_lossy(),
2794 );
2795 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2796 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2797 {
2798 return probe.merge;
2799 }
2800 let text = std::fs::read_to_string(path).ok()?;
2801 toml::from_str::<Probe>(&text).ok()?.merge
2802}
2803
2804fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2806 let mut remote = None;
2807 let mut base = None;
2808 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2809 sources.push(repo.join("magi.toml"));
2810 sources.push(repo.join(".magi").join("config.toml"));
2811 for path in sources {
2812 if let Some(m) = probe_merge(&path, repo) {
2813 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2814 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2815 }
2816 }
2817 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2818}
2819
2820fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2822 let (remote, base) = probe_remote_base(repo);
2823 let base = match base {
2824 Some(b) => b,
2825 None => {
2826 let head = format!("refs/remotes/{remote}/HEAD");
2827 git_out(repo, &["symbolic-ref", "--quiet", &head])
2828 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2829 .with_context(|| {
2830 format!(
2831 "cannot tell which branch of `{remote}` holds magi.toml: \
2832 set [merge] base, or run `git remote set-head {remote} -a`"
2833 )
2834 })?
2835 }
2836 };
2837 Ok((remote, base))
2838}
2839
2840fn fnv_hex(text: &str) -> String {
2841 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2842 for b in text.bytes() {
2843 hash ^= u64::from(b);
2844 hash = hash.wrapping_mul(0x0100_0000_01b3);
2845 }
2846 format!("{hash:016x}")
2847}
2848
2849fn declares_include(text: &str) -> bool {
2855 match toml::from_str::<toml::Table>(text) {
2856 Ok(table) => {
2857 table.contains_key("include")
2858 || table
2859 .get("teravars")
2860 .and_then(toml::Value::as_table)
2861 .is_some_and(|t| t.contains_key("include"))
2862 }
2863 Err(_) => text.contains("include"),
2864 }
2865}
2866
2867fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2870 use crate::proc::Quiet as _;
2871 #[cfg(test)]
2872 crate::web::request_cost::git();
2873 let mut archive = std::process::Command::new("git")
2874 .args(["archive", "--format=tar", sha])
2875 .quiet()
2876 .current_dir(repo)
2877 .stdin(std::process::Stdio::null())
2878 .stdout(std::process::Stdio::piped())
2879 .stderr(std::process::Stdio::null())
2880 .spawn()
2881 .context("running git archive")?;
2882 let tar = std::process::Command::new("tar")
2883 .arg("-x")
2884 .arg("-C")
2885 .arg(dest)
2886 .quiet()
2887 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2888 .output()
2889 .context("running tar")?;
2890 let status = archive.wait().context("waiting for git archive")?;
2891 if !status.success() || !tar.status.success() {
2892 bail!(
2893 "cannot unpack {sha} for the config's includes: {}",
2894 String::from_utf8_lossy(&tar.stderr).trim()
2895 );
2896 }
2897 Ok(())
2898}
2899
2900fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2903 let (remote, base) = resolve_remote_base(repo)?;
2904 let tracking = format!("refs/remotes/{remote}/{base}");
2905 let spec = format!("{tracking}^{{commit}}");
2906 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2907 .map(|s| s.trim().to_owned())
2908 .filter(|s| !s.is_empty())
2909 .with_context(|| {
2910 format!(
2911 "`{remote}/{base}` does not exist in this checkout; fetch it \
2912 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2913 a possibly stale local magi.toml instead"
2914 )
2915 })?;
2916 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2917 let rels = [".magi/config.toml", "magi.toml"];
2918 let mut texts: Vec<(&str, String)> = Vec::new();
2919 for rel in rels {
2920 let object = format!("{sha}:{rel}");
2921 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2922 continue;
2923 }
2924 let Some(text) = git_out(repo, &["show", &object]) else {
2925 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2926 };
2927 texts.push((rel, text));
2928 }
2929 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2930 let build = |root: &Path| -> Result<PathBuf> {
2934 let final_dir = root.join(&key);
2935 if !final_dir.is_dir() {
2936 std::fs::create_dir_all(root)?;
2937 let tmp = root.join(format!(
2938 "{key}.tmp-{}-{}",
2939 std::process::id(),
2940 std::time::SystemTime::now()
2941 .duration_since(std::time::UNIX_EPOCH)
2942 .map(|d| d.as_nanos())
2943 .unwrap_or_default()
2944 ));
2945 let filled = (|| -> Result<()> {
2946 std::fs::create_dir_all(&tmp)?;
2947 if wants_tree {
2948 extract_tree(repo, &sha, &tmp)?;
2949 }
2950 for (rel, text) in &texts {
2951 let file = tmp.join(rel);
2952 let parent = file.parent().unwrap_or(&tmp);
2953 std::fs::create_dir_all(parent)?;
2954 std::fs::write(&file, text)?;
2955 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2956 }
2957 Ok(())
2958 })();
2959 if let Err(e) = filled {
2960 let _ = std::fs::remove_dir_all(&tmp);
2961 return Err(e);
2962 }
2963 if std::fs::rename(&tmp, &final_dir).is_err() {
2964 let _ = std::fs::remove_dir_all(&tmp);
2966 if !final_dir.is_dir() {
2967 bail!("cannot place {}", final_dir.display());
2968 }
2969 }
2970 }
2971 Ok(final_dir)
2972 };
2973 let common = git_out(
2974 repo,
2975 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2976 )
2977 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2978 let dir = match common.map(|c| build(&c)) {
2979 Some(Ok(d)) => d,
2980 _ => build(&std::env::temp_dir().join("magi-config"))
2981 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2982 };
2983 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2984}
2985
2986#[cfg(test)]
2987mod tests {
2988 #[test]
2989 fn run_records_with_the_retired_editing_network_key_still_load() {
2990 for value in ["enabled", "restricted"] {
2992 let mut graph = serde_json::to_value(Graph::default()).unwrap();
2993 graph["editing_network"] = serde_json::json!(value);
2994 let back: Graph = serde_json::from_value(graph).unwrap();
2995 assert!(
2996 serde_json::to_value(&back)
2997 .unwrap()
2998 .get("editing_network")
2999 .is_none()
3000 );
3001 let from_toml: Graph = toml::from_str(&format!("editing_network = {value:?}")).unwrap();
3002 assert!(
3003 !toml::to_string(&from_toml)
3004 .unwrap()
3005 .contains("editing_network")
3006 );
3007 }
3008 }
3009
3010 #[test]
3011 fn coordination_defaults_off_and_validates_rendered_layer_values() {
3012 let dir = tempfile::tempdir().unwrap();
3013 let machine = dir.path().join("machine.toml");
3014 let repo = dir.path().join("repo.toml");
3015 std::fs::write(&machine, "").unwrap();
3016 assert!(Config::default().coordination.is_none());
3017 assert!(Config::load(&machine).unwrap().coordination.is_none());
3018 std::fs::write(
3019 &machine,
3020 r#"
3021[vars]
3022contract = "updater.contract"
3023[coordination]
3024contract_file = "{{ vars.contract }}"
3025contract_token = "protocol-v1"
3026lock_file = "updater.lock"
3027"#,
3028 )
3029 .unwrap();
3030 let cfg = Config::load(&machine).unwrap();
3031 let policy = cfg.coordination.unwrap();
3032 assert_eq!(policy.contract_file, "updater.contract");
3033 assert_eq!(policy.contract_token, "protocol-v1");
3034 assert_eq!(policy.lock_file, "updater.lock");
3035 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
3036 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
3037 let policy = cfg.coordination.unwrap();
3038 assert_eq!(policy.contract_file, "updater.contract");
3039 assert_eq!(policy.lock_file, "repository.lock");
3040 std::fs::write(
3041 &repo,
3042 r#"
3043[vars]
3044bad = "../escape"
3045[coordination]
3046lock_file = "{{ vars.bad }}"
3047"#,
3048 )
3049 .unwrap();
3050 let error = Config::load_layers(&[machine, repo]).unwrap_err();
3051 assert!(format!("{error:#}").contains("coordination.lock_file"));
3052 }
3053
3054 #[test]
3055 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
3056 let dir = tempfile::tempdir().unwrap();
3057 let path = dir.path().join("config.toml");
3058 let valid = toml::toml! {
3059 [coordination]
3060 contract_file = "updater.contract"
3061 contract_token = "protocol-v1"
3062 lock_file = "updater.lock"
3063 };
3064 for key in ["contract_file", "lock_file"] {
3065 for bad in [
3066 "",
3067 " ",
3068 " file",
3069 "file ",
3070 "\tfile",
3071 "file\t",
3072 ".",
3073 "..",
3074 "file..name",
3075 "../escape",
3076 "a/b",
3077 "a\\b",
3078 "/absolute",
3079 "C:drive",
3080 "C:\\absolute",
3081 "nul\0name",
3082 ] {
3083 let mut table = valid.clone();
3084 table["coordination"][key] = bad.into();
3085 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3086 let error = Config::load(&path).unwrap_err();
3087 assert!(
3088 format!("{error:#}").contains(&format!("coordination.{key}")),
3089 "{bad:?}: {error:#}"
3090 );
3091 }
3092 }
3093 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
3094 let mut table = valid.clone();
3095 table["coordination"]["contract_token"] = bad.into();
3096 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3097 let error = Config::load(&path).unwrap_err();
3098 assert!(
3099 format!("{error:#}").contains("coordination.contract_token"),
3100 "{error:#}"
3101 );
3102 }
3103 for key in ["contract_file", "contract_token", "lock_file"] {
3104 let mut table = valid.clone();
3105 table["coordination"].as_table_mut().unwrap().remove(key);
3106 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3107 let error = Config::load(&path).unwrap_err();
3108 assert!(
3109 format!("{error:#}").contains(&format!("coordination.{key}")),
3110 "{error:#}"
3111 );
3112 }
3113 let mut table = valid;
3114 table["coordination"]
3115 .as_table_mut()
3116 .unwrap()
3117 .insert("typo".into(), "value".into());
3118 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3119 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
3120 }
3121
3122 #[test]
3123 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
3124 let mut cfg = Config::default();
3125 assert_eq!(
3126 cfg.context_window("claude-sonnet-4-5-20250929"),
3127 Some(200_000)
3128 );
3129 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
3130 assert_eq!(cfg.context_window("mystery-model"), None);
3131 cfg.context_windows
3132 .insert("claude-sonnet-4-5".into(), 1_000_000);
3133 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
3134 cfg.context_windows.insert("mystery".into(), 32_768);
3135 assert_eq!(
3137 cfg.context_window("claude-sonnet-4-5-20250929"),
3138 Some(1_000_000)
3139 );
3140 cfg.context_windows
3142 .insert("claude-sonnet-4-5-20250929".into(), 7);
3143 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
3144 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
3145 }
3146
3147 use super::*;
3148
3149 #[test]
3152 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
3153 let dir = tempfile::tempdir().unwrap();
3154 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
3155 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
3156 let paths = dir.path().as_os_str();
3157 assert_eq!(
3158 find_program_in("codex", paths, Some(".EXE;.CMD")),
3159 Some(dir.path().join("codex.cmd"))
3160 );
3161 assert_eq!(
3162 find_program_in("codex", paths, None),
3163 Some(dir.path().join("codex"))
3164 );
3165 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3166 }
3167
3168 fn spec(id: &str) -> AgentSpec {
3169 AgentSpec {
3170 id: id.to_owned(),
3171 kind: AgentKind::Command,
3172 model: None,
3173 command: vec!["true".to_owned()],
3174 extra_args: Vec::new(),
3175 env: BTreeMap::new(),
3176 prompt_delivery: None,
3177 max_turn_secs: None,
3178 }
3179 }
3180
3181 #[test]
3182 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
3183 let default: Merge = toml::from_str("").unwrap();
3184 assert_eq!(default.ci, MergeCi::Expected);
3185 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
3186 assert_eq!(
3187 config.merge.ci.expectation(),
3188 crate::land::CiExpectation::Absent
3189 );
3190 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
3191 assert!(Config::starter_toml().contains("# ci = \"expected\""));
3192 }
3193
3194 #[test]
3195 fn github_text_guard_defaults_on_and_can_be_disabled() {
3196 let default: Graph = toml::from_str("").unwrap();
3197 assert!(default.github_text_guard);
3198 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3199 assert!(!disabled.github_text_guard);
3200 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3201 assert!(!config.graph.github_text_guard);
3202 assert!(Config::starter_toml().contains("github_text_guard = true"));
3203 }
3204
3205 #[test]
3206 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3207 assert!(Graph::default().rerun_flaky_checks);
3208 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3209 assert!(!off.rerun_flaky_checks);
3210 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3211 }
3212
3213 #[test]
3214 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3215 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3220 assert_eq!(g.timeout_verify, None);
3221 assert_eq!(g.verify_timeout(), 3600);
3222 }
3223
3224 #[test]
3225 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3226 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3231 assert_eq!(g.timeout_review, 45);
3232 assert_eq!(
3233 g.verify_timeout(),
3234 45,
3235 "an omitted legacy value follows review"
3236 );
3237 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3238 .expect("parse explicit override");
3239 assert_eq!(explicit.verify_timeout(), 1200);
3240 }
3241
3242 #[test]
3243 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3244 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3245 assert_eq!(g.implementers, 4);
3246 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3247 assert_eq!(g.implementers, 5);
3248 }
3249
3250 fn layered(lower: &str, upper: &str) -> Result<Config> {
3251 let dir = tempfile::tempdir().unwrap();
3252 let a = dir.path().join("a.toml");
3253 let b = dir.path().join("b.toml");
3254 std::fs::write(&a, lower).unwrap();
3255 std::fs::write(&b, upper).unwrap();
3256 Config::load_layers(&[a, b])
3257 }
3258
3259 #[test]
3260 fn graph_implementers_higher_layer_wins_across_spellings() {
3261 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3262 assert_eq!(c.graph.implementers, 5);
3263 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3264 assert_eq!(c.graph.implementers, 5);
3265 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3266 assert_eq!(c.graph.implementers, 2);
3267 }
3268
3269 #[test]
3270 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3271 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3272 .unwrap_err()
3273 .to_string();
3274 assert!(
3275 err.contains("candidates") && err.contains("implementers"),
3276 "{err}"
3277 );
3278 assert!(err.contains("b.toml"), "{err}");
3279 }
3280
3281 #[test]
3282 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3283 let g: Graph =
3287 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3288 .expect("an old-shaped [graph] table must still parse");
3289 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3290 assert!(
3291 !g.e2e_every_round,
3292 "off by default, same as before this field existed"
3293 );
3294 }
3295
3296 #[test]
3297 fn empty_roles_rotate_judges_off_their_own_candidate() {
3298 let cfg = Config {
3301 agents: vec![spec("a"), spec("b"), spec("c")],
3302 graph: Graph {
3303 implementers: 3,
3304 ..Graph::default()
3305 },
3306 ..Config::default()
3307 };
3308 let roles = cfg.resolve_roles().unwrap();
3309 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3310 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3311 assert_eq!(impls, ["a", "b", "c"]);
3312 assert_eq!(judges, ["b", "c", "a"]);
3313 for (i, j) in judges.iter().enumerate() {
3314 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3315 }
3316 }
3317
3318 #[test]
3319 fn single_agent_roster_fills_every_seat() {
3320 let cfg = Config {
3321 agents: vec![spec("solo")],
3322 graph: Graph {
3323 implementers: 3,
3324 ..Graph::default()
3325 },
3326 ..Config::default()
3327 };
3328 let roles = cfg.resolve_roles().unwrap();
3329 assert_eq!(roles.implementers.len(), 3);
3330 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3331 }
3332
3333 #[test]
3334 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3335 let cfg = Config {
3340 agents: vec![spec("a"), spec("b"), spec("c")],
3341 graph: Graph {
3342 implementers: 1,
3343 ..Graph::default()
3344 },
3345 ..Config::default()
3346 };
3347 let roles = cfg.resolve_roles().unwrap();
3348 assert_eq!(roles.implementers.len(), 1);
3349 let roster: Vec<&str> = roles
3350 .implementer_roster
3351 .iter()
3352 .map(|a| a.id.as_str())
3353 .collect();
3354 assert_eq!(roster, ["a", "b", "c"]);
3355 }
3356
3357 #[test]
3358 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3359 let cfg = Config {
3360 agents: vec![spec("a"), spec("b"), spec("c")],
3361 roles: Roles {
3362 implementers: vec!["c".to_owned(), "a".to_owned()],
3363 ..Roles::default()
3364 },
3365 graph: Graph {
3366 implementers: 1,
3367 ..Graph::default()
3368 },
3369 ..Config::default()
3370 };
3371 let roles = cfg.resolve_roles().unwrap();
3372 assert_eq!(roles.implementers.len(), 1);
3374 assert_eq!(roles.implementers[0].id, "c");
3375 let roster: Vec<&str> = roles
3376 .implementer_roster
3377 .iter()
3378 .map(|a| a.id.as_str())
3379 .collect();
3380 assert_eq!(roster, ["c", "a"]);
3381 }
3382
3383 #[test]
3384 fn explicit_roles_win() {
3385 let cfg = Config {
3386 agents: vec![spec("a"), spec("b")],
3387 roles: Roles {
3388 implementers: vec!["b".to_owned()],
3389 judges: vec!["a".to_owned()],
3390 reviewers: Vec::new(),
3391 fixer: Some("a".into()),
3392 ..Roles::default()
3393 },
3394 ..Config::default()
3395 };
3396 let roles = cfg.resolve_roles().unwrap();
3397 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3398 assert!(roles.judges.iter().all(|a| a.id == "a"));
3399 let fixer = roles.fixer.unwrap();
3400 assert_eq!(fixer.len(), 1);
3401 assert_eq!(fixer[0].id, "a");
3402 assert_eq!(roles.conductor.id, "a");
3403 }
3404
3405 #[test]
3406 fn fixer_takes_a_string_or_an_ordered_chain() {
3407 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3408 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3409 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3410 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3411
3412 let resolve = |fixer: Option<AgentChoice>| {
3413 Config {
3414 agents: vec![spec("a"), spec("b"), spec("c")],
3415 roles: Roles {
3416 fixer,
3417 ..Roles::default()
3418 },
3419 ..Config::default()
3420 }
3421 .resolve_roles()
3422 };
3423 let ids = |r: &ResolvedRoles| -> Vec<String> {
3424 r.fixer
3425 .as_ref()
3426 .unwrap()
3427 .iter()
3428 .map(|s| s.id.clone())
3429 .collect()
3430 };
3431 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3433 assert!(resolve(None).unwrap().fixer.is_none());
3434 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3436 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3437 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3439 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3440 }
3441
3442 #[test]
3443 fn unknown_agent_id_is_an_error() {
3444 let cfg = Config {
3445 agents: vec![spec("a")],
3446 roles: Roles {
3447 judges: vec!["nope".to_owned()],
3448 ..Roles::default()
3449 },
3450 ..Config::default()
3451 };
3452 assert!(cfg.resolve_roles().is_err());
3453 }
3454
3455 #[test]
3456 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3457 let mut cfg = Config {
3458 agents: vec![spec("a"), spec("b")],
3459 ..Config::default()
3460 };
3461 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3462
3463 cfg.roles.conductor = Some("b".into());
3464 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3465
3466 cfg.roles.conductor = Some("missing".into());
3467 assert!(cfg.resolve_roles().is_err());
3468 }
3469
3470 #[test]
3471 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3472 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3473 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3474 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3475
3476 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3477 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3478 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3479
3480 for roles in [one, chain] {
3481 let text = toml::to_string(&roles).unwrap();
3482 let back: Roles = toml::from_str(&text).unwrap();
3483 assert_eq!(back.synthesizer, roles.synthesizer);
3484 assert_eq!(back.chatter, roles.chatter);
3485 }
3486 let text = toml::to_string(&Roles {
3487 conductor: Some("x".into()),
3488 ..Roles::default()
3489 })
3490 .unwrap();
3491 assert!(
3492 text.contains("conductor = \"x\""),
3493 "string stays a string: {text}"
3494 );
3495 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3496 }
3497
3498 #[test]
3499 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3500 for (text, ids) in [
3501 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3502 (
3503 r#"dupes_judge = ["first", "second"]"#,
3504 vec!["first", "second"],
3505 ),
3506 ("dupes_judge = []", vec![]),
3507 ] {
3508 let roles: Roles = toml::from_str(text).unwrap();
3509 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3510 let serialized = toml::to_string(&roles).unwrap();
3511 let back: Roles = toml::from_str(&serialized).unwrap();
3512 assert_eq!(back.dupes_judge, roles.dupes_judge);
3513 assert!(serialized.contains(text));
3514 }
3515 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3516 assert!(Roles::default().dupes_judge.is_none());
3517 assert!(Config::starter_toml().contains("# dupes_judge ="));
3518
3519 let mut cfg = Config {
3521 agents: vec![spec("a")],
3522 ..Config::default()
3523 };
3524 cfg.roles.dupes_judge = Some("missing".into());
3525 assert!(cfg.resolve_roles().is_ok());
3526 }
3527
3528 #[test]
3529 fn an_empty_choice_counts_as_unset() {
3530 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3531 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3532 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3533 }
3534
3535 #[test]
3536 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3537 let mut cfg = Config {
3543 agents: vec![spec("a"), spec("b")],
3544 ..Config::default()
3545 };
3546 let want = primary(cfg.roles.synthesizer.as_ref());
3547 assert_eq!(
3548 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3549 .unwrap()
3550 .id,
3551 "a",
3552 "unset falls back to agent::pick's own default order"
3553 );
3554
3555 cfg.roles.synthesizer = Some("b".into());
3556 let want = primary(cfg.roles.synthesizer.as_ref());
3557 assert_eq!(
3558 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3559 .unwrap()
3560 .id,
3561 "b",
3562 "the named agent wins over the default order"
3563 );
3564 }
3565
3566 #[test]
3567 fn empty_roster_is_an_error() {
3568 assert!(Config::default().resolve_roles().is_err());
3569 }
3570
3571 #[test]
3572 fn advise_defaults_to_on_with_three_proposals() {
3573 let g = Graph::default();
3574 assert!(g.advise);
3575 assert!(g.graft_runner_up, "graft is on by default");
3576 assert_eq!(g.advisors, 3);
3577 }
3578
3579 #[test]
3580 fn unset_advisors_falls_back_to_the_judge_roster() {
3581 let cfg = Config {
3582 agents: vec![spec("a"), spec("b")],
3583 roles: Roles {
3584 judges: vec!["b".to_owned()],
3585 ..Roles::default()
3586 },
3587 graph: Graph {
3588 advisors: 2,
3589 ..Graph::default()
3590 },
3591 ..Config::default()
3592 };
3593 let advisors = cfg.advisors().expect("advisors resolve");
3594 assert_eq!(advisors.len(), 2);
3595 assert!(
3596 advisors.iter().all(|a| a.id == "b"),
3597 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3598 );
3599 }
3600
3601 #[test]
3602 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3603 let cfg = Config {
3604 agents: vec![spec("a"), spec("b")],
3605 roles: Roles {
3606 judges: vec!["b".to_owned()],
3607 advisors: vec!["a".to_owned()],
3608 ..Roles::default()
3609 },
3610 graph: Graph {
3611 advisors: 2,
3612 ..Graph::default()
3613 },
3614 ..Config::default()
3615 };
3616 let advisors = cfg.advisors().expect("advisors resolve");
3617 assert!(advisors.iter().all(|a| a.id == "a"));
3618 }
3619
3620 #[test]
3626 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3627 let cfg = Config {
3628 agents: vec![spec("a"), spec("b"), spec("c")],
3629 graph: Graph {
3630 advisors: 3,
3631 judges: 3,
3632 ..Graph::default()
3633 },
3634 ..Config::default()
3635 };
3636 let advisors = cfg.advisors().expect("advisors resolve");
3637 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3638 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3639 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3640 assert_eq!(
3641 advisor_ids, judge_ids,
3642 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3643 );
3644 }
3645
3646 #[test]
3647 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3648 let cfg = Config {
3649 agents: vec![spec("a")],
3650 roles: Roles {
3651 advisors: vec!["nope".to_owned()],
3652 ..Roles::default()
3653 },
3654 graph: Graph {
3655 advisors: 1,
3656 ..Graph::default()
3657 },
3658 ..Config::default()
3659 };
3660 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3661 assert!(format!("{err:#}").contains("nope"));
3662 }
3663
3664 #[test]
3665 fn repos_default_to_no_roots_and_a_day_of_trust() {
3666 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3667 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3668 assert_eq!(Config::default().repos.fetch_interval, 600);
3669 assert!(!Config::default().repos.auto_clone);
3670 assert!(Config::default().repos.clone_command.is_none());
3671 }
3672
3673 #[test]
3674 fn a_config_file_with_no_repos_table_still_loads() {
3675 let dir = tempfile::tempdir().unwrap();
3676 let path = dir.path().join("magi.toml");
3677 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3678 let cfg = Config::load(&path).expect("must load without [repos]");
3679 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3680 assert_eq!(cfg.repos.scan_ttl, 86_400);
3681 }
3682
3683 #[test]
3698 fn a_test_build_does_not_read_the_operators_machine_config() {
3699 let repo = tempfile::tempdir().unwrap();
3700 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3701
3702 let layers = Config::layers(repo.path());
3703 assert_eq!(
3704 layers,
3705 vec![repo.path().join("magi.toml")],
3706 "only the fixture's own file may be a layer"
3707 );
3708 if let Some(real) = dirs::config_dir() {
3709 let machine = real.join("magi").join("config.toml");
3710 assert!(
3711 !layers.contains(&machine),
3712 "the operator's {} must not be a layer in a test build",
3713 machine.display()
3714 );
3715 }
3716 }
3717
3718 #[test]
3719 fn auto_upgrade_config_defaults_and_opt_in() {
3720 let default: Update = toml::from_str("").unwrap();
3721 assert!(!default.auto_restart);
3722 assert_eq!(default.mode, UpdateMode::Notify);
3723 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
3724 assert!(enabled.auto_restart);
3725 assert_eq!(enabled.interval.as_deref(), Some("2h"));
3726 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
3727 }
3728
3729 #[test]
3730 fn starter_toml_loads_through_teravars() {
3731 let dir = tempfile::tempdir().unwrap();
3732 let path = dir.path().join("magi.toml");
3733 std::fs::write(&path, Config::starter_toml()).unwrap();
3734 let parsed = Config::load(&path).expect("starter config must load");
3735 assert_eq!(parsed.graph.implementers, 3);
3736 assert_eq!(parsed.merge.mode, MergeMode::None);
3737 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3738 assert!(parsed.graph.sessions);
3739 assert!(parsed.graph.github_text_guard);
3740 assert_eq!(parsed.graph.timeout_review, 1200);
3741 assert_eq!(parsed.graph.verify_timeout(), 1200);
3742 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3743 }
3744
3745 #[test]
3746 fn release_defaults_to_actions_and_the_starter_documents_it() {
3747 let dir = tempfile::tempdir().unwrap();
3748 let path = dir.path().join("magi.toml");
3749 std::fs::write(&path, Config::starter_toml()).unwrap();
3750 let r = Config::load(&path).unwrap().release;
3751 assert_eq!(r.mode, ReleaseMode::Actions);
3752 assert!(!r.is_local());
3753 assert!(r.commands.is_empty());
3754 assert_eq!(r.timeout_minutes, 30);
3755 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3756 }
3757
3758 #[test]
3759 fn release_local_parses_and_unknown_keys_are_refused() {
3760 let dir = tempfile::tempdir().unwrap();
3761 let path = dir.path().join("magi.toml");
3762 std::fs::write(
3763 &path,
3764 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3765 )
3766 .unwrap();
3767 let r = Config::load(&path).unwrap().release;
3768 assert!(r.is_local());
3769 assert_eq!(r.commands.len(), 2);
3770 assert_eq!(r.timeout_minutes, 5);
3771 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3772 assert!(Config::load(&path).is_err());
3773 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3774 assert!(Config::load(&path).is_err());
3775 }
3776
3777 #[test]
3778 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3779 let dir = tempfile::tempdir().unwrap();
3780 let path = dir.path().join("magi.toml");
3781 std::fs::write(&path, Config::starter_toml()).unwrap();
3782 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3783 assert!(Config::starter_toml().contains("# pre_gate = []"));
3784 }
3785
3786 #[test]
3787 fn release_version_files_parse_default_empty_and_are_validated() {
3788 let dir = tempfile::tempdir().unwrap();
3789 let path = dir.path().join("magi.toml");
3790 std::fs::write(&path, "").unwrap();
3791 assert!(
3792 Config::load(&path)
3793 .unwrap()
3794 .release
3795 .version_files
3796 .is_empty()
3797 );
3798 std::fs::write(
3799 &path,
3800 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
3801 )
3802 .unwrap();
3803 let files = Config::load(&path).unwrap().release.version_files;
3804 assert_eq!(files.len(), 2);
3805 assert_eq!(files[1].kind, VersionKind::Json);
3806 for bad in [
3807 "{ path = \"package.json\", kind = \"json\" }",
3808 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
3809 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
3810 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
3811 ] {
3812 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
3813 assert!(Config::load(&path).is_err(), "{bad}");
3814 }
3815 assert!(Config::starter_toml().contains("# version_files = ["));
3816 }
3817
3818 #[test]
3819 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3820 let starter = Config::starter_toml();
3821 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3822 assert!(starter.contains("verification independent if timeout_review changes later"));
3823 assert!(starter.contains("# timeout_verify = 1200"));
3824 }
3825
3826 #[test]
3827 fn starter_toml_documents_chat_personas() {
3828 let starter = Config::starter_toml();
3829 assert!(starter.contains("# [[talk.personas]]"));
3830 assert!(starter.contains("tone only"));
3831 }
3832
3833 #[test]
3834 fn talk_personas_parse_and_are_validated() {
3835 let dir = tempfile::tempdir().unwrap();
3836 let path = dir.path().join("magi.toml");
3837 std::fs::write(
3838 &path,
3839 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3840 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3841 )
3842 .unwrap();
3843 let cfg = Config::load(&path).expect("loads");
3844 assert_eq!(cfg.talk.personas.len(), 2);
3845 let catalog = crate::persona::catalog(&cfg.talk.personas);
3846 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3847 assert_eq!(
3848 (rei.name.as_str(), rei.prompt.as_str()),
3849 ("Quiet", "Be brief.")
3850 );
3851 assert_eq!(catalog.last().unwrap().id, "gendo");
3852
3853 for (body, needle) in [
3854 (
3855 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3856 "empty `id`",
3857 ),
3858 (
3859 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3860 "empty `prompt`",
3861 ),
3862 (
3863 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3864 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3865 "more than once",
3866 ),
3867 (
3868 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3869 "cannot be redefined",
3870 ),
3871 ] {
3872 std::fs::write(&path, body).unwrap();
3873 let err = format!("{:#}", Config::load(&path).unwrap_err());
3874 assert!(err.contains(needle), "{needle}: {err}");
3875 }
3876 }
3877
3878 #[test]
3879 fn talk_operator_name_is_trimmed_and_validated() {
3880 let dir = tempfile::tempdir().unwrap();
3881 let path = dir.path().join("magi.toml");
3882 let load = |body: &str| {
3883 std::fs::write(&path, body).unwrap();
3884 Config::load(&path)
3885 };
3886 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3887 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3888 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3889 assert_eq!(blank.talk.operator_name(), None);
3890 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3891 let long = "x".repeat(65);
3892 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3893 }
3894
3895 #[test]
3896 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3897 let dir = tempfile::tempdir().unwrap();
3898 let load = |body: &str| {
3899 let path = dir.path().join("c.toml");
3900 std::fs::write(&path, body).unwrap();
3901 Config::load(&path)
3902 };
3903 let ok = load(
3904 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3905 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3906 )
3907 .unwrap();
3908 let c = crate::persona::catalog(&ok.talk.personas);
3909 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3910 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3911 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3912 let oversized = format!(
3913 "data:image/png;base64,{}",
3914 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3915 );
3916 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3917 for (id, fields) in [
3918 ("rei", ""),
3919 ("default", ""),
3920 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3921 ] {
3922 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3923 let cfg = load(&body).expect("bad icon must not invalidate config");
3924 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3925 assert_eq!(persona.id, id);
3926 assert!(crate::persona_icon::load(bad).is_err());
3927 }
3928 }
3929 let doc = Config::starter_toml();
3930 assert!(doc.contains("# icon = "));
3931 }
3932
3933 #[test]
3934 fn talk_personas_in_two_layers_are_refused() {
3935 let dir = tempfile::tempdir().unwrap();
3936 let machine = dir.path().join("machine.toml");
3937 let repo = dir.path().join("repo.toml");
3938 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3939 std::fs::write(&machine, one).unwrap();
3940 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3941 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3942 assert!(err.contains("talk.personas"), "{err}");
3943 }
3944
3945 #[test]
3946 fn starter_toml_documents_role_lists_as_backup_order() {
3947 let starter = Config::starter_toml();
3948 assert!(starter.contains("also an ordered backup list"));
3949 assert!(starter.contains("codex then sonnet are spares"));
3950 }
3951
3952 #[test]
3956 fn a_repository_can_declare_a_linear_history_merge_style() {
3957 let dir = tempfile::tempdir().unwrap();
3958 let path = dir.path().join("magi.toml");
3959 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3960 let parsed = Config::load(&path).expect("config must load");
3961 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3962 }
3963
3964 #[test]
3965 fn later_layers_win_and_vars_render() {
3966 let dir = tempfile::tempdir().unwrap();
3967 let machine = dir.path().join("machine.toml");
3968 let project = dir.path().join("magi.toml");
3969 std::fs::write(
3971 &machine,
3972 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3973 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3974 )
3975 .unwrap();
3976 std::fs::write(
3979 &project,
3980 "[vars]\ncache = \"/shared\"\n\n\
3981 [graph]\ncandidates = 2\n\n\
3982 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3983 )
3984 .unwrap();
3985
3986 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3987 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3988 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3989 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3990 assert_eq!(
3991 cfg.verify.gate,
3992 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3993 );
3994 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3996 }
3997
3998 #[test]
3999 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
4000 let g = Graph::default();
4004 assert_eq!(g.timeout_talk, 3600);
4005
4006 let dir = tempfile::tempdir().unwrap();
4007 let path = dir.path().join("magi.toml");
4008 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4009 let cfg = Config::load(&path).expect("must load without timeout_talk set");
4010 assert_eq!(cfg.graph.timeout_talk, 3600);
4011 }
4012
4013 #[test]
4014 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
4015 let dir = tempfile::tempdir().unwrap();
4016 let path = dir.path().join("magi.toml");
4017 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
4018 let cfg = Config::load(&path).expect("must load");
4019 assert_eq!(cfg.graph.timeout_talk, 120);
4020 }
4021
4022 #[test]
4023 fn the_disk_defaults_are_the_measurements_made_up_front() {
4024 let cfg = Config::default();
4025 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
4026 assert!(cfg.disk.auto_fold);
4027 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
4028 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
4029 }
4030
4031 #[test]
4032 fn an_unset_disk_section_is_the_safe_default() {
4033 let dir = tempfile::tempdir().unwrap();
4034 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
4035 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
4036 assert_eq!(cfg.disk, Disk::default());
4037 }
4038
4039 #[test]
4040 fn env_is_available_to_templates_with_a_default() {
4041 let dir = tempfile::tempdir().unwrap();
4042 let path = dir.path().join("magi.toml");
4043 std::fs::write(
4051 &path,
4052 "[verify]\n\
4053 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
4054 \"populated={{ env | length > 0 }}\"]\n",
4055 )
4056 .unwrap();
4057 let cfg = Config::load(&path).expect("env lookup must render");
4058 assert_eq!(cfg.verify.gate[0], "cache=fallback");
4059 assert_eq!(cfg.verify.gate[1], "populated=true");
4060 }
4061
4062 #[test]
4063 fn a_broken_template_names_the_file() {
4064 let dir = tempfile::tempdir().unwrap();
4065 let path = dir.path().join("magi.toml");
4066 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
4067 let err = Config::load(&path).expect_err("must not silently ignore");
4068 assert!(err.to_string().contains("teravars"), "{err}");
4069 }
4070
4071 #[test]
4072 fn tera_syntax_in_comments_is_inert() {
4073 let dir = tempfile::tempdir().unwrap();
4077 let path = dir.path().join("magi.toml");
4078 std::fs::write(
4079 &path,
4080 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
4081 [graph]\ncandidates = 2\n",
4082 )
4083 .unwrap();
4084 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
4085 assert_eq!(cfg.graph.implementers, 2);
4086 }
4087
4088 #[test]
4089 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
4090 use std::time::Duration;
4091
4092 let mut s: AgentSpec =
4093 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
4094 let budget = Duration::from_millis(1500);
4095 assert_eq!(s.max_turn_secs, None);
4096 assert_eq!(s.turn_timeout(budget), budget);
4097 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
4098 for (cap, expected) in [
4099 (1, Duration::from_secs(1)),
4100 (2, budget),
4101 (0, Duration::ZERO),
4102 ] {
4103 s.max_turn_secs = Some(cap);
4104 let saved = toml::to_string(&s).unwrap();
4105 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
4106 assert_eq!(loaded.max_turn_secs, Some(cap));
4107 assert_eq!(loaded.turn_timeout(budget), expected);
4108 }
4109 }
4110
4111 #[test]
4112 fn opencode_defaults_to_file_delivery() {
4113 let mut s = spec("oc");
4114 s.kind = AgentKind::Opencode;
4115 assert_eq!(s.delivery(), Delivery::File);
4116 s.prompt_delivery = Some(Delivery::Argv);
4117 assert_eq!(s.delivery(), Delivery::Argv);
4118 }
4119 #[test]
4120 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
4121 let g = Graph::default();
4126 assert!(
4127 g.land,
4128 "stopping at an open PR left the watching to a human"
4129 );
4130 assert!(
4131 g.land_approval,
4132 "on-by-default land is only defensible while this is also on"
4133 );
4134 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
4135 assert!(
4136 g.hold_contested_merge,
4137 "a contested hand-off must still reach a human when approvals are off"
4138 );
4139 }
4140 #[test]
4141 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
4142 let dir = tempfile::tempdir().unwrap();
4146 let machine = dir.path().join("machine.toml");
4147 let repo = dir.path().join("magi.toml");
4148 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
4149 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
4150
4151 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4152 .expect_err("two layers naming one array must not merge silently");
4153 assert_eq!(
4154 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4155 "config-merge"
4156 );
4157 let err = err.to_string();
4158 assert!(err.contains("roles.implementers"), "{err}");
4159 assert!(err.contains("machine.toml"), "{err}");
4162 assert!(err.contains("magi.toml"), "{err}");
4163 }
4164
4165 #[test]
4166 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
4167 let dir = tempfile::tempdir().unwrap();
4170 let machine = dir.path().join("machine.toml");
4171 let repo = dir.path().join("magi.toml");
4172 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
4173 std::fs::write(
4174 &repo,
4175 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
4176 [roles]\nimplementers = [\"oc\"]\n",
4177 )
4178 .unwrap();
4179
4180 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
4181 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
4182 assert_eq!(cfg.roles.implementers, ["oc"]);
4183 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
4184 }
4185
4186 #[test]
4187 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
4188 let dir = tempfile::tempdir().unwrap();
4191 let machine = dir.path().join("machine.toml");
4192 let repo = dir.path().join("magi.toml");
4193 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4194 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4195
4196 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4197 assert_eq!(
4198 cfg.verify.gate,
4199 [
4200 "editorconfig-checker".to_owned(),
4201 "cargo make check".to_owned()
4202 ],
4203 "low-priority (machine) command first, high-priority (repo) command after"
4204 );
4205 }
4206
4207 fn load_one(body: &str) -> Result<Config> {
4208 let dir = tempfile::tempdir().unwrap();
4209 let path = dir.path().join("magi.toml");
4210 std::fs::write(&path, body).unwrap();
4211 Config::load_layers(&[path])
4212 }
4213
4214 #[test]
4215 fn pre_clean_config_is_strict_and_single_layer() {
4216 assert!(Config::default().worktree.pre_clean.is_empty());
4217 let good = load_one("[worktree]\npre_clean = [{run = 'cleanup', timeout_secs = 60}]\n");
4218 assert_eq!(good.unwrap().worktree.pre_clean[0].timeout_secs, Some(60));
4219 for bad in [
4220 "{}",
4221 "{run = ''}",
4222 "{run = ' ', timeout_secs = 2}",
4223 "{run = 'x', timeout_secs = 0}",
4224 "{run = 'x', timeout_secs = -1}",
4225 "{copy = 'cache'}",
4226 "{run = 'x', optional = true}",
4227 "'x'",
4228 ] {
4229 assert!(
4230 load_one(&format!("[worktree]\npre_clean = [{bad}]\n")).is_err(),
4231 "{bad}"
4232 );
4233 }
4234 let dir = tempfile::tempdir().unwrap();
4235 let a = dir.path().join("a.toml");
4236 let b = dir.path().join("b.toml");
4237 for path in [&a, &b] {
4238 std::fs::write(path, "[worktree]\npre_clean = [{run = 'cleanup'}]\n").unwrap();
4239 }
4240 assert!(
4241 Config::load_layers(&[a, b])
4242 .unwrap_err()
4243 .to_string()
4244 .contains("worktree.pre_clean")
4245 );
4246 }
4247
4248 #[test]
4249 fn worktree_setup_defaults_to_empty_and_parses_steps() {
4250 assert!(Config::default().worktree.setup.is_empty());
4251 let cfg = load_one(
4252 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
4253 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
4254 )
4255 .unwrap();
4256 assert_eq!(cfg.worktree.setup.len(), 3);
4257 assert!(cfg.worktree.setup[1].optional);
4258 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
4259 }
4260
4261 #[test]
4262 fn worktree_setup_rejects_malformed_steps() {
4263 for bad in [
4264 "{ copy = \"a\", run = \"b\" }",
4265 "{ optional = true }",
4266 "{ copy = \"a -> ../b\" }",
4267 "{ copy = \"a -> /abs\" }",
4268 "{ copy = \"a -> .git/config\" }",
4269 "{ run = \"b\", optional = true }",
4270 "{ copy = \"a\", timeout_secs = 3 }",
4271 "{ run = \"b\", bogus = 1 }",
4272 ] {
4273 let body = format!("[worktree]\nsetup = [{bad}]\n");
4274 assert!(load_one(&body).is_err(), "{bad}");
4275 }
4276 }
4277
4278 #[test]
4279 fn worktree_setup_in_two_layers_is_refused() {
4280 let dir = tempfile::tempdir().unwrap();
4281 let machine = dir.path().join("machine.toml");
4282 let repo = dir.path().join("magi.toml");
4283 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4284 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4285 assert!(Config::load_layers(&[machine, repo]).is_err());
4286 }
4287
4288 #[test]
4289 fn starter_toml_documents_worktree_setup() {
4290 let starter = Config::starter_toml();
4291 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4292 let body = starter.replace("# [worktree]", "[worktree]");
4294 let mut out = String::new();
4295 let mut live = false;
4296 for line in body.lines() {
4297 if line == "[worktree]" {
4298 live = true;
4299 } else if live && !line.starts_with("# ") {
4300 live = false;
4301 }
4302 out.push_str(&if live {
4303 line.replacen("# ", "", 1)
4304 } else {
4305 line.to_owned()
4306 });
4307 out.push('\n');
4308 }
4309 let cfg = load_one(&out).expect("uncommented example loads");
4310 assert_eq!(cfg.worktree.setup.len(), 3);
4311 }
4312
4313 #[test]
4314 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4315 let dir = tempfile::tempdir().unwrap();
4316 let machine = dir.path().join("machine.toml");
4317 let repo = dir.path().join("magi.toml");
4318 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4319 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4320
4321 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4322 assert_eq!(
4323 cfg.verify.e2e,
4324 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4325 );
4326 }
4327
4328 #[test]
4329 fn two_layers_declaring_repos_roots_are_both_scanned() {
4330 let dir = tempfile::tempdir().unwrap();
4331 let machine = dir.path().join("machine.toml");
4332 let repo = dir.path().join("magi.toml");
4333 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4334 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4335
4336 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4337 assert_eq!(
4338 cfg.repos.roots,
4339 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4340 );
4341 }
4342
4343 #[test]
4344 fn duplicate_gate_commands_across_layers_both_run() {
4345 let dir = tempfile::tempdir().unwrap();
4348 let machine = dir.path().join("machine.toml");
4349 let repo = dir.path().join("magi.toml");
4350 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4351 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4352
4353 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4354 assert_eq!(
4355 cfg.verify.gate,
4356 ["same-command".to_owned(), "same-command".to_owned()]
4357 );
4358 }
4359
4360 #[test]
4361 fn notify_command_is_still_refused_across_two_layers() {
4362 let dir = tempfile::tempdir().unwrap();
4364 let machine = dir.path().join("machine.toml");
4365 let repo = dir.path().join("magi.toml");
4366 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4367 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4368
4369 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4370 .expect_err("an argv split across layers must not concatenate");
4371 assert_eq!(
4372 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4373 "config-merge"
4374 );
4375 let err = err.to_string();
4376 assert!(err.contains("notify.command"), "{err}");
4377 assert!(err.contains("machine.toml"), "{err}");
4378 assert!(err.contains("magi.toml"), "{err}");
4379 }
4380
4381 #[test]
4382 fn one_layer_declaring_verify_gate_runs_unchanged() {
4383 let dir = tempfile::tempdir().unwrap();
4386 let path = dir.path().join("magi.toml");
4387 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4388
4389 let cfg = Config::load(&path).expect("single layer must still load");
4390 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4391 }
4392
4393 #[test]
4394 fn layered_parse_failures_name_the_failing_input() {
4395 let dir = tempfile::tempdir().unwrap();
4396 let a = dir.path().join("a.toml");
4397 let b = dir.path().join("b.toml");
4398 std::fs::write(&a, "[graph").unwrap();
4399 std::fs::write(&b, "[verify").unwrap();
4400 let paths = [a.clone(), b.clone()];
4401 let first = Config::load_layers(&paths).unwrap_err();
4402 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4403 assert_eq!(first_cause.stage, "config-parse");
4404 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4405 std::fs::write(&a, "").unwrap();
4406 let second = Config::load_layers(&paths).unwrap_err();
4407 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4408 assert_eq!(second_cause.stage, "config-parse");
4409 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4410 assert_ne!(first_cause.target, second_cause.target);
4411 }
4412
4413 #[test]
4414 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4415 let dir = tempfile::tempdir().unwrap();
4416 let machine = dir.path().join("machine.toml");
4417 let repo = dir.path().join("magi.toml");
4418 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4419 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4420 let paths = vec![machine.clone(), repo.clone()];
4421
4422 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4423 let described =
4424 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4425 assert!(described.contains("editorconfig-checker && cargo make check"));
4426 assert!(
4427 described.contains(&machine.display().to_string()),
4428 "{described}"
4429 );
4430 assert!(
4431 described.contains(&repo.display().to_string()),
4432 "{described}"
4433 );
4434
4435 let single = vec![repo.clone()];
4437 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4438 let solo_described =
4439 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4440 assert_eq!(solo_described, "cargo make check");
4441 }
4442
4443 mod remote_layers {
4444 use super::*;
4445
4446 fn git(dir: &Path, args: &[&str]) {
4447 use crate::proc::Quiet as _;
4448 let out = std::process::Command::new("git")
4449 .args(args)
4450 .quiet()
4451 .current_dir(dir)
4452 .output()
4453 .unwrap();
4454 assert!(out.status.success(), "git {args:?}: {out:?}");
4455 }
4456
4457 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4460 let tmp = tempfile::tempdir().unwrap();
4461 let bare = tmp.path().join("o.git");
4462 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4463 let repo = tmp.path().join("repo");
4464 std::fs::create_dir_all(&repo).unwrap();
4465 git(&repo, &["init", "-b", "trunk"]);
4466 git(&repo, &["config", "user.name", "t"]);
4467 git(&repo, &["config", "user.email", "t@example.com"]);
4468 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4469 git(&repo, &["add", "-A"]);
4470 git(&repo, &["commit", "-m", "x"]);
4471 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4472 git(&repo, &["push", "origin", "trunk"]);
4473 git(&repo, &["fetch", "origin"]);
4474 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4475 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4476 (tmp, repo)
4477 }
4478
4479 #[tokio::test]
4480 async fn branch_owner_holds_only_add_literal_true_values() {
4481 for (text, expected) in [
4482 ("[graph]\nland_approval = true\n", true),
4483 ("[graph]\nland_approval = false\n", false),
4484 ("[graph]\nland = true\n", false),
4485 ("[graph\n", false),
4486 ("[graph]\nland_approval = \"yes\"\n", false),
4487 ("[graph]\nland_approval = 1\n", false),
4488 ] {
4489 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4490 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4491 let (holds, _) = branch_owner_holds(&repo, &head).await;
4492 assert_eq!(
4493 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4494 expected
4495 );
4496 assert!(
4497 !holds
4498 .iter()
4499 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4500 );
4501 for base in [false, true] {
4502 let mut cfg = Config::default();
4503 cfg.graph.land_approval = base;
4504 let mut state = crate::run::RunState::new(
4505 repo.clone(),
4506 "trunk".into(),
4507 head.clone(),
4508 "review".into(),
4509 cfg,
4510 );
4511 state.observe_branch_owner_holds(&head).await;
4512 assert!(
4513 state.branch_owner_holds.is_empty(),
4514 "competition candidates are excluded"
4515 );
4516 state.reviewed_commits = Some(Vec::new());
4517 state.observe_branch_owner_holds(&head).await;
4518 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4519 }
4520 }
4521 }
4522
4523 #[tokio::test]
4524 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4525 let (_tmp, repo) = fixture(
4526 "[graph]\nland_approval = true\n",
4527 "[graph]\nland_approval = true\n",
4528 );
4529 git(&repo, &["rm", "magi.toml"]);
4530 std::fs::create_dir(repo.join(".magi")).unwrap();
4531 std::fs::write(
4532 repo.join(".magi/config.toml"),
4533 "[graph]\nhold_contested_merge = true\n",
4534 )
4535 .unwrap();
4536 git(&repo, &["add", "."]);
4537 git(&repo, &["commit", "-m", "nested hold"]);
4538 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4539 let (holds, _) = branch_owner_holds(&repo, &head).await;
4540 assert_eq!(
4541 holds,
4542 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4543 );
4544 let (holds, diagnostics) =
4545 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4546 assert!(holds.is_empty());
4547 assert!(!diagnostics.is_empty());
4548 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4549 assert!(holds.is_empty());
4550 assert!(!diagnostics.is_empty());
4551 for base in [false, true] {
4552 let mut cfg = Config::default();
4553 cfg.graph.land_approval = base;
4554 let mut state = crate::run::RunState::new(
4555 repo.clone(),
4556 "trunk".into(),
4557 head.clone(),
4558 "review".into(),
4559 cfg,
4560 );
4561 state.reviewed_commits = Some(Vec::new());
4562 state.observe_branch_owner_holds(&head).await;
4563 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4564 state
4565 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4566 .await;
4567 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4568 }
4569 }
4570
4571 #[test]
4572 fn reads_the_remote_blob_not_the_working_tree() {
4573 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4574 let (cfg, _) = Config::discover(&repo, None).unwrap();
4575 assert_eq!(cfg.graph.implementers, 2);
4576 }
4577
4578 #[test]
4579 fn detached_head_still_reads_the_remote() {
4580 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4581 git(&repo, &["checkout", "--detach"]);
4582 let (cfg, _) = Config::discover(&repo, None).unwrap();
4583 assert_eq!(cfg.graph.implementers, 2);
4584 }
4585
4586 #[test]
4587 fn a_missing_ref_is_an_error_not_a_fallback() {
4588 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4589 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4590 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4591 assert!(err.contains("origin"), "{err}");
4592 }
4593
4594 #[test]
4595 fn merge_base_in_the_checkout_locates_the_ref() {
4596 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4597 assert!(Config::discover(&repo, None).is_err());
4598 }
4599
4600 #[test]
4601 fn the_magi_dir_layer_is_read_too() {
4602 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4603 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4604 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4605 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4606 git(&repo, &["add", "-A"]);
4607 git(&repo, &["commit", "-m", "y"]);
4608 git(&repo, &["push", "origin", "trunk"]);
4609 git(&repo, &["fetch", "origin"]);
4610 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4611 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4612 assert_eq!(layers.len(), 2);
4613 }
4614
4615 #[test]
4616 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4617 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4618 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4619 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4620 git(&repo, &["add", "-A"]);
4621 git(&repo, &["commit", "-m", "inc"]);
4622 git(&repo, &["push", "origin", "trunk"]);
4623 git(&repo, &["fetch", "origin"]);
4624 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4626 let (cfg, _) = Config::discover(&repo, None).unwrap();
4627 assert_eq!(cfg.graph.implementers, 2);
4628 }
4629
4630 #[test]
4631 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4632 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4633 let m = t.path().join("machine.toml");
4634 std::fs::write(
4635 &m,
4636 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4637 )
4638 .unwrap();
4639 let (remote, base) = {
4640 let probe = probe_merge(&m, &repo).unwrap();
4641 (probe.remote, probe.base)
4642 };
4643 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4644 }
4645
4646 #[test]
4647 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4648 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4649 let m = t.path().join("machine.toml");
4650 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4651 let probe = probe_merge(&m, &repo).unwrap();
4652 assert_eq!(probe.base.as_deref(), Some("repo"));
4653 }
4654
4655 #[test]
4656 fn every_include_form_is_recognised() {
4657 assert!(declares_include("include = [\"a.toml\"]\n"));
4658 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4659 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4660 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4661 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4662 }
4663
4664 #[test]
4665 fn an_explicit_config_is_read_as_named() {
4666 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4667 let own = t.path().join("own.toml");
4668 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4669 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4670 assert_eq!(cfg.graph.implementers, 4);
4671 }
4672
4673 #[test]
4674 fn discover_fetched_fails_when_the_fetch_does() {
4675 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4676 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4677 let rt = tokio::runtime::Builder::new_current_thread()
4678 .enable_all()
4679 .build()
4680 .unwrap();
4681 let err = rt
4682 .block_on(Config::discover_fetched(&repo, None))
4683 .unwrap_err();
4684 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4685 }
4686
4687 #[test]
4688 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4689 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4690 let remote = tmp.path().join("o.git");
4691 let offline = tmp.path().join("offline.git");
4692 std::fs::rename(&remote, &offline).unwrap();
4693 let rt = tokio::runtime::Builder::new_current_thread()
4694 .enable_all()
4695 .build()
4696 .unwrap();
4697 let fetch = rt
4698 .block_on(Config::discover_fetched(&repo, None))
4699 .unwrap_err();
4700 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4701 assert_eq!(fetch_cause.stage, "config-fetch");
4702 assert_eq!(fetch_cause.target, "origin/trunk");
4703
4704 std::fs::rename(&offline, &remote).unwrap();
4705 let parse = rt
4706 .block_on(Config::discover_fetched(&repo, None))
4707 .unwrap_err();
4708 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4709 assert_eq!(parse_cause.stage, "config-parse");
4710 assert!(parse_cause.target.contains("magi.toml"));
4711 assert!(
4712 !parse_cause.target.contains("/magi/config/"),
4713 "cache commit paths are incidental"
4714 );
4715 assert_ne!(fetch_cause.stage, parse_cause.stage);
4716 }
4717
4718 #[test]
4719 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4720 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4723 git(&repo, &["remote", "set-head", "origin", "-d"]);
4724 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4725 git(
4726 &repo,
4727 &["config", "remote.origin.followRemoteHEAD", "never"],
4728 );
4729 let rt = tokio::runtime::Builder::new_current_thread()
4730 .enable_all()
4731 .build()
4732 .unwrap();
4733 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4734 assert_eq!(cfg.graph.implementers, 2);
4735 }
4736
4737 #[test]
4738 fn a_non_git_directory_reads_its_files() {
4739 let dir = tempfile::tempdir().unwrap();
4740 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4741 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4742 assert_eq!(cfg.graph.implementers, 4);
4743 }
4744 }
4745
4746 #[test]
4747 fn github_language_defaults_to_english_and_accepts_japanese() {
4748 let default: Graph = toml::from_str("").unwrap();
4749 assert_eq!(default.github_language, "en");
4750 assert!(default.github_english() && default.language_gate());
4751 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4752 assert!(!ja.github_english() && !ja.language_gate());
4753 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4755 assert!(only_ops.language_gate());
4756 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4757 assert!(!off.language_gate() && off.github_english());
4758 assert!(Config::starter_toml().contains("github_language = \"en\""));
4759 }
4760}