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 pub github_text_guard: bool,
377 pub github_language: String,
383 #[serde(alias = "candidates")]
415 pub implementers: usize,
416 #[serde(default)]
418 pub selected_implementer: Option<String>,
419 pub judges: usize,
421 pub deliberate_rounds: usize,
423 pub reviewers: usize,
431 pub review_rounds: usize,
433 pub gate_fix_rounds: usize,
439 pub max_parallel: usize,
441 pub language: String,
443 pub sessions: bool,
451 pub timeout_implement: u64,
453 pub timeout_judge: u64,
455 pub timeout_review: u64,
457 pub timeout_verify: Option<u64>,
466 pub timeout_fix: u64,
468 pub timeout_talk: u64,
476 pub timeout_resource_wait: u64,
485 pub retries: usize,
487 pub worktree_root: Option<PathBuf>,
489 pub land: bool,
502 pub land_rounds: usize,
504 pub rerun_flaky_checks: bool,
512 pub land_approval: bool,
523 pub hold_contested_merge: bool,
534 pub question_routing: bool,
539 pub file_followups: bool,
546 pub release_deputy_followups: bool,
554 pub answer_timeout: u64,
558 pub incomplete_review: IncompleteReviewPolicy,
561 pub e2e_every_round: bool,
579 pub advise: bool,
593 pub advisors: usize,
598 pub graft_runner_up: bool,
607}
608
609impl Default for Graph {
610 fn default() -> Self {
611 Self {
612 github_text_guard: true,
613 github_language: "en".into(),
614 implementers: 1,
615 selected_implementer: None,
616 judges: 3,
617 deliberate_rounds: 1,
618 reviewers: 3,
619 review_rounds: 6,
620 gate_fix_rounds: 1,
621 max_parallel: 4,
622 language: "en".to_owned(),
623 sessions: true,
624 timeout_implement: 3600,
625 timeout_judge: 1200,
626 timeout_review: 1200,
627 timeout_verify: None,
628 timeout_fix: 1800,
629 timeout_talk: 3600,
630 timeout_resource_wait: 1800,
631 retries: 1,
632 worktree_root: None,
633 land: true,
634 land_rounds: 4,
635 rerun_flaky_checks: true,
636 land_approval: true,
637 hold_contested_merge: true,
638 question_routing: true,
639 file_followups: true,
640 release_deputy_followups: true,
641 answer_timeout: 86_400,
642 incomplete_review: IncompleteReviewPolicy::Block,
643 e2e_every_round: false,
644 advise: true,
645 advisors: 3,
646 graft_runner_up: true,
647 }
648 }
649}
650
651impl Graph {
652 pub fn verify_timeout(&self) -> u64 {
656 self.timeout_verify.unwrap_or(self.timeout_review)
657 }
658
659 pub fn language_gate(&self) -> bool {
662 self.github_text_guard && self.github_english()
663 }
664
665 pub fn github_english(&self) -> bool {
667 crate::lang::is_english(&self.github_language)
668 }
669}
670
671#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
678#[serde(rename_all = "lowercase")]
679pub enum IncompleteReviewPolicy {
680 Block,
684 Warn,
689}
690
691#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
693#[serde(rename_all = "lowercase")]
694pub enum LeakPolicy {
695 Warn,
697 Redact,
699 Fail,
701}
702
703#[derive(Debug, Clone, Deserialize, Serialize)]
710#[serde(deny_unknown_fields, default)]
711pub struct Blind {
712 pub commit_msg_hook: bool,
715 pub strip_lines: Vec<String>,
719 pub vendor_tokens: Vec<String>,
721 pub on_leak: LeakPolicy,
723 pub seed: Option<u64>,
726}
727
728impl Default for Blind {
729 fn default() -> Self {
730 Self {
731 commit_msg_hook: true,
732 strip_lines: [
733 "Co-Authored-By:",
734 "Signed-off-by:",
735 "Assisted-by:",
736 "Generated-by:",
737 "Generated with",
738 "\u{1f916}",
739 ]
740 .iter()
741 .map(|s| (*s).to_owned())
742 .collect(),
743 vendor_tokens: [
744 "claude",
745 "anthropic",
746 "codex",
747 "openai",
748 "chatgpt",
749 "gemini",
750 "grok",
751 "xai",
752 "copilot",
753 "opencode",
754 "qoder",
755 "cursor",
756 "\u{1f916}",
757 ]
758 .iter()
759 .map(|s| (*s).to_owned())
760 .collect(),
761 on_leak: LeakPolicy::Warn,
762 seed: None,
763 }
764 }
765}
766
767#[derive(Debug, Clone, Default, Deserialize, Serialize)]
769#[serde(deny_unknown_fields, default)]
770pub struct Verify {
771 pub e2e: Vec<String>,
774 pub gate: Vec<String>,
776 #[serde(default)]
785 pub pre_gate: Vec<String>,
786 pub shell: Option<Vec<String>>,
789}
790
791impl Verify {
792 pub fn cache_dir(&self) -> Option<PathBuf> {
798 self.e2e
799 .iter()
800 .chain(self.gate.iter())
801 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
802 }
803
804 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
807 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
808 crate::cache::extract_manifest_paths(&all)
809 }
810}
811
812#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
814#[serde(deny_unknown_fields, default)]
815pub struct Worktree {
816 pub setup: Vec<SetupStep>,
819}
820
821#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
823#[serde(deny_unknown_fields, default)]
824pub struct SetupStep {
825 pub copy: Option<String>,
828 pub optional: bool,
830 pub run: Option<String>,
832 pub timeout_secs: Option<u64>,
835}
836
837impl Worktree {
838 pub fn validate(&self) -> Result<()> {
840 for (i, step) in self.setup.iter().enumerate() {
841 let n = i + 1;
842 match (&step.copy, &step.run) {
843 (Some(c), None) => {
844 if step.timeout_secs.is_some() {
845 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
846 }
847 crate::worktree_setup::validate_copy(c)
848 .with_context(|| format!("[worktree] setup step {n}"))?;
849 }
850 (None, Some(r)) => {
851 if r.trim().is_empty() {
852 bail!("[worktree] setup step {n}: `run` is empty");
853 }
854 if step.optional {
855 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
856 }
857 }
858 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
859 }
860 }
861 Ok(())
862 }
863}
864
865#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
875#[serde(deny_unknown_fields, default)]
876pub struct Disk {
877 pub min_free_bytes: u64,
886 pub auto_fold: bool,
892 pub fold_grace_secs: u64,
900 pub cache_limit_bytes: u64,
912 pub worktree_limit_bytes: u64,
914 pub worktree_reclaim_bytes: u64,
916 pub retained_attempt_limit: usize,
920}
921
922impl Default for Disk {
923 fn default() -> Self {
924 Self {
925 min_free_bytes: 8 * 1024 * 1024 * 1024,
926 auto_fold: true,
927 fold_grace_secs: 6 * 60 * 60,
928 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
929 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
930 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
931 retained_attempt_limit: 8,
932 }
933 }
934}
935
936#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
938#[serde(rename_all = "lowercase")]
939pub enum MergeMode {
940 None,
943 Local,
946 Pr,
950}
951
952#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
966#[serde(rename_all = "lowercase")]
967pub enum MergeStyle {
968 #[default]
973 Merge,
974 Squash,
980 Rebase,
986}
987
988#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
990#[serde(rename_all = "lowercase")]
991pub enum MergeCi {
992 #[default]
994 Expected,
995 None,
997}
998
999impl MergeCi {
1000 pub fn expectation(self) -> crate::land::CiExpectation {
1002 match self {
1003 Self::Expected => crate::land::CiExpectation::Expected,
1004 Self::None => crate::land::CiExpectation::Absent,
1005 }
1006 }
1007}
1008
1009#[derive(Debug, Clone, Deserialize, Serialize)]
1011#[serde(deny_unknown_fields, default)]
1012pub struct Merge {
1013 pub mode: MergeMode,
1016 pub ci: MergeCi,
1018 pub base: Option<String>,
1020 pub style: MergeStyle,
1023 pub remote: String,
1025 pub release_bump: bool,
1038}
1039
1040impl Default for Merge {
1041 fn default() -> Self {
1042 Self {
1043 mode: MergeMode::None,
1044 ci: MergeCi::Expected,
1045 base: None,
1046 style: MergeStyle::default(),
1047 remote: "origin".to_owned(),
1048 release_bump: true,
1049 }
1050 }
1051}
1052
1053#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1055#[serde(rename_all = "lowercase")]
1056pub enum UpdateMode {
1057 Off,
1059 Notify,
1062 Install,
1064}
1065
1066#[derive(Debug, Clone, Deserialize, Serialize)]
1068#[serde(deny_unknown_fields, default)]
1069pub struct Update {
1070 pub mode: UpdateMode,
1072 pub interval: Option<String>,
1074 pub auto_restart: bool,
1076}
1077
1078impl Default for Update {
1079 fn default() -> Self {
1080 Self {
1081 mode: UpdateMode::Notify,
1082 interval: None,
1083 auto_restart: false,
1084 }
1085 }
1086}
1087
1088#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1090#[serde(rename_all = "lowercase")]
1091pub enum ReleaseMode {
1092 #[default]
1095 Actions,
1096 Local,
1101}
1102
1103#[derive(Debug, Clone, Deserialize, Serialize)]
1105#[serde(deny_unknown_fields, default)]
1106pub struct Release {
1107 pub mode: ReleaseMode,
1110 pub commands: Vec<String>,
1117 pub timeout_minutes: u64,
1119 pub version_files: Vec<VersionFile>,
1127}
1128
1129#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1131#[serde(rename_all = "lowercase")]
1132pub enum VersionKind {
1133 Cargo,
1135 Json,
1137}
1138
1139#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1141#[serde(deny_unknown_fields)]
1142pub struct VersionFile {
1143 pub path: String,
1145 pub kind: VersionKind,
1147}
1148
1149impl Default for Release {
1150 fn default() -> Self {
1151 Self {
1152 mode: ReleaseMode::Actions,
1153 commands: Vec::new(),
1154 timeout_minutes: 30,
1155 version_files: Vec::new(),
1156 }
1157 }
1158}
1159
1160impl Release {
1161 pub fn validate(&self) -> Result<()> {
1163 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1164 }
1165
1166 pub fn is_local(&self) -> bool {
1168 self.mode == ReleaseMode::Local
1169 }
1170}
1171
1172#[derive(Debug, Clone, Deserialize, Serialize)]
1174#[serde(try_from = "CoordinationFields")]
1175pub struct Coordination {
1176 pub contract_file: String,
1178 pub contract_token: String,
1180 pub lock_file: String,
1182}
1183
1184#[derive(Deserialize, Default)]
1185#[serde(deny_unknown_fields, default)]
1186struct CoordinationFields {
1187 contract_file: String,
1188 contract_token: String,
1189 lock_file: String,
1190}
1191
1192impl TryFrom<CoordinationFields> for Coordination {
1193 type Error = anyhow::Error;
1194
1195 fn try_from(fields: CoordinationFields) -> Result<Self> {
1196 for (key, name) in [
1197 ("coordination.contract_file", &fields.contract_file),
1198 ("coordination.lock_file", &fields.lock_file),
1199 ] {
1200 if name.trim().is_empty()
1201 || name != name.trim()
1202 || name == "."
1203 || name.contains("..")
1204 || name.contains(['/', '\\', ':', '\0'])
1205 {
1206 bail!(
1207 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1208 );
1209 }
1210 }
1211 let token = &fields.contract_token;
1212 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1213 bail!(
1214 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1215 );
1216 }
1217 Ok(Self {
1218 contract_file: fields.contract_file,
1219 contract_token: fields.contract_token,
1220 lock_file: fields.lock_file,
1221 })
1222 }
1223}
1224
1225#[cfg(test)]
1226pub(crate) fn test_coordination() -> Option<Coordination> {
1227 Some(Coordination {
1228 contract_file: "updater.contract".into(),
1229 contract_token: "test-protocol-v1".into(),
1230 lock_file: "updater.lock".into(),
1231 })
1232}
1233
1234#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1236#[serde(deny_unknown_fields, default)]
1237pub struct Config {
1238 pub coordination: Option<Coordination>,
1240 pub agents: Vec<AgentSpec>,
1242 pub roles: Roles,
1244 pub graph: Graph,
1246 pub blind: Blind,
1248 pub verify: Verify,
1250 pub worktree: Worktree,
1252 pub disk: Disk,
1254 pub merge: Merge,
1256 pub update: Update,
1258 pub prompts: Prompts,
1260 pub notify: Notify,
1262 pub repos: Repos,
1265 pub talk: Talk,
1267 pub daemon: Daemon,
1269 pub release: Release,
1271 pub context_windows: BTreeMap<String, u64>,
1274}
1275
1276const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1286 ("claude-opus-4", 200_000),
1287 ("claude-sonnet-4", 200_000),
1288 ("claude-haiku-4", 200_000),
1289 ("claude-3", 200_000),
1290 ("opus", 200_000),
1291 ("sonnet", 200_000),
1292 ("haiku", 200_000),
1293 ("gpt-5", 400_000),
1294 ("gpt-4.1", 1_000_000),
1295 ("gpt-4o", 128_000),
1296 ("o3", 200_000),
1297 ("o4-mini", 200_000),
1298 ("gemini-2.5", 1_000_000),
1299 ("deepseek", 128_000),
1300];
1301
1302impl Config {
1303 pub fn context_window(&self, model: &str) -> Option<u64> {
1308 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1309 let mut best: Option<(usize, u64)> = None;
1310 for (key, window) in entries {
1311 if key == model {
1312 return Some(window);
1313 }
1314 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1315 best = Some((key.len(), window));
1316 }
1317 }
1318 best.map(|(_, w)| w)
1319 }
1320 lookup(
1321 model,
1322 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1323 )
1324 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1325 }
1326}
1327
1328#[derive(Debug, Clone, Deserialize, Serialize)]
1338#[serde(deny_unknown_fields, default)]
1339pub struct Daemon {
1340 pub max_concurrent_runs: usize,
1361 pub pause_for_interrupts: bool,
1377 pub max_deputies: usize,
1384 pub release_stall_minutes: u64,
1391}
1392
1393impl Default for Daemon {
1394 fn default() -> Self {
1395 Self {
1396 max_concurrent_runs: 1,
1397 pause_for_interrupts: false,
1398 max_deputies: 2,
1399 release_stall_minutes: 60,
1400 }
1401 }
1402}
1403
1404#[derive(Debug, Clone, Deserialize, Serialize)]
1416#[serde(deny_unknown_fields, default)]
1417pub struct Repos {
1418 pub roots: Vec<PathBuf>,
1422 pub scan_ttl: u64,
1429 pub fetch_interval: u64,
1434}
1435
1436impl Default for Repos {
1437 fn default() -> Self {
1438 Self {
1439 roots: Vec::new(),
1440 scan_ttl: 86_400,
1441 fetch_interval: 600,
1442 }
1443 }
1444}
1445
1446#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1462#[serde(deny_unknown_fields, default)]
1463pub struct Prompts {
1464 pub all: String,
1466 pub implement: String,
1468 pub judge: String,
1470 pub review: String,
1472 pub fix: String,
1474}
1475
1476impl Prompts {
1477 pub fn overlay(&self, node: &str) -> Option<String> {
1482 let specific = match node {
1483 "implement" => &self.implement,
1484 "judge" | "vote" | "deliberate" => &self.judge,
1485 "review" => &self.review,
1486 "fix" => &self.fix,
1487 _ => "",
1488 };
1489 let mut parts: Vec<&str> = Vec::new();
1490 for p in [self.all.trim(), specific.trim()] {
1491 if !p.is_empty() {
1492 parts.push(p);
1493 }
1494 }
1495 if parts.is_empty() {
1496 return None;
1497 }
1498 Some(parts.join("\n\n"))
1499 }
1500}
1501
1502#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1509#[serde(deny_unknown_fields, default)]
1510pub struct Notify {
1511 pub command: Vec<String>,
1514}
1515
1516#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1518#[serde(deny_unknown_fields, default)]
1519pub struct Talk {
1520 pub allow_write: bool,
1529 pub personas: Vec<PersonaSpec>,
1534 pub operator_name: Option<String>,
1538}
1539
1540pub const OPERATOR_NAME_MAX: usize = 64;
1542
1543impl Talk {
1544 pub fn operator_name(&self) -> Option<&str> {
1546 self.operator_name
1547 .as_deref()
1548 .map(str::trim)
1549 .filter(|n| !n.is_empty())
1550 }
1551}
1552
1553#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1555#[serde(deny_unknown_fields)]
1556pub struct PersonaSpec {
1557 pub id: String,
1559 #[serde(default)]
1562 pub name: String,
1563 #[serde(default)]
1566 pub prompt: String,
1567 #[serde(default, skip_serializing_if = "Option::is_none")]
1571 pub icon: Option<String>,
1572}
1573
1574#[derive(Debug, Clone)]
1576pub struct ResolvedRoles {
1577 pub implementers: Vec<AgentSpec>,
1579 pub judges: Vec<AgentSpec>,
1581 pub reviewers: Vec<AgentSpec>,
1583 pub fixer: Option<Vec<AgentSpec>>,
1588 pub conductor: AgentSpec,
1590 pub implementer_roster: Vec<AgentSpec>,
1598 pub judge_roster: Vec<AgentSpec>,
1602 pub reviewer_roster: Vec<AgentSpec>,
1604}
1605
1606fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1613 let mut out = Vec::new();
1614 for (k, v) in table {
1615 if prefix.is_empty() && k == "vars" {
1616 continue;
1617 }
1618 let path = if prefix.is_empty() {
1619 k.clone()
1620 } else {
1621 format!("{prefix}.{k}")
1622 };
1623 match v {
1624 toml::Value::Array(_) => out.push(path),
1625 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1626 _ => {}
1627 }
1628 }
1629 out
1630}
1631
1632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1634enum ArrayMerge {
1635 Append,
1639 Replace,
1642}
1643
1644fn array_merge_policy(key: &str) -> ArrayMerge {
1683 match key {
1684 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1685 _ => ArrayMerge::Replace,
1686 }
1687}
1688
1689impl Config {
1690 pub fn load(path: &Path) -> Result<Self> {
1693 Self::load_layers(&[path.to_path_buf()])
1694 }
1695
1696 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1706 let mut ctx = teravars::system_context();
1707 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1708 ctx.insert("env", &env);
1709 if let Some(last) = paths.last()
1710 && let Some(dir) = last.parent()
1711 {
1712 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1715 .map(|s| PathBuf::from(s.trim()))
1716 .unwrap_or_else(|_| dir.to_path_buf());
1717 ctx.insert("repo", &dir.to_string_lossy());
1718 ctx.insert(
1719 "repo_name",
1720 &dir.file_name().unwrap_or_default().to_string_lossy(),
1721 );
1722 }
1723 ctx
1724 }
1725
1726 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1734 let mut engine = teravars::Engine::default();
1735 let ctx = Self::render_ctx(paths);
1736 if paths.len() > 1 {
1737 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1738 if error.downcast_ref::<ConfigFailure>().is_some() {
1739 error
1740 } else {
1741 let message = error.to_string();
1744 error
1745 .context(ConfigFailure::layers("config-merge", paths))
1746 .context(message)
1747 }
1748 })?;
1749 }
1750 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1751 .map_err(|error| {
1752 let cause = ConfigFailure::render(&error, paths);
1753 anyhow::Error::new(error).context(cause)
1754 })
1755 .with_context(|| {
1756 format!(
1757 "rendering config via teravars: {}",
1758 paths
1759 .iter()
1760 .map(|p| p.display().to_string())
1761 .collect::<Vec<_>>()
1762 .join(", ")
1763 )
1764 })?;
1765 let mut table = merged.config;
1766 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1767 table.remove("vars");
1770 let detect_agents = !table.contains_key("agents");
1774 let mut cfg: Self = toml::Value::Table(table)
1775 .try_into()
1776 .context("deserializing magi config")
1777 .context(ConfigFailure::layers("config-deserialize", paths))?;
1778 crate::persona::validate(&cfg.talk.personas)?;
1779 cfg.worktree.validate()?;
1780 cfg.release.validate()?;
1781 if let Some(name) = cfg.talk.operator_name() {
1782 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1783 bail!(
1784 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1785 );
1786 }
1787 }
1788 if detect_agents {
1789 cfg.agents = Self::autodetected().agents;
1790 }
1791 Ok(cfg)
1792 }
1793
1794 fn normalize_renamed_keys(
1802 paths: &[PathBuf],
1803 engine: &mut teravars::Engine,
1804 ctx: &teravars::Context,
1805 table: &mut toml::map::Map<String, toml::Value>,
1806 ) -> Result<()> {
1807 let both = matches!(
1808 table.get("graph"),
1809 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1810 );
1811 if !both {
1812 return Ok(());
1813 }
1814 let mut winner: Option<toml::Value> = None;
1815 for path in paths {
1816 let one = teravars::load_merged([path], engine, ctx)
1817 .map_err(|error| {
1818 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1819 anyhow::Error::new(error).context(cause)
1820 })
1821 .with_context(|| format!("rendering {}", path.display()))?;
1822 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1823 continue;
1824 };
1825 if g.contains_key("candidates") && g.contains_key("implementers") {
1826 bail!(
1827 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1828 path.display()
1829 );
1830 }
1831 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1832 winner = Some(v.clone());
1833 }
1834 }
1835 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1836 g.remove("candidates");
1837 if let Some(v) = winner {
1838 g.insert("implementers".to_owned(), v);
1839 }
1840 }
1841 Ok(())
1842 }
1843
1844 fn refuse_split_arrays(
1868 paths: &[PathBuf],
1869 engine: &mut teravars::Engine,
1870 ctx: &teravars::Context,
1871 ) -> Result<()> {
1872 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1873 for path in paths {
1874 let one = teravars::load_merged([path], engine, ctx)
1875 .map_err(|error| {
1876 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1877 anyhow::Error::new(error).context(cause)
1878 })
1879 .with_context(|| format!("rendering {}", path.display()))?;
1880 for key in array_keys(&one.config, "") {
1881 if array_merge_policy(&key) == ArrayMerge::Append {
1882 continue;
1883 }
1884 if let Some(first) = seen.get(&key) {
1885 bail!(
1886 "`{key}` is an array declared in two config layers:\n \
1887 {}\n {}\nteravars appends arrays when it merges, so \
1888 magi would run the concatenation of both - which is \
1889 not what either file says. Declare `{key}` in exactly \
1890 one of them.",
1891 first.display(),
1892 path.display()
1893 );
1894 }
1895 seen.insert(key, path.clone());
1896 }
1897 }
1898 Ok(())
1899 }
1900
1901 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1923 let mut engine = teravars::Engine::default();
1924 let ctx = Self::render_ctx(paths);
1925 let mut out = Vec::new();
1926 for path in paths {
1927 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1928 continue;
1929 };
1930 let mut cur = &one.config;
1931 let mut found = None;
1932 let parts: Vec<&str> = key.split('.').collect();
1933 for (i, part) in parts.iter().enumerate() {
1934 match cur.get(*part) {
1935 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1936 found = Some(a);
1937 break;
1938 }
1939 Some(toml::Value::Table(t)) => cur = t,
1940 _ => break,
1941 }
1942 }
1943 let Some(values) = found else { continue };
1944 let strings: Vec<String> = values
1945 .iter()
1946 .filter_map(|v| v.as_str().map(str::to_owned))
1947 .collect();
1948 if !strings.is_empty() {
1949 out.push((path.clone(), strings));
1950 }
1951 }
1952 out
1953 }
1954
1955 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1961 let mut engine = teravars::Engine::default();
1962 let ctx = Self::render_ctx(paths);
1963 paths
1964 .iter()
1965 .map(|path| {
1966 let one = teravars::load_merged([path], &mut engine, &ctx)
1967 .map(|m| m.config)
1968 .with_context(|| format!("rendering {}", path.display()));
1969 (path.clone(), one)
1970 })
1971 .collect()
1972 }
1973
1974 pub fn describe_composed(
1984 paths: &[PathBuf],
1985 commands: &[String],
1986 key: &str,
1987 empty: &str,
1988 ) -> String {
1989 if commands.is_empty() {
1990 return empty.to_owned();
1991 }
1992 let joined = commands.join(" && ");
1993 let provenance = Self::array_provenance(paths, key);
1994 if provenance.len() <= 1 {
1995 return joined;
1996 }
1997 let mut out = joined;
1998 for (path, cmds) in &provenance {
1999 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2000 }
2001 out
2002 }
2003
2004 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2011 #[cfg(test)]
2012 crate::web::request_cost::discovery();
2013 if let Some(p) = explicit {
2014 let paths = vec![p.to_path_buf()];
2015 return Ok((Self::load_layers(&paths)?, paths));
2016 }
2017 let paths = Self::layers_checked(repo)?;
2018 if paths.is_empty() {
2019 return Ok((Self::autodetected(), paths));
2020 }
2021 Ok((Self::load_layers(&paths)?, paths))
2022 }
2023
2024 pub async fn discover_fetched(
2027 repo: &Path,
2028 explicit: Option<&Path>,
2029 ) -> Result<(Self, Vec<PathBuf>)> {
2030 if explicit.is_none() && is_git_worktree(repo) {
2031 let (remote, cfg_base) = probe_remote_base(repo);
2035 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2036 .await
2037 .with_context(|| ConfigFailure {
2038 stage: "config-base",
2039 target: remote.clone(),
2040 })?;
2041 let out = crate::git::fetch(repo, &remote, &base)
2042 .await
2043 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2044 .with_context(|| ConfigFailure {
2045 stage: "config-fetch",
2046 target: format!("{remote}/{base}"),
2047 })?;
2048 if !out.ok() {
2049 return Err(anyhow::anyhow!(
2050 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2051 out.stderr.lines().next().unwrap_or("").trim()
2052 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2053 }
2054 if cfg_base.is_none() {
2055 crate::git::ensure_remote_head(repo, &remote, &base).await;
2056 }
2057 }
2058 Self::discover(repo, explicit).map_err(|error| {
2059 if error.downcast_ref::<ConfigFailure>().is_some() {
2060 error
2061 } else {
2062 error.context(ConfigFailure {
2063 stage: "config-load",
2064 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2065 })
2066 }
2067 })
2068 }
2069
2070 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2072 if !is_git_worktree(repo) {
2073 return Ok(Self::layers(repo));
2074 }
2075 let mut paths: Vec<PathBuf> = Self::machine_layer()
2076 .into_iter()
2077 .filter(|p| p.is_file())
2078 .collect();
2079 paths.extend(Self::repo_layers(repo)?);
2080 Ok(paths)
2081 }
2082
2083 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2085 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2086 if let Some(root) = cached {
2087 let relative = path.strip_prefix(root).unwrap_or(path);
2088 let reference = resolve_remote_base(repo)
2089 .map(|(remote, base)| format!("{remote}/{base}"))
2090 .unwrap_or_else(|_| "remote base".to_owned());
2091 format!(
2092 "{} at {reference} (including its includes)",
2093 repo.join(relative).display()
2094 )
2095 } else {
2096 format!("{} (including its includes)", path.display())
2097 }
2098 }
2099
2100 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2103 if !is_git_worktree(repo) {
2104 return Ok([
2105 repo.join(".magi").join("config.toml"),
2106 repo.join("magi.toml"),
2107 ]
2108 .into_iter()
2109 .filter(|p| p.is_file())
2110 .collect());
2111 }
2112 remote_layers(repo)
2113 }
2114
2115 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2135
2136 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2141 let mut paths = Vec::new();
2142 paths.extend(Self::machine_layer());
2143 paths.push(repo.join(".magi").join("config.toml"));
2144 paths.push(repo.join("magi.toml"));
2145 paths.retain(|p| p.is_file());
2146 paths
2147 }
2148
2149 #[cfg(test)]
2156 pub(crate) fn machine_layer() -> Option<PathBuf> {
2157 std::env::var(Self::CONFIG_DIR_ENV)
2158 .ok()
2159 .filter(|dir| !dir.trim().is_empty())
2160 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2161 }
2162
2163 #[cfg(not(test))]
2165 pub(crate) fn machine_layer() -> Option<PathBuf> {
2166 match std::env::var(Self::CONFIG_DIR_ENV) {
2167 Ok(dir) if dir.trim().is_empty() => None,
2169 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2170 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2171 }
2172 }
2173
2174 pub fn autodetected() -> Self {
2176 let mut cfg = Self::default();
2177 for (kind, id, model) in [
2178 (AgentKind::Claude, "opus", Some("opus")),
2179 (AgentKind::Claude, "sonnet", Some("sonnet")),
2180 (AgentKind::Antigravity, "antigravity", None),
2181 (AgentKind::Opencode, "opencode", None),
2182 (AgentKind::Codex, "codex", None),
2183 (AgentKind::Omp, "omp", None),
2184 ] {
2185 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2186 cfg.agents.push(AgentSpec {
2187 id: id.to_owned(),
2188 kind,
2189 model: model.map(str::to_owned),
2190 command: Vec::new(),
2191 extra_args: Vec::new(),
2192 env: BTreeMap::new(),
2193 prompt_delivery: None,
2194 max_turn_secs: None,
2195 });
2196 }
2197 }
2198 cfg
2199 }
2200
2201 pub fn cache_dir(&self) -> Option<PathBuf> {
2204 self.verify.cache_dir()
2205 }
2206
2207 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2209 self.agents
2210 .iter()
2211 .find(|a| a.id == id)
2212 .with_context(|| format!("no agent with id `{id}` in the roster"))
2213 }
2214
2215 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2222 let mut out = Vec::with_capacity(count);
2223 for i in 0..count {
2224 let spec = if ids.is_empty() {
2225 self.agents[(i + offset) % self.agents.len()].clone()
2226 } else {
2227 self.agent(&ids[i % ids.len()])?.clone()
2228 };
2229 out.push(spec);
2230 }
2231 Ok(out)
2232 }
2233
2234 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2241 if ids.is_empty() {
2242 Ok(self.agents.clone())
2243 } else {
2244 ids.iter().map(|id| self.agent(id).cloned()).collect()
2245 }
2246 }
2247
2248 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2255 if self.agents.is_empty() {
2256 bail!(
2257 "agent roster is empty: no agent CLI found on PATH and no \
2258 [[agents]] in the config. Run `magi init` to write a starter \
2259 magi.toml."
2260 );
2261 }
2262 let pinned = self
2263 .graph
2264 .selected_implementer
2265 .as_ref()
2266 .map(|id| self.agent(id).cloned())
2267 .transpose()?;
2268 Ok(ResolvedRoles {
2269 implementers: match &pinned {
2270 Some(agent) => vec![agent.clone()],
2271 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2272 },
2273 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2274 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2275 fixer: match self.roles.fixer.as_ref() {
2276 Some(choice) => Some(crate::agent::pick_chain(
2279 &self.agents,
2280 Some(choice),
2281 &|_| true,
2282 "fixer",
2283 )?),
2284 None => None,
2285 },
2286 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2291 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2292 Some(ids) if !ids.is_empty() => ids
2295 .iter()
2296 .find_map(|id| self.agent(id).ok())
2297 .cloned()
2298 .with_context(|| {
2299 format!("[roles] conductor names no agent in the roster: {ids:?}")
2300 })?,
2301 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2306 .unwrap_or_else(|_| self.agents[0].clone()),
2307 },
2308 implementer_roster: match pinned {
2309 Some(agent) => vec![agent],
2310 None => self.full_roster(&self.roles.implementers)?,
2311 },
2312 judge_roster: self.full_roster(&self.roles.judges)?,
2313 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2314 })
2315 }
2316
2317 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2339 if self.agents.is_empty() {
2340 bail!(
2341 "agent roster is empty: no agent CLI found on PATH and no \
2342 [[agents]] in the config. Run `magi init` to write a starter \
2343 magi.toml."
2344 );
2345 }
2346 if !self.roles.advisors.is_empty() {
2347 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2348 }
2349 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2350 }
2351
2352 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2356 if self.roles.advisors.is_empty() {
2357 self.full_roster(&self.roles.judges)
2358 } else {
2359 self.full_roster(&self.roles.advisors)
2360 }
2361 }
2362
2363 pub fn shell(&self) -> Vec<String> {
2365 if let Some(s) = &self.verify.shell {
2366 return s.clone();
2367 }
2368 if which("sh") {
2369 vec!["sh".to_owned(), "-c".to_owned()]
2370 } else {
2371 vec!["cmd".to_owned(), "/C".to_owned()]
2372 }
2373 }
2374
2375 pub fn starter_toml() -> String {
2377 let detected = Self::autodetected();
2378 let mut s = String::from(
2379 "# magi — blind multi-agent implementation competition.\n\
2380 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2381 # -> blind judging -> deliberation -> private final vote\n\
2382 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2383 #\n\
2384 # Rendered by teravars: a `[vars]` table, env\n\
2385 # and system lookups, and `include = [...]` all work. Tera\n\
2386 # braces are live everywhere in this file, but comments are\n\
2387 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2388 # may quote `{{ ... }}` freely.\n\
2389 #\n\
2390 # Layers deep-merge in increasing\n\
2391 # precedence, so the roster can live once per machine in\n\
2392 # <config_dir>/magi/config.toml and each repo only states its own\n\
2393 # gate:\n\
2394 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2395 [vars]\n\
2396 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2397 # Single quotes inside the braces: teravars renders the raw file\n\
2398 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2399 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2400 );
2401 if detected.agents.is_empty() {
2402 s.push_str(
2403 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2404 # kind = claude | opencode | antigravity | codex | command\n\
2405 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2406 );
2407 } else {
2408 for a in &detected.agents {
2409 s.push_str("[[agents]]\n");
2410 s.push_str(&format!("id = {:?}\n", a.id));
2411 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2412 if let Some(m) = &a.model {
2413 s.push_str(&format!("model = {m:?}\n"));
2414 }
2415 s.push('\n');
2416 }
2417 }
2418 s.push_str(
2419 "# Leave a role list empty to rotate through the roster.\n\
2420 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2421 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2422 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2423 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2424 [roles]\n\
2425 implementers = []\n\
2426 judges = []\n\
2427 reviewers = []\n\
2428 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2429 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2430 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2431 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2432 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2433 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2434 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2435 [graph]\n\
2436 # Gate GitHub prose; secret redaction is always enabled.\n\
2437 github_text_guard = true\n\
2438 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2439 github_language = \"en\"\n\
2440 implementers = 3\n\
2441 judges = 3\n\
2442 deliberate_rounds = 1\n\
2443 reviewers = 3\n\
2444 review_rounds = 6\n\
2445 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2446 gate_fix_rounds = 1\n\
2447 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2448 rerun_flaky_checks = true\n\
2449 # Port the strengths judges named in the losing candidates onto the\n\
2450 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2451 graft_runner_up = true\n\
2452 max_parallel = 4\n\
2453 language = \"en\"\n\
2454 # One CLI conversation per seat: judges keep their own argument\n\
2455 # across deliberation, the fixer keeps its implementation context.\n\
2456 sessions = true\n\
2457 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2458 # the final gate inherit this value for compatibility.\n\
2459 timeout_review = 1200\n\
2460 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2461 # verification independent if timeout_review changes later.\n\
2462 # timeout_verify = 1200\n\
2463 # Longest a seat waits for the shared build cache before it is\n\
2464 # spawned. Never counted against an agent's own timeout; expiry\n\
2465 # holds the run (resumable) instead of failing the agent.\n\
2466 # timeout_resource_wait = 1800\n\n\
2467 # What the chat calls you (persona address and the Chat's turn label).\n\
2468 # [talk]\n\
2469 # operator_name = \"Commander\"\n\n\
2470 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2471 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2472 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2473 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2474 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2475 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2476 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2477 # [[talk.personas]]\n\
2478 # id = \"gendo\"\n\
2479 # name = \"Gendo Ikari\"\n\
2480 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2481 # icon = \"~/pictures/gendo.png\"\n\n\
2482 [verify]\n\
2483 # Run once per review round in the winner's worktree; failures are\n\
2484 # fed back to the fixer.\n\
2485 e2e = []\n\
2486 # Final gate. Every command must exit 0 before a merge.\n\
2487 gate = []\n\
2488 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2489 # before the gate; whatever they change becomes one commit. A failing\n\
2490 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2491 # gate (timeout_verify). Keep it light and idempotent.\n\
2492 # pre_gate = []\n\n\
2493 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2494 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2495 # before any agent or verify command touches it. `copy` reads from the\n\
2496 # primary checkout and never overwrites; `optional` skips a missing\n\
2497 # source. `run` goes through the shell with the worktree as cwd and\n\
2498 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2499 # the verify timeout). Setup must not edit tracked files, and what it\n\
2500 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2501 # layer only.\n\
2502 # [worktree]\n\
2503 # setup = [\n\
2504 # { copy = \".env.example -> .env\" },\n\
2505 # { copy = \".env.local\", optional = true },\n\
2506 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2507 # ]\n\n\
2508 [merge]\n\
2509 # none | local | pr\n\
2510 mode = \"none\"\n\
2511 # expected (default) | none. Set none only in repository config without CI.\n\
2512 # Ignores all check statuses; reviews and approval still apply.\n\
2513 # ci = \"expected\"\n\
2514 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2515 [update]\n\
2516 # off | notify | install — checked in the background, throttled.\n\
2517 mode = \"notify\"\n\
2518 # interval = \"24h\"\n\n\
2519 # Opt-in: magi web updates and restarts only after runs/chats finish.\n\
2520 # auto_restart = false\n\
2521 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2522 # Standalone magi serve cannot restart. Busy work waits indefinitely.\n\
2523 # Failed tags are skipped until process restart or a different tag.\n\
2524 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2525 [daemon]\n\
2526 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2527 # no new commit and no check changing state before `magi serve`\n\
2528 # notices and asks you. A failed check is rerun once on its own;\n\
2529 # still red after that escalates at once. 0 turns the watcher off.\n\
2530 # release_stall_minutes = 60\n\n\
2531 [release]\n\
2532 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2533 # Actions never run (private, no minutes): the release pull request\n\
2534 # does not wait for CI, you approve the merge in magi, and then\n\
2535 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2536 # runs `commands` from a clean checkout of the merge commit. A\n\
2537 # failure holds the release with a notice; it is never retried blind.\n\
2538 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2539 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2540 # mode = \"actions\"\n\
2541 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2542 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2543 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2544 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2545 # timeout_minutes = 30\n\
2546 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2547 # The first entry is the version of record and must be the file the\n\
2548 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2549 # rewritten to the same version. Paths are relative to the repository\n\
2550 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2551 # is not touched.\n\
2552 # version_files = [\n\
2553 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2554 # { path = \"package.json\", kind = \"json\" },\n\
2555 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2556 # ]\n",
2557 );
2558 s
2559 }
2560}
2561
2562pub fn which(program: &str) -> bool {
2564 find_program(program).is_some()
2565}
2566
2567pub fn find_program(program: &str) -> Option<PathBuf> {
2576 find_program_on(program, &std::env::var_os("PATH")?)
2577}
2578
2579pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2582 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2583 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2584}
2585
2586fn find_program_in(
2587 program: &str,
2588 paths: &std::ffi::OsStr,
2589 pathext: Option<&str>,
2590) -> Option<PathBuf> {
2591 let p = Path::new(program);
2592 if p.components().count() > 1 {
2593 return p.is_file().then(|| p.to_path_buf());
2594 }
2595 std::env::split_paths(paths).find_map(|dir| match pathext {
2596 Some(exts) => {
2597 let bare = dir.join(program);
2598 if p.extension().is_some() && bare.is_file() {
2599 return Some(bare);
2600 }
2601 exts.split(';')
2602 .filter(|e| !e.is_empty())
2603 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2604 .find(|c| c.is_file())
2605 }
2606 None => Some(dir.join(program)).filter(|c| c.is_file()),
2607 })
2608}
2609
2610const REPO_MARKER: &str = ".magi-repo";
2612
2613fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2614 use crate::proc::Quiet as _;
2615 #[cfg(test)]
2616 crate::web::request_cost::git();
2617 let out = std::process::Command::new("git")
2618 .args(args)
2619 .quiet()
2620 .current_dir(repo)
2621 .stdin(std::process::Stdio::null())
2622 .output()
2623 .ok()?;
2624 out.status
2625 .success()
2626 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2627}
2628
2629fn is_git_worktree(repo: &Path) -> bool {
2632 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2633}
2634
2635#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2638pub enum OwnerHold {
2639 LandApproval,
2641 HoldContestedMerge,
2643}
2644
2645impl OwnerHold {
2646 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2648
2649 pub fn key(self) -> &'static str {
2651 match self {
2652 Self::LandApproval => "land_approval",
2653 Self::HoldContestedMerge => "hold_contested_merge",
2654 }
2655 }
2656
2657 pub fn base_value(self, graph: &Graph) -> bool {
2659 match self {
2660 Self::LandApproval => graph.land_approval,
2661 Self::HoldContestedMerge => graph.hold_contested_merge,
2662 }
2663 }
2664}
2665
2666pub async fn branch_owner_holds(
2669 repo: &Path,
2670 head: &str,
2671) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2672 let mut holds = Vec::new();
2673 let mut diagnostics = Vec::new();
2674 if let Err(error) =
2677 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2678 {
2679 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2680 return (holds, diagnostics);
2681 }
2682 for file in ["magi.toml", ".magi/config.toml"] {
2683 let object = format!("{head}:{file}");
2684 let text = match crate::git::git(repo, &["show", &object]).await {
2685 Ok(text) => text,
2686 Err(error) => {
2687 let error = format!("{error:#}");
2689 if !error.contains("does not exist in")
2690 && !error.contains("exists on disk, but not in")
2691 {
2692 diagnostics.push(format!(
2693 "cannot read reviewed branch {file} at {head}: {error}"
2694 ));
2695 }
2696 continue;
2697 }
2698 };
2699 let value = match toml::from_str::<toml::Value>(&text) {
2700 Ok(value) => value,
2701 Err(error) => {
2702 diagnostics.push(format!(
2703 "cannot parse reviewed branch {file} at {head}: {error}"
2704 ));
2705 continue;
2706 }
2707 };
2708 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2709 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2710 }
2711 for hold in OwnerHold::ALL {
2712 if value
2713 .get("graph")
2714 .and_then(|g| g.get(hold.key()))
2715 .and_then(toml::Value::as_bool)
2716 == Some(true)
2717 {
2718 holds.push((hold, file.to_owned()));
2719 }
2720 }
2721 }
2722 (holds, diagnostics)
2723}
2724
2725#[derive(Deserialize, Default)]
2726struct ProbeMerge {
2727 base: Option<String>,
2728 remote: Option<String>,
2729}
2730
2731#[derive(Deserialize, Default)]
2732struct Probe {
2733 merge: Option<ProbeMerge>,
2734}
2735
2736fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2742 if !path.is_file() {
2743 return None;
2744 }
2745 let paths = [path.to_path_buf()];
2746 let mut engine = teravars::Engine::default();
2747 let mut ctx = Config::render_ctx(&paths);
2748 ctx.insert("repo", &repo.to_string_lossy());
2751 ctx.insert(
2752 "repo_name",
2753 &repo.file_name().unwrap_or_default().to_string_lossy(),
2754 );
2755 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2756 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2757 {
2758 return probe.merge;
2759 }
2760 let text = std::fs::read_to_string(path).ok()?;
2761 toml::from_str::<Probe>(&text).ok()?.merge
2762}
2763
2764fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2766 let mut remote = None;
2767 let mut base = None;
2768 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2769 sources.push(repo.join("magi.toml"));
2770 sources.push(repo.join(".magi").join("config.toml"));
2771 for path in sources {
2772 if let Some(m) = probe_merge(&path, repo) {
2773 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2774 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2775 }
2776 }
2777 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2778}
2779
2780fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2782 let (remote, base) = probe_remote_base(repo);
2783 let base = match base {
2784 Some(b) => b,
2785 None => {
2786 let head = format!("refs/remotes/{remote}/HEAD");
2787 git_out(repo, &["symbolic-ref", "--quiet", &head])
2788 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2789 .with_context(|| {
2790 format!(
2791 "cannot tell which branch of `{remote}` holds magi.toml: \
2792 set [merge] base, or run `git remote set-head {remote} -a`"
2793 )
2794 })?
2795 }
2796 };
2797 Ok((remote, base))
2798}
2799
2800fn fnv_hex(text: &str) -> String {
2801 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2802 for b in text.bytes() {
2803 hash ^= u64::from(b);
2804 hash = hash.wrapping_mul(0x0100_0000_01b3);
2805 }
2806 format!("{hash:016x}")
2807}
2808
2809fn declares_include(text: &str) -> bool {
2815 match toml::from_str::<toml::Table>(text) {
2816 Ok(table) => {
2817 table.contains_key("include")
2818 || table
2819 .get("teravars")
2820 .and_then(toml::Value::as_table)
2821 .is_some_and(|t| t.contains_key("include"))
2822 }
2823 Err(_) => text.contains("include"),
2824 }
2825}
2826
2827fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2830 use crate::proc::Quiet as _;
2831 #[cfg(test)]
2832 crate::web::request_cost::git();
2833 let mut archive = std::process::Command::new("git")
2834 .args(["archive", "--format=tar", sha])
2835 .quiet()
2836 .current_dir(repo)
2837 .stdin(std::process::Stdio::null())
2838 .stdout(std::process::Stdio::piped())
2839 .stderr(std::process::Stdio::null())
2840 .spawn()
2841 .context("running git archive")?;
2842 let tar = std::process::Command::new("tar")
2843 .arg("-x")
2844 .arg("-C")
2845 .arg(dest)
2846 .quiet()
2847 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2848 .output()
2849 .context("running tar")?;
2850 let status = archive.wait().context("waiting for git archive")?;
2851 if !status.success() || !tar.status.success() {
2852 bail!(
2853 "cannot unpack {sha} for the config's includes: {}",
2854 String::from_utf8_lossy(&tar.stderr).trim()
2855 );
2856 }
2857 Ok(())
2858}
2859
2860fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2863 let (remote, base) = resolve_remote_base(repo)?;
2864 let tracking = format!("refs/remotes/{remote}/{base}");
2865 let spec = format!("{tracking}^{{commit}}");
2866 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2867 .map(|s| s.trim().to_owned())
2868 .filter(|s| !s.is_empty())
2869 .with_context(|| {
2870 format!(
2871 "`{remote}/{base}` does not exist in this checkout; fetch it \
2872 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2873 a possibly stale local magi.toml instead"
2874 )
2875 })?;
2876 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2877 let rels = [".magi/config.toml", "magi.toml"];
2878 let mut texts: Vec<(&str, String)> = Vec::new();
2879 for rel in rels {
2880 let object = format!("{sha}:{rel}");
2881 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2882 continue;
2883 }
2884 let Some(text) = git_out(repo, &["show", &object]) else {
2885 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2886 };
2887 texts.push((rel, text));
2888 }
2889 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2890 let build = |root: &Path| -> Result<PathBuf> {
2894 let final_dir = root.join(&key);
2895 if !final_dir.is_dir() {
2896 std::fs::create_dir_all(root)?;
2897 let tmp = root.join(format!(
2898 "{key}.tmp-{}-{}",
2899 std::process::id(),
2900 std::time::SystemTime::now()
2901 .duration_since(std::time::UNIX_EPOCH)
2902 .map(|d| d.as_nanos())
2903 .unwrap_or_default()
2904 ));
2905 let filled = (|| -> Result<()> {
2906 std::fs::create_dir_all(&tmp)?;
2907 if wants_tree {
2908 extract_tree(repo, &sha, &tmp)?;
2909 }
2910 for (rel, text) in &texts {
2911 let file = tmp.join(rel);
2912 let parent = file.parent().unwrap_or(&tmp);
2913 std::fs::create_dir_all(parent)?;
2914 std::fs::write(&file, text)?;
2915 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2916 }
2917 Ok(())
2918 })();
2919 if let Err(e) = filled {
2920 let _ = std::fs::remove_dir_all(&tmp);
2921 return Err(e);
2922 }
2923 if std::fs::rename(&tmp, &final_dir).is_err() {
2924 let _ = std::fs::remove_dir_all(&tmp);
2926 if !final_dir.is_dir() {
2927 bail!("cannot place {}", final_dir.display());
2928 }
2929 }
2930 }
2931 Ok(final_dir)
2932 };
2933 let common = git_out(
2934 repo,
2935 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2936 )
2937 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2938 let dir = match common.map(|c| build(&c)) {
2939 Some(Ok(d)) => d,
2940 _ => build(&std::env::temp_dir().join("magi-config"))
2941 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2942 };
2943 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2944}
2945
2946#[cfg(test)]
2947mod tests {
2948 #[test]
2949 fn coordination_defaults_off_and_validates_rendered_layer_values() {
2950 let dir = tempfile::tempdir().unwrap();
2951 let machine = dir.path().join("machine.toml");
2952 let repo = dir.path().join("repo.toml");
2953 std::fs::write(&machine, "").unwrap();
2954 assert!(Config::default().coordination.is_none());
2955 assert!(Config::load(&machine).unwrap().coordination.is_none());
2956 std::fs::write(
2957 &machine,
2958 r#"
2959[vars]
2960contract = "updater.contract"
2961[coordination]
2962contract_file = "{{ vars.contract }}"
2963contract_token = "protocol-v1"
2964lock_file = "updater.lock"
2965"#,
2966 )
2967 .unwrap();
2968 let cfg = Config::load(&machine).unwrap();
2969 let policy = cfg.coordination.unwrap();
2970 assert_eq!(policy.contract_file, "updater.contract");
2971 assert_eq!(policy.contract_token, "protocol-v1");
2972 assert_eq!(policy.lock_file, "updater.lock");
2973 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
2974 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
2975 let policy = cfg.coordination.unwrap();
2976 assert_eq!(policy.contract_file, "updater.contract");
2977 assert_eq!(policy.lock_file, "repository.lock");
2978 std::fs::write(
2979 &repo,
2980 r#"
2981[vars]
2982bad = "../escape"
2983[coordination]
2984lock_file = "{{ vars.bad }}"
2985"#,
2986 )
2987 .unwrap();
2988 let error = Config::load_layers(&[machine, repo]).unwrap_err();
2989 assert!(format!("{error:#}").contains("coordination.lock_file"));
2990 }
2991
2992 #[test]
2993 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
2994 let dir = tempfile::tempdir().unwrap();
2995 let path = dir.path().join("config.toml");
2996 let valid = toml::toml! {
2997 [coordination]
2998 contract_file = "updater.contract"
2999 contract_token = "protocol-v1"
3000 lock_file = "updater.lock"
3001 };
3002 for key in ["contract_file", "lock_file"] {
3003 for bad in [
3004 "",
3005 " ",
3006 " file",
3007 "file ",
3008 "\tfile",
3009 "file\t",
3010 ".",
3011 "..",
3012 "file..name",
3013 "../escape",
3014 "a/b",
3015 "a\\b",
3016 "/absolute",
3017 "C:drive",
3018 "C:\\absolute",
3019 "nul\0name",
3020 ] {
3021 let mut table = valid.clone();
3022 table["coordination"][key] = bad.into();
3023 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3024 let error = Config::load(&path).unwrap_err();
3025 assert!(
3026 format!("{error:#}").contains(&format!("coordination.{key}")),
3027 "{bad:?}: {error:#}"
3028 );
3029 }
3030 }
3031 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
3032 let mut table = valid.clone();
3033 table["coordination"]["contract_token"] = bad.into();
3034 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3035 let error = Config::load(&path).unwrap_err();
3036 assert!(
3037 format!("{error:#}").contains("coordination.contract_token"),
3038 "{error:#}"
3039 );
3040 }
3041 for key in ["contract_file", "contract_token", "lock_file"] {
3042 let mut table = valid.clone();
3043 table["coordination"].as_table_mut().unwrap().remove(key);
3044 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3045 let error = Config::load(&path).unwrap_err();
3046 assert!(
3047 format!("{error:#}").contains(&format!("coordination.{key}")),
3048 "{error:#}"
3049 );
3050 }
3051 let mut table = valid;
3052 table["coordination"]
3053 .as_table_mut()
3054 .unwrap()
3055 .insert("typo".into(), "value".into());
3056 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3057 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
3058 }
3059
3060 #[test]
3061 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
3062 let mut cfg = Config::default();
3063 assert_eq!(
3064 cfg.context_window("claude-sonnet-4-5-20250929"),
3065 Some(200_000)
3066 );
3067 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
3068 assert_eq!(cfg.context_window("mystery-model"), None);
3069 cfg.context_windows
3070 .insert("claude-sonnet-4-5".into(), 1_000_000);
3071 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
3072 cfg.context_windows.insert("mystery".into(), 32_768);
3073 assert_eq!(
3075 cfg.context_window("claude-sonnet-4-5-20250929"),
3076 Some(1_000_000)
3077 );
3078 cfg.context_windows
3080 .insert("claude-sonnet-4-5-20250929".into(), 7);
3081 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
3082 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
3083 }
3084
3085 use super::*;
3086
3087 #[test]
3090 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
3091 let dir = tempfile::tempdir().unwrap();
3092 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
3093 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
3094 let paths = dir.path().as_os_str();
3095 assert_eq!(
3096 find_program_in("codex", paths, Some(".EXE;.CMD")),
3097 Some(dir.path().join("codex.cmd"))
3098 );
3099 assert_eq!(
3100 find_program_in("codex", paths, None),
3101 Some(dir.path().join("codex"))
3102 );
3103 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3104 }
3105
3106 fn spec(id: &str) -> AgentSpec {
3107 AgentSpec {
3108 id: id.to_owned(),
3109 kind: AgentKind::Command,
3110 model: None,
3111 command: vec!["true".to_owned()],
3112 extra_args: Vec::new(),
3113 env: BTreeMap::new(),
3114 prompt_delivery: None,
3115 max_turn_secs: None,
3116 }
3117 }
3118
3119 #[test]
3120 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
3121 let default: Merge = toml::from_str("").unwrap();
3122 assert_eq!(default.ci, MergeCi::Expected);
3123 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
3124 assert_eq!(
3125 config.merge.ci.expectation(),
3126 crate::land::CiExpectation::Absent
3127 );
3128 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
3129 assert!(Config::starter_toml().contains("# ci = \"expected\""));
3130 }
3131
3132 #[test]
3133 fn github_text_guard_defaults_on_and_can_be_disabled() {
3134 let default: Graph = toml::from_str("").unwrap();
3135 assert!(default.github_text_guard);
3136 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3137 assert!(!disabled.github_text_guard);
3138 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3139 assert!(!config.graph.github_text_guard);
3140 assert!(Config::starter_toml().contains("github_text_guard = true"));
3141 }
3142
3143 #[test]
3144 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3145 assert!(Graph::default().rerun_flaky_checks);
3146 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3147 assert!(!off.rerun_flaky_checks);
3148 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3149 }
3150
3151 #[test]
3152 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3153 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3158 assert_eq!(g.timeout_verify, None);
3159 assert_eq!(g.verify_timeout(), 3600);
3160 }
3161
3162 #[test]
3163 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3164 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3169 assert_eq!(g.timeout_review, 45);
3170 assert_eq!(
3171 g.verify_timeout(),
3172 45,
3173 "an omitted legacy value follows review"
3174 );
3175 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3176 .expect("parse explicit override");
3177 assert_eq!(explicit.verify_timeout(), 1200);
3178 }
3179
3180 #[test]
3181 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3182 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3183 assert_eq!(g.implementers, 4);
3184 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3185 assert_eq!(g.implementers, 5);
3186 }
3187
3188 fn layered(lower: &str, upper: &str) -> Result<Config> {
3189 let dir = tempfile::tempdir().unwrap();
3190 let a = dir.path().join("a.toml");
3191 let b = dir.path().join("b.toml");
3192 std::fs::write(&a, lower).unwrap();
3193 std::fs::write(&b, upper).unwrap();
3194 Config::load_layers(&[a, b])
3195 }
3196
3197 #[test]
3198 fn graph_implementers_higher_layer_wins_across_spellings() {
3199 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3200 assert_eq!(c.graph.implementers, 5);
3201 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3202 assert_eq!(c.graph.implementers, 5);
3203 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3204 assert_eq!(c.graph.implementers, 2);
3205 }
3206
3207 #[test]
3208 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3209 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3210 .unwrap_err()
3211 .to_string();
3212 assert!(
3213 err.contains("candidates") && err.contains("implementers"),
3214 "{err}"
3215 );
3216 assert!(err.contains("b.toml"), "{err}");
3217 }
3218
3219 #[test]
3220 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3221 let g: Graph =
3225 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3226 .expect("an old-shaped [graph] table must still parse");
3227 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3228 assert!(
3229 !g.e2e_every_round,
3230 "off by default, same as before this field existed"
3231 );
3232 }
3233
3234 #[test]
3235 fn empty_roles_rotate_judges_off_their_own_candidate() {
3236 let cfg = Config {
3239 agents: vec![spec("a"), spec("b"), spec("c")],
3240 graph: Graph {
3241 implementers: 3,
3242 ..Graph::default()
3243 },
3244 ..Config::default()
3245 };
3246 let roles = cfg.resolve_roles().unwrap();
3247 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3248 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3249 assert_eq!(impls, ["a", "b", "c"]);
3250 assert_eq!(judges, ["b", "c", "a"]);
3251 for (i, j) in judges.iter().enumerate() {
3252 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3253 }
3254 }
3255
3256 #[test]
3257 fn single_agent_roster_fills_every_seat() {
3258 let cfg = Config {
3259 agents: vec![spec("solo")],
3260 graph: Graph {
3261 implementers: 3,
3262 ..Graph::default()
3263 },
3264 ..Config::default()
3265 };
3266 let roles = cfg.resolve_roles().unwrap();
3267 assert_eq!(roles.implementers.len(), 3);
3268 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3269 }
3270
3271 #[test]
3272 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3273 let cfg = Config {
3278 agents: vec![spec("a"), spec("b"), spec("c")],
3279 graph: Graph {
3280 implementers: 1,
3281 ..Graph::default()
3282 },
3283 ..Config::default()
3284 };
3285 let roles = cfg.resolve_roles().unwrap();
3286 assert_eq!(roles.implementers.len(), 1);
3287 let roster: Vec<&str> = roles
3288 .implementer_roster
3289 .iter()
3290 .map(|a| a.id.as_str())
3291 .collect();
3292 assert_eq!(roster, ["a", "b", "c"]);
3293 }
3294
3295 #[test]
3296 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3297 let cfg = Config {
3298 agents: vec![spec("a"), spec("b"), spec("c")],
3299 roles: Roles {
3300 implementers: vec!["c".to_owned(), "a".to_owned()],
3301 ..Roles::default()
3302 },
3303 graph: Graph {
3304 implementers: 1,
3305 ..Graph::default()
3306 },
3307 ..Config::default()
3308 };
3309 let roles = cfg.resolve_roles().unwrap();
3310 assert_eq!(roles.implementers.len(), 1);
3312 assert_eq!(roles.implementers[0].id, "c");
3313 let roster: Vec<&str> = roles
3314 .implementer_roster
3315 .iter()
3316 .map(|a| a.id.as_str())
3317 .collect();
3318 assert_eq!(roster, ["c", "a"]);
3319 }
3320
3321 #[test]
3322 fn explicit_roles_win() {
3323 let cfg = Config {
3324 agents: vec![spec("a"), spec("b")],
3325 roles: Roles {
3326 implementers: vec!["b".to_owned()],
3327 judges: vec!["a".to_owned()],
3328 reviewers: Vec::new(),
3329 fixer: Some("a".into()),
3330 ..Roles::default()
3331 },
3332 ..Config::default()
3333 };
3334 let roles = cfg.resolve_roles().unwrap();
3335 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3336 assert!(roles.judges.iter().all(|a| a.id == "a"));
3337 let fixer = roles.fixer.unwrap();
3338 assert_eq!(fixer.len(), 1);
3339 assert_eq!(fixer[0].id, "a");
3340 assert_eq!(roles.conductor.id, "a");
3341 }
3342
3343 #[test]
3344 fn fixer_takes_a_string_or_an_ordered_chain() {
3345 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3346 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3347 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3348 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3349
3350 let resolve = |fixer: Option<AgentChoice>| {
3351 Config {
3352 agents: vec![spec("a"), spec("b"), spec("c")],
3353 roles: Roles {
3354 fixer,
3355 ..Roles::default()
3356 },
3357 ..Config::default()
3358 }
3359 .resolve_roles()
3360 };
3361 let ids = |r: &ResolvedRoles| -> Vec<String> {
3362 r.fixer
3363 .as_ref()
3364 .unwrap()
3365 .iter()
3366 .map(|s| s.id.clone())
3367 .collect()
3368 };
3369 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3371 assert!(resolve(None).unwrap().fixer.is_none());
3372 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3374 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3375 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3377 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3378 }
3379
3380 #[test]
3381 fn unknown_agent_id_is_an_error() {
3382 let cfg = Config {
3383 agents: vec![spec("a")],
3384 roles: Roles {
3385 judges: vec!["nope".to_owned()],
3386 ..Roles::default()
3387 },
3388 ..Config::default()
3389 };
3390 assert!(cfg.resolve_roles().is_err());
3391 }
3392
3393 #[test]
3394 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3395 let mut cfg = Config {
3396 agents: vec![spec("a"), spec("b")],
3397 ..Config::default()
3398 };
3399 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3400
3401 cfg.roles.conductor = Some("b".into());
3402 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3403
3404 cfg.roles.conductor = Some("missing".into());
3405 assert!(cfg.resolve_roles().is_err());
3406 }
3407
3408 #[test]
3409 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3410 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3411 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3412 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3413
3414 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3415 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3416 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3417
3418 for roles in [one, chain] {
3419 let text = toml::to_string(&roles).unwrap();
3420 let back: Roles = toml::from_str(&text).unwrap();
3421 assert_eq!(back.synthesizer, roles.synthesizer);
3422 assert_eq!(back.chatter, roles.chatter);
3423 }
3424 let text = toml::to_string(&Roles {
3425 conductor: Some("x".into()),
3426 ..Roles::default()
3427 })
3428 .unwrap();
3429 assert!(
3430 text.contains("conductor = \"x\""),
3431 "string stays a string: {text}"
3432 );
3433 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3434 }
3435
3436 #[test]
3437 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3438 for (text, ids) in [
3439 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3440 (
3441 r#"dupes_judge = ["first", "second"]"#,
3442 vec!["first", "second"],
3443 ),
3444 ("dupes_judge = []", vec![]),
3445 ] {
3446 let roles: Roles = toml::from_str(text).unwrap();
3447 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3448 let serialized = toml::to_string(&roles).unwrap();
3449 let back: Roles = toml::from_str(&serialized).unwrap();
3450 assert_eq!(back.dupes_judge, roles.dupes_judge);
3451 assert!(serialized.contains(text));
3452 }
3453 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3454 assert!(Roles::default().dupes_judge.is_none());
3455 assert!(Config::starter_toml().contains("# dupes_judge ="));
3456
3457 let mut cfg = Config {
3459 agents: vec![spec("a")],
3460 ..Config::default()
3461 };
3462 cfg.roles.dupes_judge = Some("missing".into());
3463 assert!(cfg.resolve_roles().is_ok());
3464 }
3465
3466 #[test]
3467 fn an_empty_choice_counts_as_unset() {
3468 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3469 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3470 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3471 }
3472
3473 #[test]
3474 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3475 let mut cfg = Config {
3481 agents: vec![spec("a"), spec("b")],
3482 ..Config::default()
3483 };
3484 let want = primary(cfg.roles.synthesizer.as_ref());
3485 assert_eq!(
3486 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3487 .unwrap()
3488 .id,
3489 "a",
3490 "unset falls back to agent::pick's own default order"
3491 );
3492
3493 cfg.roles.synthesizer = Some("b".into());
3494 let want = primary(cfg.roles.synthesizer.as_ref());
3495 assert_eq!(
3496 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3497 .unwrap()
3498 .id,
3499 "b",
3500 "the named agent wins over the default order"
3501 );
3502 }
3503
3504 #[test]
3505 fn empty_roster_is_an_error() {
3506 assert!(Config::default().resolve_roles().is_err());
3507 }
3508
3509 #[test]
3510 fn advise_defaults_to_on_with_three_proposals() {
3511 let g = Graph::default();
3512 assert!(g.advise);
3513 assert!(g.graft_runner_up, "graft is on by default");
3514 assert_eq!(g.advisors, 3);
3515 }
3516
3517 #[test]
3518 fn unset_advisors_falls_back_to_the_judge_roster() {
3519 let cfg = Config {
3520 agents: vec![spec("a"), spec("b")],
3521 roles: Roles {
3522 judges: vec!["b".to_owned()],
3523 ..Roles::default()
3524 },
3525 graph: Graph {
3526 advisors: 2,
3527 ..Graph::default()
3528 },
3529 ..Config::default()
3530 };
3531 let advisors = cfg.advisors().expect("advisors resolve");
3532 assert_eq!(advisors.len(), 2);
3533 assert!(
3534 advisors.iter().all(|a| a.id == "b"),
3535 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3536 );
3537 }
3538
3539 #[test]
3540 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3541 let cfg = Config {
3542 agents: vec![spec("a"), spec("b")],
3543 roles: Roles {
3544 judges: vec!["b".to_owned()],
3545 advisors: vec!["a".to_owned()],
3546 ..Roles::default()
3547 },
3548 graph: Graph {
3549 advisors: 2,
3550 ..Graph::default()
3551 },
3552 ..Config::default()
3553 };
3554 let advisors = cfg.advisors().expect("advisors resolve");
3555 assert!(advisors.iter().all(|a| a.id == "a"));
3556 }
3557
3558 #[test]
3564 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3565 let cfg = Config {
3566 agents: vec![spec("a"), spec("b"), spec("c")],
3567 graph: Graph {
3568 advisors: 3,
3569 judges: 3,
3570 ..Graph::default()
3571 },
3572 ..Config::default()
3573 };
3574 let advisors = cfg.advisors().expect("advisors resolve");
3575 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3576 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3577 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3578 assert_eq!(
3579 advisor_ids, judge_ids,
3580 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3581 );
3582 }
3583
3584 #[test]
3585 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3586 let cfg = Config {
3587 agents: vec![spec("a")],
3588 roles: Roles {
3589 advisors: vec!["nope".to_owned()],
3590 ..Roles::default()
3591 },
3592 graph: Graph {
3593 advisors: 1,
3594 ..Graph::default()
3595 },
3596 ..Config::default()
3597 };
3598 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3599 assert!(format!("{err:#}").contains("nope"));
3600 }
3601
3602 #[test]
3603 fn repos_default_to_no_roots_and_a_day_of_trust() {
3604 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3605 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3606 assert_eq!(Config::default().repos.fetch_interval, 600);
3607 }
3608
3609 #[test]
3610 fn a_config_file_with_no_repos_table_still_loads() {
3611 let dir = tempfile::tempdir().unwrap();
3612 let path = dir.path().join("magi.toml");
3613 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3614 let cfg = Config::load(&path).expect("must load without [repos]");
3615 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3616 assert_eq!(cfg.repos.scan_ttl, 86_400);
3617 }
3618
3619 #[test]
3634 fn a_test_build_does_not_read_the_operators_machine_config() {
3635 let repo = tempfile::tempdir().unwrap();
3636 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3637
3638 let layers = Config::layers(repo.path());
3639 assert_eq!(
3640 layers,
3641 vec![repo.path().join("magi.toml")],
3642 "only the fixture's own file may be a layer"
3643 );
3644 if let Some(real) = dirs::config_dir() {
3645 let machine = real.join("magi").join("config.toml");
3646 assert!(
3647 !layers.contains(&machine),
3648 "the operator's {} must not be a layer in a test build",
3649 machine.display()
3650 );
3651 }
3652 }
3653
3654 #[test]
3655 fn auto_upgrade_config_defaults_and_opt_in() {
3656 let default: Update = toml::from_str("").unwrap();
3657 assert!(!default.auto_restart);
3658 assert_eq!(default.mode, UpdateMode::Notify);
3659 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
3660 assert!(enabled.auto_restart);
3661 assert_eq!(enabled.interval.as_deref(), Some("2h"));
3662 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
3663 }
3664
3665 #[test]
3666 fn starter_toml_loads_through_teravars() {
3667 let dir = tempfile::tempdir().unwrap();
3668 let path = dir.path().join("magi.toml");
3669 std::fs::write(&path, Config::starter_toml()).unwrap();
3670 let parsed = Config::load(&path).expect("starter config must load");
3671 assert_eq!(parsed.graph.implementers, 3);
3672 assert_eq!(parsed.merge.mode, MergeMode::None);
3673 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3674 assert!(parsed.graph.sessions);
3675 assert!(parsed.graph.github_text_guard);
3676 assert_eq!(parsed.graph.timeout_review, 1200);
3677 assert_eq!(parsed.graph.verify_timeout(), 1200);
3678 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3679 }
3680
3681 #[test]
3682 fn release_defaults_to_actions_and_the_starter_documents_it() {
3683 let dir = tempfile::tempdir().unwrap();
3684 let path = dir.path().join("magi.toml");
3685 std::fs::write(&path, Config::starter_toml()).unwrap();
3686 let r = Config::load(&path).unwrap().release;
3687 assert_eq!(r.mode, ReleaseMode::Actions);
3688 assert!(!r.is_local());
3689 assert!(r.commands.is_empty());
3690 assert_eq!(r.timeout_minutes, 30);
3691 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3692 }
3693
3694 #[test]
3695 fn release_local_parses_and_unknown_keys_are_refused() {
3696 let dir = tempfile::tempdir().unwrap();
3697 let path = dir.path().join("magi.toml");
3698 std::fs::write(
3699 &path,
3700 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3701 )
3702 .unwrap();
3703 let r = Config::load(&path).unwrap().release;
3704 assert!(r.is_local());
3705 assert_eq!(r.commands.len(), 2);
3706 assert_eq!(r.timeout_minutes, 5);
3707 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3708 assert!(Config::load(&path).is_err());
3709 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3710 assert!(Config::load(&path).is_err());
3711 }
3712
3713 #[test]
3714 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3715 let dir = tempfile::tempdir().unwrap();
3716 let path = dir.path().join("magi.toml");
3717 std::fs::write(&path, Config::starter_toml()).unwrap();
3718 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3719 assert!(Config::starter_toml().contains("# pre_gate = []"));
3720 }
3721
3722 #[test]
3723 fn release_version_files_parse_default_empty_and_are_validated() {
3724 let dir = tempfile::tempdir().unwrap();
3725 let path = dir.path().join("magi.toml");
3726 std::fs::write(&path, "").unwrap();
3727 assert!(
3728 Config::load(&path)
3729 .unwrap()
3730 .release
3731 .version_files
3732 .is_empty()
3733 );
3734 std::fs::write(
3735 &path,
3736 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
3737 )
3738 .unwrap();
3739 let files = Config::load(&path).unwrap().release.version_files;
3740 assert_eq!(files.len(), 2);
3741 assert_eq!(files[1].kind, VersionKind::Json);
3742 for bad in [
3743 "{ path = \"package.json\", kind = \"json\" }",
3744 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
3745 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
3746 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
3747 ] {
3748 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
3749 assert!(Config::load(&path).is_err(), "{bad}");
3750 }
3751 assert!(Config::starter_toml().contains("# version_files = ["));
3752 }
3753
3754 #[test]
3755 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3756 let starter = Config::starter_toml();
3757 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3758 assert!(starter.contains("verification independent if timeout_review changes later"));
3759 assert!(starter.contains("# timeout_verify = 1200"));
3760 }
3761
3762 #[test]
3763 fn starter_toml_documents_chat_personas() {
3764 let starter = Config::starter_toml();
3765 assert!(starter.contains("# [[talk.personas]]"));
3766 assert!(starter.contains("tone only"));
3767 }
3768
3769 #[test]
3770 fn talk_personas_parse_and_are_validated() {
3771 let dir = tempfile::tempdir().unwrap();
3772 let path = dir.path().join("magi.toml");
3773 std::fs::write(
3774 &path,
3775 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3776 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3777 )
3778 .unwrap();
3779 let cfg = Config::load(&path).expect("loads");
3780 assert_eq!(cfg.talk.personas.len(), 2);
3781 let catalog = crate::persona::catalog(&cfg.talk.personas);
3782 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3783 assert_eq!(
3784 (rei.name.as_str(), rei.prompt.as_str()),
3785 ("Quiet", "Be brief.")
3786 );
3787 assert_eq!(catalog.last().unwrap().id, "gendo");
3788
3789 for (body, needle) in [
3790 (
3791 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3792 "empty `id`",
3793 ),
3794 (
3795 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3796 "empty `prompt`",
3797 ),
3798 (
3799 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3800 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3801 "more than once",
3802 ),
3803 (
3804 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3805 "cannot be redefined",
3806 ),
3807 ] {
3808 std::fs::write(&path, body).unwrap();
3809 let err = format!("{:#}", Config::load(&path).unwrap_err());
3810 assert!(err.contains(needle), "{needle}: {err}");
3811 }
3812 }
3813
3814 #[test]
3815 fn talk_operator_name_is_trimmed_and_validated() {
3816 let dir = tempfile::tempdir().unwrap();
3817 let path = dir.path().join("magi.toml");
3818 let load = |body: &str| {
3819 std::fs::write(&path, body).unwrap();
3820 Config::load(&path)
3821 };
3822 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3823 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3824 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3825 assert_eq!(blank.talk.operator_name(), None);
3826 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3827 let long = "x".repeat(65);
3828 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3829 }
3830
3831 #[test]
3832 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3833 let dir = tempfile::tempdir().unwrap();
3834 let load = |body: &str| {
3835 let path = dir.path().join("c.toml");
3836 std::fs::write(&path, body).unwrap();
3837 Config::load(&path)
3838 };
3839 let ok = load(
3840 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3841 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3842 )
3843 .unwrap();
3844 let c = crate::persona::catalog(&ok.talk.personas);
3845 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3846 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3847 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3848 let oversized = format!(
3849 "data:image/png;base64,{}",
3850 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3851 );
3852 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3853 for (id, fields) in [
3854 ("rei", ""),
3855 ("default", ""),
3856 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3857 ] {
3858 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3859 let cfg = load(&body).expect("bad icon must not invalidate config");
3860 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3861 assert_eq!(persona.id, id);
3862 assert!(crate::persona_icon::load(bad).is_err());
3863 }
3864 }
3865 let doc = Config::starter_toml();
3866 assert!(doc.contains("# icon = "));
3867 }
3868
3869 #[test]
3870 fn talk_personas_in_two_layers_are_refused() {
3871 let dir = tempfile::tempdir().unwrap();
3872 let machine = dir.path().join("machine.toml");
3873 let repo = dir.path().join("repo.toml");
3874 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3875 std::fs::write(&machine, one).unwrap();
3876 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3877 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3878 assert!(err.contains("talk.personas"), "{err}");
3879 }
3880
3881 #[test]
3882 fn starter_toml_documents_role_lists_as_backup_order() {
3883 let starter = Config::starter_toml();
3884 assert!(starter.contains("also an ordered backup list"));
3885 assert!(starter.contains("codex then sonnet are spares"));
3886 }
3887
3888 #[test]
3892 fn a_repository_can_declare_a_linear_history_merge_style() {
3893 let dir = tempfile::tempdir().unwrap();
3894 let path = dir.path().join("magi.toml");
3895 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3896 let parsed = Config::load(&path).expect("config must load");
3897 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3898 }
3899
3900 #[test]
3901 fn later_layers_win_and_vars_render() {
3902 let dir = tempfile::tempdir().unwrap();
3903 let machine = dir.path().join("machine.toml");
3904 let project = dir.path().join("magi.toml");
3905 std::fs::write(
3907 &machine,
3908 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3909 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3910 )
3911 .unwrap();
3912 std::fs::write(
3915 &project,
3916 "[vars]\ncache = \"/shared\"\n\n\
3917 [graph]\ncandidates = 2\n\n\
3918 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3919 )
3920 .unwrap();
3921
3922 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3923 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3924 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3925 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3926 assert_eq!(
3927 cfg.verify.gate,
3928 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3929 );
3930 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3932 }
3933
3934 #[test]
3935 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3936 let g = Graph::default();
3940 assert_eq!(g.timeout_talk, 3600);
3941
3942 let dir = tempfile::tempdir().unwrap();
3943 let path = dir.path().join("magi.toml");
3944 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3945 let cfg = Config::load(&path).expect("must load without timeout_talk set");
3946 assert_eq!(cfg.graph.timeout_talk, 3600);
3947 }
3948
3949 #[test]
3950 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
3951 let dir = tempfile::tempdir().unwrap();
3952 let path = dir.path().join("magi.toml");
3953 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
3954 let cfg = Config::load(&path).expect("must load");
3955 assert_eq!(cfg.graph.timeout_talk, 120);
3956 }
3957
3958 #[test]
3959 fn the_disk_defaults_are_the_measurements_made_up_front() {
3960 let cfg = Config::default();
3961 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
3962 assert!(cfg.disk.auto_fold);
3963 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
3964 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
3965 }
3966
3967 #[test]
3968 fn an_unset_disk_section_is_the_safe_default() {
3969 let dir = tempfile::tempdir().unwrap();
3970 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
3971 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
3972 assert_eq!(cfg.disk, Disk::default());
3973 }
3974
3975 #[test]
3976 fn env_is_available_to_templates_with_a_default() {
3977 let dir = tempfile::tempdir().unwrap();
3978 let path = dir.path().join("magi.toml");
3979 std::fs::write(
3987 &path,
3988 "[verify]\n\
3989 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
3990 \"populated={{ env | length > 0 }}\"]\n",
3991 )
3992 .unwrap();
3993 let cfg = Config::load(&path).expect("env lookup must render");
3994 assert_eq!(cfg.verify.gate[0], "cache=fallback");
3995 assert_eq!(cfg.verify.gate[1], "populated=true");
3996 }
3997
3998 #[test]
3999 fn a_broken_template_names_the_file() {
4000 let dir = tempfile::tempdir().unwrap();
4001 let path = dir.path().join("magi.toml");
4002 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
4003 let err = Config::load(&path).expect_err("must not silently ignore");
4004 assert!(err.to_string().contains("teravars"), "{err}");
4005 }
4006
4007 #[test]
4008 fn tera_syntax_in_comments_is_inert() {
4009 let dir = tempfile::tempdir().unwrap();
4013 let path = dir.path().join("magi.toml");
4014 std::fs::write(
4015 &path,
4016 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
4017 [graph]\ncandidates = 2\n",
4018 )
4019 .unwrap();
4020 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
4021 assert_eq!(cfg.graph.implementers, 2);
4022 }
4023
4024 #[test]
4025 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
4026 use std::time::Duration;
4027
4028 let mut s: AgentSpec =
4029 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
4030 let budget = Duration::from_millis(1500);
4031 assert_eq!(s.max_turn_secs, None);
4032 assert_eq!(s.turn_timeout(budget), budget);
4033 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
4034 for (cap, expected) in [
4035 (1, Duration::from_secs(1)),
4036 (2, budget),
4037 (0, Duration::ZERO),
4038 ] {
4039 s.max_turn_secs = Some(cap);
4040 let saved = toml::to_string(&s).unwrap();
4041 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
4042 assert_eq!(loaded.max_turn_secs, Some(cap));
4043 assert_eq!(loaded.turn_timeout(budget), expected);
4044 }
4045 }
4046
4047 #[test]
4048 fn opencode_defaults_to_file_delivery() {
4049 let mut s = spec("oc");
4050 s.kind = AgentKind::Opencode;
4051 assert_eq!(s.delivery(), Delivery::File);
4052 s.prompt_delivery = Some(Delivery::Argv);
4053 assert_eq!(s.delivery(), Delivery::Argv);
4054 }
4055 #[test]
4056 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
4057 let g = Graph::default();
4062 assert!(
4063 g.land,
4064 "stopping at an open PR left the watching to a human"
4065 );
4066 assert!(
4067 g.land_approval,
4068 "on-by-default land is only defensible while this is also on"
4069 );
4070 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
4071 assert!(
4072 g.hold_contested_merge,
4073 "a contested hand-off must still reach a human when approvals are off"
4074 );
4075 }
4076 #[test]
4077 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
4078 let dir = tempfile::tempdir().unwrap();
4082 let machine = dir.path().join("machine.toml");
4083 let repo = dir.path().join("magi.toml");
4084 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
4085 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
4086
4087 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4088 .expect_err("two layers naming one array must not merge silently");
4089 assert_eq!(
4090 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4091 "config-merge"
4092 );
4093 let err = err.to_string();
4094 assert!(err.contains("roles.implementers"), "{err}");
4095 assert!(err.contains("machine.toml"), "{err}");
4098 assert!(err.contains("magi.toml"), "{err}");
4099 }
4100
4101 #[test]
4102 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
4103 let dir = tempfile::tempdir().unwrap();
4106 let machine = dir.path().join("machine.toml");
4107 let repo = dir.path().join("magi.toml");
4108 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
4109 std::fs::write(
4110 &repo,
4111 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
4112 [roles]\nimplementers = [\"oc\"]\n",
4113 )
4114 .unwrap();
4115
4116 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
4117 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
4118 assert_eq!(cfg.roles.implementers, ["oc"]);
4119 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
4120 }
4121
4122 #[test]
4123 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
4124 let dir = tempfile::tempdir().unwrap();
4127 let machine = dir.path().join("machine.toml");
4128 let repo = dir.path().join("magi.toml");
4129 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4130 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4131
4132 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4133 assert_eq!(
4134 cfg.verify.gate,
4135 [
4136 "editorconfig-checker".to_owned(),
4137 "cargo make check".to_owned()
4138 ],
4139 "low-priority (machine) command first, high-priority (repo) command after"
4140 );
4141 }
4142
4143 fn load_one(body: &str) -> Result<Config> {
4144 let dir = tempfile::tempdir().unwrap();
4145 let path = dir.path().join("magi.toml");
4146 std::fs::write(&path, body).unwrap();
4147 Config::load_layers(&[path])
4148 }
4149
4150 #[test]
4151 fn worktree_setup_defaults_to_empty_and_parses_steps() {
4152 assert!(Config::default().worktree.setup.is_empty());
4153 let cfg = load_one(
4154 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
4155 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
4156 )
4157 .unwrap();
4158 assert_eq!(cfg.worktree.setup.len(), 3);
4159 assert!(cfg.worktree.setup[1].optional);
4160 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
4161 }
4162
4163 #[test]
4164 fn worktree_setup_rejects_malformed_steps() {
4165 for bad in [
4166 "{ copy = \"a\", run = \"b\" }",
4167 "{ optional = true }",
4168 "{ copy = \"a -> ../b\" }",
4169 "{ copy = \"a -> /abs\" }",
4170 "{ copy = \"a -> .git/config\" }",
4171 "{ run = \"b\", optional = true }",
4172 "{ copy = \"a\", timeout_secs = 3 }",
4173 "{ run = \"b\", bogus = 1 }",
4174 ] {
4175 let body = format!("[worktree]\nsetup = [{bad}]\n");
4176 assert!(load_one(&body).is_err(), "{bad}");
4177 }
4178 }
4179
4180 #[test]
4181 fn worktree_setup_in_two_layers_is_refused() {
4182 let dir = tempfile::tempdir().unwrap();
4183 let machine = dir.path().join("machine.toml");
4184 let repo = dir.path().join("magi.toml");
4185 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4186 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4187 assert!(Config::load_layers(&[machine, repo]).is_err());
4188 }
4189
4190 #[test]
4191 fn starter_toml_documents_worktree_setup() {
4192 let starter = Config::starter_toml();
4193 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4194 let body = starter.replace("# [worktree]", "[worktree]");
4196 let mut out = String::new();
4197 let mut live = false;
4198 for line in body.lines() {
4199 if line == "[worktree]" {
4200 live = true;
4201 } else if live && !line.starts_with("# ") {
4202 live = false;
4203 }
4204 out.push_str(&if live {
4205 line.replacen("# ", "", 1)
4206 } else {
4207 line.to_owned()
4208 });
4209 out.push('\n');
4210 }
4211 let cfg = load_one(&out).expect("uncommented example loads");
4212 assert_eq!(cfg.worktree.setup.len(), 3);
4213 }
4214
4215 #[test]
4216 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4217 let dir = tempfile::tempdir().unwrap();
4218 let machine = dir.path().join("machine.toml");
4219 let repo = dir.path().join("magi.toml");
4220 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4221 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4222
4223 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4224 assert_eq!(
4225 cfg.verify.e2e,
4226 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4227 );
4228 }
4229
4230 #[test]
4231 fn two_layers_declaring_repos_roots_are_both_scanned() {
4232 let dir = tempfile::tempdir().unwrap();
4233 let machine = dir.path().join("machine.toml");
4234 let repo = dir.path().join("magi.toml");
4235 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4236 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4237
4238 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4239 assert_eq!(
4240 cfg.repos.roots,
4241 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4242 );
4243 }
4244
4245 #[test]
4246 fn duplicate_gate_commands_across_layers_both_run() {
4247 let dir = tempfile::tempdir().unwrap();
4250 let machine = dir.path().join("machine.toml");
4251 let repo = dir.path().join("magi.toml");
4252 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4253 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4254
4255 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4256 assert_eq!(
4257 cfg.verify.gate,
4258 ["same-command".to_owned(), "same-command".to_owned()]
4259 );
4260 }
4261
4262 #[test]
4263 fn notify_command_is_still_refused_across_two_layers() {
4264 let dir = tempfile::tempdir().unwrap();
4266 let machine = dir.path().join("machine.toml");
4267 let repo = dir.path().join("magi.toml");
4268 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4269 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4270
4271 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4272 .expect_err("an argv split across layers must not concatenate");
4273 assert_eq!(
4274 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4275 "config-merge"
4276 );
4277 let err = err.to_string();
4278 assert!(err.contains("notify.command"), "{err}");
4279 assert!(err.contains("machine.toml"), "{err}");
4280 assert!(err.contains("magi.toml"), "{err}");
4281 }
4282
4283 #[test]
4284 fn one_layer_declaring_verify_gate_runs_unchanged() {
4285 let dir = tempfile::tempdir().unwrap();
4288 let path = dir.path().join("magi.toml");
4289 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4290
4291 let cfg = Config::load(&path).expect("single layer must still load");
4292 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4293 }
4294
4295 #[test]
4296 fn layered_parse_failures_name_the_failing_input() {
4297 let dir = tempfile::tempdir().unwrap();
4298 let a = dir.path().join("a.toml");
4299 let b = dir.path().join("b.toml");
4300 std::fs::write(&a, "[graph").unwrap();
4301 std::fs::write(&b, "[verify").unwrap();
4302 let paths = [a.clone(), b.clone()];
4303 let first = Config::load_layers(&paths).unwrap_err();
4304 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4305 assert_eq!(first_cause.stage, "config-parse");
4306 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4307 std::fs::write(&a, "").unwrap();
4308 let second = Config::load_layers(&paths).unwrap_err();
4309 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4310 assert_eq!(second_cause.stage, "config-parse");
4311 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4312 assert_ne!(first_cause.target, second_cause.target);
4313 }
4314
4315 #[test]
4316 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4317 let dir = tempfile::tempdir().unwrap();
4318 let machine = dir.path().join("machine.toml");
4319 let repo = dir.path().join("magi.toml");
4320 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4321 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4322 let paths = vec![machine.clone(), repo.clone()];
4323
4324 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4325 let described =
4326 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4327 assert!(described.contains("editorconfig-checker && cargo make check"));
4328 assert!(
4329 described.contains(&machine.display().to_string()),
4330 "{described}"
4331 );
4332 assert!(
4333 described.contains(&repo.display().to_string()),
4334 "{described}"
4335 );
4336
4337 let single = vec![repo.clone()];
4339 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4340 let solo_described =
4341 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4342 assert_eq!(solo_described, "cargo make check");
4343 }
4344
4345 mod remote_layers {
4346 use super::*;
4347
4348 fn git(dir: &Path, args: &[&str]) {
4349 use crate::proc::Quiet as _;
4350 let out = std::process::Command::new("git")
4351 .args(args)
4352 .quiet()
4353 .current_dir(dir)
4354 .output()
4355 .unwrap();
4356 assert!(out.status.success(), "git {args:?}: {out:?}");
4357 }
4358
4359 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4362 let tmp = tempfile::tempdir().unwrap();
4363 let bare = tmp.path().join("o.git");
4364 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4365 let repo = tmp.path().join("repo");
4366 std::fs::create_dir_all(&repo).unwrap();
4367 git(&repo, &["init", "-b", "trunk"]);
4368 git(&repo, &["config", "user.name", "t"]);
4369 git(&repo, &["config", "user.email", "t@example.com"]);
4370 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4371 git(&repo, &["add", "-A"]);
4372 git(&repo, &["commit", "-m", "x"]);
4373 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4374 git(&repo, &["push", "origin", "trunk"]);
4375 git(&repo, &["fetch", "origin"]);
4376 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4377 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4378 (tmp, repo)
4379 }
4380
4381 #[tokio::test]
4382 async fn branch_owner_holds_only_add_literal_true_values() {
4383 for (text, expected) in [
4384 ("[graph]\nland_approval = true\n", true),
4385 ("[graph]\nland_approval = false\n", false),
4386 ("[graph]\nland = true\n", false),
4387 ("[graph\n", false),
4388 ("[graph]\nland_approval = \"yes\"\n", false),
4389 ("[graph]\nland_approval = 1\n", false),
4390 ] {
4391 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4392 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4393 let (holds, _) = branch_owner_holds(&repo, &head).await;
4394 assert_eq!(
4395 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4396 expected
4397 );
4398 assert!(
4399 !holds
4400 .iter()
4401 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4402 );
4403 for base in [false, true] {
4404 let mut cfg = Config::default();
4405 cfg.graph.land_approval = base;
4406 let mut state = crate::run::RunState::new(
4407 repo.clone(),
4408 "trunk".into(),
4409 head.clone(),
4410 "review".into(),
4411 cfg,
4412 );
4413 state.observe_branch_owner_holds(&head).await;
4414 assert!(
4415 state.branch_owner_holds.is_empty(),
4416 "competition candidates are excluded"
4417 );
4418 state.reviewed_commits = Some(Vec::new());
4419 state.observe_branch_owner_holds(&head).await;
4420 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4421 }
4422 }
4423 }
4424
4425 #[tokio::test]
4426 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4427 let (_tmp, repo) = fixture(
4428 "[graph]\nland_approval = true\n",
4429 "[graph]\nland_approval = true\n",
4430 );
4431 git(&repo, &["rm", "magi.toml"]);
4432 std::fs::create_dir(repo.join(".magi")).unwrap();
4433 std::fs::write(
4434 repo.join(".magi/config.toml"),
4435 "[graph]\nhold_contested_merge = true\n",
4436 )
4437 .unwrap();
4438 git(&repo, &["add", "."]);
4439 git(&repo, &["commit", "-m", "nested hold"]);
4440 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4441 let (holds, _) = branch_owner_holds(&repo, &head).await;
4442 assert_eq!(
4443 holds,
4444 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4445 );
4446 let (holds, diagnostics) =
4447 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4448 assert!(holds.is_empty());
4449 assert!(!diagnostics.is_empty());
4450 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4451 assert!(holds.is_empty());
4452 assert!(!diagnostics.is_empty());
4453 for base in [false, true] {
4454 let mut cfg = Config::default();
4455 cfg.graph.land_approval = base;
4456 let mut state = crate::run::RunState::new(
4457 repo.clone(),
4458 "trunk".into(),
4459 head.clone(),
4460 "review".into(),
4461 cfg,
4462 );
4463 state.reviewed_commits = Some(Vec::new());
4464 state.observe_branch_owner_holds(&head).await;
4465 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4466 state
4467 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4468 .await;
4469 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4470 }
4471 }
4472
4473 #[test]
4474 fn reads_the_remote_blob_not_the_working_tree() {
4475 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4476 let (cfg, _) = Config::discover(&repo, None).unwrap();
4477 assert_eq!(cfg.graph.implementers, 2);
4478 }
4479
4480 #[test]
4481 fn detached_head_still_reads_the_remote() {
4482 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4483 git(&repo, &["checkout", "--detach"]);
4484 let (cfg, _) = Config::discover(&repo, None).unwrap();
4485 assert_eq!(cfg.graph.implementers, 2);
4486 }
4487
4488 #[test]
4489 fn a_missing_ref_is_an_error_not_a_fallback() {
4490 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4491 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4492 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4493 assert!(err.contains("origin"), "{err}");
4494 }
4495
4496 #[test]
4497 fn merge_base_in_the_checkout_locates_the_ref() {
4498 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4499 assert!(Config::discover(&repo, None).is_err());
4500 }
4501
4502 #[test]
4503 fn the_magi_dir_layer_is_read_too() {
4504 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4505 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4506 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4507 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4508 git(&repo, &["add", "-A"]);
4509 git(&repo, &["commit", "-m", "y"]);
4510 git(&repo, &["push", "origin", "trunk"]);
4511 git(&repo, &["fetch", "origin"]);
4512 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4513 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4514 assert_eq!(layers.len(), 2);
4515 }
4516
4517 #[test]
4518 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4519 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4520 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4521 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4522 git(&repo, &["add", "-A"]);
4523 git(&repo, &["commit", "-m", "inc"]);
4524 git(&repo, &["push", "origin", "trunk"]);
4525 git(&repo, &["fetch", "origin"]);
4526 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4528 let (cfg, _) = Config::discover(&repo, None).unwrap();
4529 assert_eq!(cfg.graph.implementers, 2);
4530 }
4531
4532 #[test]
4533 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4534 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4535 let m = t.path().join("machine.toml");
4536 std::fs::write(
4537 &m,
4538 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4539 )
4540 .unwrap();
4541 let (remote, base) = {
4542 let probe = probe_merge(&m, &repo).unwrap();
4543 (probe.remote, probe.base)
4544 };
4545 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4546 }
4547
4548 #[test]
4549 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4550 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4551 let m = t.path().join("machine.toml");
4552 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4553 let probe = probe_merge(&m, &repo).unwrap();
4554 assert_eq!(probe.base.as_deref(), Some("repo"));
4555 }
4556
4557 #[test]
4558 fn every_include_form_is_recognised() {
4559 assert!(declares_include("include = [\"a.toml\"]\n"));
4560 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4561 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4562 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4563 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4564 }
4565
4566 #[test]
4567 fn an_explicit_config_is_read_as_named() {
4568 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4569 let own = t.path().join("own.toml");
4570 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4571 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4572 assert_eq!(cfg.graph.implementers, 4);
4573 }
4574
4575 #[test]
4576 fn discover_fetched_fails_when_the_fetch_does() {
4577 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4578 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4579 let rt = tokio::runtime::Builder::new_current_thread()
4580 .enable_all()
4581 .build()
4582 .unwrap();
4583 let err = rt
4584 .block_on(Config::discover_fetched(&repo, None))
4585 .unwrap_err();
4586 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4587 }
4588
4589 #[test]
4590 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4591 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4592 let remote = tmp.path().join("o.git");
4593 let offline = tmp.path().join("offline.git");
4594 std::fs::rename(&remote, &offline).unwrap();
4595 let rt = tokio::runtime::Builder::new_current_thread()
4596 .enable_all()
4597 .build()
4598 .unwrap();
4599 let fetch = rt
4600 .block_on(Config::discover_fetched(&repo, None))
4601 .unwrap_err();
4602 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4603 assert_eq!(fetch_cause.stage, "config-fetch");
4604 assert_eq!(fetch_cause.target, "origin/trunk");
4605
4606 std::fs::rename(&offline, &remote).unwrap();
4607 let parse = rt
4608 .block_on(Config::discover_fetched(&repo, None))
4609 .unwrap_err();
4610 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4611 assert_eq!(parse_cause.stage, "config-parse");
4612 assert!(parse_cause.target.contains("magi.toml"));
4613 assert!(
4614 !parse_cause.target.contains("/magi/config/"),
4615 "cache commit paths are incidental"
4616 );
4617 assert_ne!(fetch_cause.stage, parse_cause.stage);
4618 }
4619
4620 #[test]
4621 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4622 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4625 git(&repo, &["remote", "set-head", "origin", "-d"]);
4626 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4627 git(
4628 &repo,
4629 &["config", "remote.origin.followRemoteHEAD", "never"],
4630 );
4631 let rt = tokio::runtime::Builder::new_current_thread()
4632 .enable_all()
4633 .build()
4634 .unwrap();
4635 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4636 assert_eq!(cfg.graph.implementers, 2);
4637 }
4638
4639 #[test]
4640 fn a_non_git_directory_reads_its_files() {
4641 let dir = tempfile::tempdir().unwrap();
4642 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4643 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4644 assert_eq!(cfg.graph.implementers, 4);
4645 }
4646 }
4647
4648 #[test]
4649 fn github_language_defaults_to_english_and_accepts_japanese() {
4650 let default: Graph = toml::from_str("").unwrap();
4651 assert_eq!(default.github_language, "en");
4652 assert!(default.github_english() && default.language_gate());
4653 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4654 assert!(!ja.github_english() && !ja.language_gate());
4655 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4657 assert!(only_ops.language_gate());
4658 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4659 assert!(!off.language_gate() && off.github_english());
4660 assert!(Config::starter_toml().contains("github_language = \"en\""));
4661 }
4662}