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, Deserialize, Serialize)]
990#[serde(deny_unknown_fields, default)]
991pub struct Merge {
992 pub mode: MergeMode,
995 pub base: Option<String>,
997 pub style: MergeStyle,
1000 pub remote: String,
1002 pub release_bump: bool,
1015}
1016
1017impl Default for Merge {
1018 fn default() -> Self {
1019 Self {
1020 mode: MergeMode::None,
1021 base: None,
1022 style: MergeStyle::default(),
1023 remote: "origin".to_owned(),
1024 release_bump: true,
1025 }
1026 }
1027}
1028
1029#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1031#[serde(rename_all = "lowercase")]
1032pub enum UpdateMode {
1033 Off,
1035 Notify,
1038 Install,
1040}
1041
1042#[derive(Debug, Clone, Deserialize, Serialize)]
1044#[serde(deny_unknown_fields, default)]
1045pub struct Update {
1046 pub mode: UpdateMode,
1048 pub interval: Option<String>,
1050}
1051
1052impl Default for Update {
1053 fn default() -> Self {
1054 Self {
1055 mode: UpdateMode::Notify,
1056 interval: None,
1057 }
1058 }
1059}
1060
1061#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1063#[serde(rename_all = "lowercase")]
1064pub enum ReleaseMode {
1065 #[default]
1068 Actions,
1069 Local,
1073}
1074
1075#[derive(Debug, Clone, Deserialize, Serialize)]
1077#[serde(deny_unknown_fields, default)]
1078pub struct Release {
1079 pub mode: ReleaseMode,
1082 pub commands: Vec<String>,
1089 pub timeout_minutes: u64,
1091 pub version_files: Vec<VersionFile>,
1099}
1100
1101#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1103#[serde(rename_all = "lowercase")]
1104pub enum VersionKind {
1105 Cargo,
1107 Json,
1109}
1110
1111#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1113#[serde(deny_unknown_fields)]
1114pub struct VersionFile {
1115 pub path: String,
1117 pub kind: VersionKind,
1119}
1120
1121impl Default for Release {
1122 fn default() -> Self {
1123 Self {
1124 mode: ReleaseMode::Actions,
1125 commands: Vec::new(),
1126 timeout_minutes: 30,
1127 version_files: Vec::new(),
1128 }
1129 }
1130}
1131
1132impl Release {
1133 pub fn validate(&self) -> Result<()> {
1135 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1136 }
1137
1138 pub fn is_local(&self) -> bool {
1140 self.mode == ReleaseMode::Local
1141 }
1142}
1143
1144#[derive(Debug, Clone, Deserialize, Serialize)]
1146#[serde(try_from = "CoordinationFields")]
1147pub struct Coordination {
1148 pub contract_file: String,
1150 pub contract_token: String,
1152 pub lock_file: String,
1154}
1155
1156#[derive(Deserialize, Default)]
1157#[serde(deny_unknown_fields, default)]
1158struct CoordinationFields {
1159 contract_file: String,
1160 contract_token: String,
1161 lock_file: String,
1162}
1163
1164impl TryFrom<CoordinationFields> for Coordination {
1165 type Error = anyhow::Error;
1166
1167 fn try_from(fields: CoordinationFields) -> Result<Self> {
1168 for (key, name) in [
1169 ("coordination.contract_file", &fields.contract_file),
1170 ("coordination.lock_file", &fields.lock_file),
1171 ] {
1172 if name.trim().is_empty()
1173 || name != name.trim()
1174 || name == "."
1175 || name.contains("..")
1176 || name.contains(['/', '\\', ':', '\0'])
1177 {
1178 bail!(
1179 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1180 );
1181 }
1182 }
1183 let token = &fields.contract_token;
1184 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1185 bail!(
1186 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1187 );
1188 }
1189 Ok(Self {
1190 contract_file: fields.contract_file,
1191 contract_token: fields.contract_token,
1192 lock_file: fields.lock_file,
1193 })
1194 }
1195}
1196
1197#[cfg(test)]
1198pub(crate) fn test_coordination() -> Option<Coordination> {
1199 Some(Coordination {
1200 contract_file: "updater.contract".into(),
1201 contract_token: "test-protocol-v1".into(),
1202 lock_file: "updater.lock".into(),
1203 })
1204}
1205
1206#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1208#[serde(deny_unknown_fields, default)]
1209pub struct Config {
1210 pub coordination: Option<Coordination>,
1212 pub agents: Vec<AgentSpec>,
1214 pub roles: Roles,
1216 pub graph: Graph,
1218 pub blind: Blind,
1220 pub verify: Verify,
1222 pub worktree: Worktree,
1224 pub disk: Disk,
1226 pub merge: Merge,
1228 pub update: Update,
1230 pub prompts: Prompts,
1232 pub notify: Notify,
1234 pub repos: Repos,
1237 pub talk: Talk,
1239 pub daemon: Daemon,
1241 pub release: Release,
1243 pub context_windows: BTreeMap<String, u64>,
1246}
1247
1248const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1258 ("claude-opus-4", 200_000),
1259 ("claude-sonnet-4", 200_000),
1260 ("claude-haiku-4", 200_000),
1261 ("claude-3", 200_000),
1262 ("opus", 200_000),
1263 ("sonnet", 200_000),
1264 ("haiku", 200_000),
1265 ("gpt-5", 400_000),
1266 ("gpt-4.1", 1_000_000),
1267 ("gpt-4o", 128_000),
1268 ("o3", 200_000),
1269 ("o4-mini", 200_000),
1270 ("gemini-2.5", 1_000_000),
1271 ("deepseek", 128_000),
1272];
1273
1274impl Config {
1275 pub fn context_window(&self, model: &str) -> Option<u64> {
1280 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1281 let mut best: Option<(usize, u64)> = None;
1282 for (key, window) in entries {
1283 if key == model {
1284 return Some(window);
1285 }
1286 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1287 best = Some((key.len(), window));
1288 }
1289 }
1290 best.map(|(_, w)| w)
1291 }
1292 lookup(
1293 model,
1294 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1295 )
1296 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1297 }
1298}
1299
1300#[derive(Debug, Clone, Deserialize, Serialize)]
1310#[serde(deny_unknown_fields, default)]
1311pub struct Daemon {
1312 pub max_concurrent_runs: usize,
1333 pub pause_for_interrupts: bool,
1349 pub max_deputies: usize,
1356 pub release_stall_minutes: u64,
1363}
1364
1365impl Default for Daemon {
1366 fn default() -> Self {
1367 Self {
1368 max_concurrent_runs: 1,
1369 pause_for_interrupts: false,
1370 max_deputies: 2,
1371 release_stall_minutes: 60,
1372 }
1373 }
1374}
1375
1376#[derive(Debug, Clone, Deserialize, Serialize)]
1388#[serde(deny_unknown_fields, default)]
1389pub struct Repos {
1390 pub roots: Vec<PathBuf>,
1394 pub scan_ttl: u64,
1401 pub fetch_interval: u64,
1406}
1407
1408impl Default for Repos {
1409 fn default() -> Self {
1410 Self {
1411 roots: Vec::new(),
1412 scan_ttl: 86_400,
1413 fetch_interval: 600,
1414 }
1415 }
1416}
1417
1418#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1434#[serde(deny_unknown_fields, default)]
1435pub struct Prompts {
1436 pub all: String,
1438 pub implement: String,
1440 pub judge: String,
1442 pub review: String,
1444 pub fix: String,
1446}
1447
1448impl Prompts {
1449 pub fn overlay(&self, node: &str) -> Option<String> {
1454 let specific = match node {
1455 "implement" => &self.implement,
1456 "judge" | "vote" | "deliberate" => &self.judge,
1457 "review" => &self.review,
1458 "fix" => &self.fix,
1459 _ => "",
1460 };
1461 let mut parts: Vec<&str> = Vec::new();
1462 for p in [self.all.trim(), specific.trim()] {
1463 if !p.is_empty() {
1464 parts.push(p);
1465 }
1466 }
1467 if parts.is_empty() {
1468 return None;
1469 }
1470 Some(parts.join("\n\n"))
1471 }
1472}
1473
1474#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1481#[serde(deny_unknown_fields, default)]
1482pub struct Notify {
1483 pub command: Vec<String>,
1486}
1487
1488#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1490#[serde(deny_unknown_fields, default)]
1491pub struct Talk {
1492 pub allow_write: bool,
1501 pub personas: Vec<PersonaSpec>,
1506 pub operator_name: Option<String>,
1510}
1511
1512pub const OPERATOR_NAME_MAX: usize = 64;
1514
1515impl Talk {
1516 pub fn operator_name(&self) -> Option<&str> {
1518 self.operator_name
1519 .as_deref()
1520 .map(str::trim)
1521 .filter(|n| !n.is_empty())
1522 }
1523}
1524
1525#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1527#[serde(deny_unknown_fields)]
1528pub struct PersonaSpec {
1529 pub id: String,
1531 #[serde(default)]
1534 pub name: String,
1535 #[serde(default)]
1538 pub prompt: String,
1539 #[serde(default, skip_serializing_if = "Option::is_none")]
1543 pub icon: Option<String>,
1544}
1545
1546#[derive(Debug, Clone)]
1548pub struct ResolvedRoles {
1549 pub implementers: Vec<AgentSpec>,
1551 pub judges: Vec<AgentSpec>,
1553 pub reviewers: Vec<AgentSpec>,
1555 pub fixer: Option<Vec<AgentSpec>>,
1560 pub conductor: AgentSpec,
1562 pub implementer_roster: Vec<AgentSpec>,
1570 pub judge_roster: Vec<AgentSpec>,
1574 pub reviewer_roster: Vec<AgentSpec>,
1576}
1577
1578fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1585 let mut out = Vec::new();
1586 for (k, v) in table {
1587 if prefix.is_empty() && k == "vars" {
1588 continue;
1589 }
1590 let path = if prefix.is_empty() {
1591 k.clone()
1592 } else {
1593 format!("{prefix}.{k}")
1594 };
1595 match v {
1596 toml::Value::Array(_) => out.push(path),
1597 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1598 _ => {}
1599 }
1600 }
1601 out
1602}
1603
1604#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1606enum ArrayMerge {
1607 Append,
1611 Replace,
1614}
1615
1616fn array_merge_policy(key: &str) -> ArrayMerge {
1655 match key {
1656 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1657 _ => ArrayMerge::Replace,
1658 }
1659}
1660
1661impl Config {
1662 pub fn load(path: &Path) -> Result<Self> {
1665 Self::load_layers(&[path.to_path_buf()])
1666 }
1667
1668 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1678 let mut ctx = teravars::system_context();
1679 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1680 ctx.insert("env", &env);
1681 if let Some(last) = paths.last()
1682 && let Some(dir) = last.parent()
1683 {
1684 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1687 .map(|s| PathBuf::from(s.trim()))
1688 .unwrap_or_else(|_| dir.to_path_buf());
1689 ctx.insert("repo", &dir.to_string_lossy());
1690 ctx.insert(
1691 "repo_name",
1692 &dir.file_name().unwrap_or_default().to_string_lossy(),
1693 );
1694 }
1695 ctx
1696 }
1697
1698 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1706 let mut engine = teravars::Engine::default();
1707 let ctx = Self::render_ctx(paths);
1708 if paths.len() > 1 {
1709 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1710 if error.downcast_ref::<ConfigFailure>().is_some() {
1711 error
1712 } else {
1713 let message = error.to_string();
1716 error
1717 .context(ConfigFailure::layers("config-merge", paths))
1718 .context(message)
1719 }
1720 })?;
1721 }
1722 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1723 .map_err(|error| {
1724 let cause = ConfigFailure::render(&error, paths);
1725 anyhow::Error::new(error).context(cause)
1726 })
1727 .with_context(|| {
1728 format!(
1729 "rendering config via teravars: {}",
1730 paths
1731 .iter()
1732 .map(|p| p.display().to_string())
1733 .collect::<Vec<_>>()
1734 .join(", ")
1735 )
1736 })?;
1737 let mut table = merged.config;
1738 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1739 table.remove("vars");
1742 let detect_agents = !table.contains_key("agents");
1746 let mut cfg: Self = toml::Value::Table(table)
1747 .try_into()
1748 .context("deserializing magi config")
1749 .context(ConfigFailure::layers("config-deserialize", paths))?;
1750 crate::persona::validate(&cfg.talk.personas)?;
1751 cfg.worktree.validate()?;
1752 cfg.release.validate()?;
1753 if let Some(name) = cfg.talk.operator_name() {
1754 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1755 bail!(
1756 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1757 );
1758 }
1759 }
1760 if detect_agents {
1761 cfg.agents = Self::autodetected().agents;
1762 }
1763 Ok(cfg)
1764 }
1765
1766 fn normalize_renamed_keys(
1774 paths: &[PathBuf],
1775 engine: &mut teravars::Engine,
1776 ctx: &teravars::Context,
1777 table: &mut toml::map::Map<String, toml::Value>,
1778 ) -> Result<()> {
1779 let both = matches!(
1780 table.get("graph"),
1781 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1782 );
1783 if !both {
1784 return Ok(());
1785 }
1786 let mut winner: Option<toml::Value> = None;
1787 for path in paths {
1788 let one = teravars::load_merged([path], engine, ctx)
1789 .map_err(|error| {
1790 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1791 anyhow::Error::new(error).context(cause)
1792 })
1793 .with_context(|| format!("rendering {}", path.display()))?;
1794 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1795 continue;
1796 };
1797 if g.contains_key("candidates") && g.contains_key("implementers") {
1798 bail!(
1799 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1800 path.display()
1801 );
1802 }
1803 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1804 winner = Some(v.clone());
1805 }
1806 }
1807 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1808 g.remove("candidates");
1809 if let Some(v) = winner {
1810 g.insert("implementers".to_owned(), v);
1811 }
1812 }
1813 Ok(())
1814 }
1815
1816 fn refuse_split_arrays(
1840 paths: &[PathBuf],
1841 engine: &mut teravars::Engine,
1842 ctx: &teravars::Context,
1843 ) -> Result<()> {
1844 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1845 for path in paths {
1846 let one = teravars::load_merged([path], engine, ctx)
1847 .map_err(|error| {
1848 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1849 anyhow::Error::new(error).context(cause)
1850 })
1851 .with_context(|| format!("rendering {}", path.display()))?;
1852 for key in array_keys(&one.config, "") {
1853 if array_merge_policy(&key) == ArrayMerge::Append {
1854 continue;
1855 }
1856 if let Some(first) = seen.get(&key) {
1857 bail!(
1858 "`{key}` is an array declared in two config layers:\n \
1859 {}\n {}\nteravars appends arrays when it merges, so \
1860 magi would run the concatenation of both - which is \
1861 not what either file says. Declare `{key}` in exactly \
1862 one of them.",
1863 first.display(),
1864 path.display()
1865 );
1866 }
1867 seen.insert(key, path.clone());
1868 }
1869 }
1870 Ok(())
1871 }
1872
1873 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1895 let mut engine = teravars::Engine::default();
1896 let ctx = Self::render_ctx(paths);
1897 let mut out = Vec::new();
1898 for path in paths {
1899 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1900 continue;
1901 };
1902 let mut cur = &one.config;
1903 let mut found = None;
1904 let parts: Vec<&str> = key.split('.').collect();
1905 for (i, part) in parts.iter().enumerate() {
1906 match cur.get(*part) {
1907 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1908 found = Some(a);
1909 break;
1910 }
1911 Some(toml::Value::Table(t)) => cur = t,
1912 _ => break,
1913 }
1914 }
1915 let Some(values) = found else { continue };
1916 let strings: Vec<String> = values
1917 .iter()
1918 .filter_map(|v| v.as_str().map(str::to_owned))
1919 .collect();
1920 if !strings.is_empty() {
1921 out.push((path.clone(), strings));
1922 }
1923 }
1924 out
1925 }
1926
1927 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1933 let mut engine = teravars::Engine::default();
1934 let ctx = Self::render_ctx(paths);
1935 paths
1936 .iter()
1937 .map(|path| {
1938 let one = teravars::load_merged([path], &mut engine, &ctx)
1939 .map(|m| m.config)
1940 .with_context(|| format!("rendering {}", path.display()));
1941 (path.clone(), one)
1942 })
1943 .collect()
1944 }
1945
1946 pub fn describe_composed(
1956 paths: &[PathBuf],
1957 commands: &[String],
1958 key: &str,
1959 empty: &str,
1960 ) -> String {
1961 if commands.is_empty() {
1962 return empty.to_owned();
1963 }
1964 let joined = commands.join(" && ");
1965 let provenance = Self::array_provenance(paths, key);
1966 if provenance.len() <= 1 {
1967 return joined;
1968 }
1969 let mut out = joined;
1970 for (path, cmds) in &provenance {
1971 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1972 }
1973 out
1974 }
1975
1976 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1983 #[cfg(test)]
1984 crate::web::request_cost::discovery();
1985 if let Some(p) = explicit {
1986 let paths = vec![p.to_path_buf()];
1987 return Ok((Self::load_layers(&paths)?, paths));
1988 }
1989 let paths = Self::layers_checked(repo)?;
1990 if paths.is_empty() {
1991 return Ok((Self::autodetected(), paths));
1992 }
1993 Ok((Self::load_layers(&paths)?, paths))
1994 }
1995
1996 pub async fn discover_fetched(
1999 repo: &Path,
2000 explicit: Option<&Path>,
2001 ) -> Result<(Self, Vec<PathBuf>)> {
2002 if explicit.is_none() && is_git_worktree(repo) {
2003 let (remote, cfg_base) = probe_remote_base(repo);
2007 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2008 .await
2009 .with_context(|| ConfigFailure {
2010 stage: "config-base",
2011 target: remote.clone(),
2012 })?;
2013 let out = crate::git::fetch(repo, &remote, &base)
2014 .await
2015 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2016 .with_context(|| ConfigFailure {
2017 stage: "config-fetch",
2018 target: format!("{remote}/{base}"),
2019 })?;
2020 if !out.ok() {
2021 return Err(anyhow::anyhow!(
2022 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2023 out.stderr.lines().next().unwrap_or("").trim()
2024 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2025 }
2026 if cfg_base.is_none() {
2027 crate::git::ensure_remote_head(repo, &remote, &base).await;
2028 }
2029 }
2030 Self::discover(repo, explicit).map_err(|error| {
2031 if error.downcast_ref::<ConfigFailure>().is_some() {
2032 error
2033 } else {
2034 error.context(ConfigFailure {
2035 stage: "config-load",
2036 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2037 })
2038 }
2039 })
2040 }
2041
2042 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2044 if !is_git_worktree(repo) {
2045 return Ok(Self::layers(repo));
2046 }
2047 let mut paths: Vec<PathBuf> = Self::machine_layer()
2048 .into_iter()
2049 .filter(|p| p.is_file())
2050 .collect();
2051 paths.extend(Self::repo_layers(repo)?);
2052 Ok(paths)
2053 }
2054
2055 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2057 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2058 if let Some(root) = cached {
2059 let relative = path.strip_prefix(root).unwrap_or(path);
2060 let reference = resolve_remote_base(repo)
2061 .map(|(remote, base)| format!("{remote}/{base}"))
2062 .unwrap_or_else(|_| "remote base".to_owned());
2063 format!(
2064 "{} at {reference} (including its includes)",
2065 repo.join(relative).display()
2066 )
2067 } else {
2068 format!("{} (including its includes)", path.display())
2069 }
2070 }
2071
2072 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2075 if !is_git_worktree(repo) {
2076 return Ok([
2077 repo.join(".magi").join("config.toml"),
2078 repo.join("magi.toml"),
2079 ]
2080 .into_iter()
2081 .filter(|p| p.is_file())
2082 .collect());
2083 }
2084 remote_layers(repo)
2085 }
2086
2087 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2107
2108 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2113 let mut paths = Vec::new();
2114 paths.extend(Self::machine_layer());
2115 paths.push(repo.join(".magi").join("config.toml"));
2116 paths.push(repo.join("magi.toml"));
2117 paths.retain(|p| p.is_file());
2118 paths
2119 }
2120
2121 #[cfg(test)]
2128 pub(crate) fn machine_layer() -> Option<PathBuf> {
2129 std::env::var(Self::CONFIG_DIR_ENV)
2130 .ok()
2131 .filter(|dir| !dir.trim().is_empty())
2132 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2133 }
2134
2135 #[cfg(not(test))]
2137 pub(crate) fn machine_layer() -> Option<PathBuf> {
2138 match std::env::var(Self::CONFIG_DIR_ENV) {
2139 Ok(dir) if dir.trim().is_empty() => None,
2141 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2142 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2143 }
2144 }
2145
2146 pub fn autodetected() -> Self {
2148 let mut cfg = Self::default();
2149 for (kind, id, model) in [
2150 (AgentKind::Claude, "opus", Some("opus")),
2151 (AgentKind::Claude, "sonnet", Some("sonnet")),
2152 (AgentKind::Antigravity, "antigravity", None),
2153 (AgentKind::Opencode, "opencode", None),
2154 (AgentKind::Codex, "codex", None),
2155 (AgentKind::Omp, "omp", None),
2156 ] {
2157 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2158 cfg.agents.push(AgentSpec {
2159 id: id.to_owned(),
2160 kind,
2161 model: model.map(str::to_owned),
2162 command: Vec::new(),
2163 extra_args: Vec::new(),
2164 env: BTreeMap::new(),
2165 prompt_delivery: None,
2166 max_turn_secs: None,
2167 });
2168 }
2169 }
2170 cfg
2171 }
2172
2173 pub fn cache_dir(&self) -> Option<PathBuf> {
2176 self.verify.cache_dir()
2177 }
2178
2179 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2181 self.agents
2182 .iter()
2183 .find(|a| a.id == id)
2184 .with_context(|| format!("no agent with id `{id}` in the roster"))
2185 }
2186
2187 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2194 let mut out = Vec::with_capacity(count);
2195 for i in 0..count {
2196 let spec = if ids.is_empty() {
2197 self.agents[(i + offset) % self.agents.len()].clone()
2198 } else {
2199 self.agent(&ids[i % ids.len()])?.clone()
2200 };
2201 out.push(spec);
2202 }
2203 Ok(out)
2204 }
2205
2206 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2213 if ids.is_empty() {
2214 Ok(self.agents.clone())
2215 } else {
2216 ids.iter().map(|id| self.agent(id).cloned()).collect()
2217 }
2218 }
2219
2220 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2227 if self.agents.is_empty() {
2228 bail!(
2229 "agent roster is empty: no agent CLI found on PATH and no \
2230 [[agents]] in the config. Run `magi init` to write a starter \
2231 magi.toml."
2232 );
2233 }
2234 let pinned = self
2235 .graph
2236 .selected_implementer
2237 .as_ref()
2238 .map(|id| self.agent(id).cloned())
2239 .transpose()?;
2240 Ok(ResolvedRoles {
2241 implementers: match &pinned {
2242 Some(agent) => vec![agent.clone()],
2243 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2244 },
2245 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2246 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2247 fixer: match self.roles.fixer.as_ref() {
2248 Some(choice) => Some(crate::agent::pick_chain(
2251 &self.agents,
2252 Some(choice),
2253 &|_| true,
2254 "fixer",
2255 )?),
2256 None => None,
2257 },
2258 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2263 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2264 Some(ids) if !ids.is_empty() => ids
2267 .iter()
2268 .find_map(|id| self.agent(id).ok())
2269 .cloned()
2270 .with_context(|| {
2271 format!("[roles] conductor names no agent in the roster: {ids:?}")
2272 })?,
2273 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2278 .unwrap_or_else(|_| self.agents[0].clone()),
2279 },
2280 implementer_roster: match pinned {
2281 Some(agent) => vec![agent],
2282 None => self.full_roster(&self.roles.implementers)?,
2283 },
2284 judge_roster: self.full_roster(&self.roles.judges)?,
2285 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2286 })
2287 }
2288
2289 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2311 if self.agents.is_empty() {
2312 bail!(
2313 "agent roster is empty: no agent CLI found on PATH and no \
2314 [[agents]] in the config. Run `magi init` to write a starter \
2315 magi.toml."
2316 );
2317 }
2318 if !self.roles.advisors.is_empty() {
2319 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2320 }
2321 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2322 }
2323
2324 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2328 if self.roles.advisors.is_empty() {
2329 self.full_roster(&self.roles.judges)
2330 } else {
2331 self.full_roster(&self.roles.advisors)
2332 }
2333 }
2334
2335 pub fn shell(&self) -> Vec<String> {
2337 if let Some(s) = &self.verify.shell {
2338 return s.clone();
2339 }
2340 if which("sh") {
2341 vec!["sh".to_owned(), "-c".to_owned()]
2342 } else {
2343 vec!["cmd".to_owned(), "/C".to_owned()]
2344 }
2345 }
2346
2347 pub fn starter_toml() -> String {
2349 let detected = Self::autodetected();
2350 let mut s = String::from(
2351 "# magi — blind multi-agent implementation competition.\n\
2352 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2353 # -> blind judging -> deliberation -> private final vote\n\
2354 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2355 #\n\
2356 # Rendered by teravars: a `[vars]` table, env\n\
2357 # and system lookups, and `include = [...]` all work. Tera\n\
2358 # braces are live everywhere in this file, but comments are\n\
2359 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2360 # may quote `{{ ... }}` freely.\n\
2361 #\n\
2362 # Layers deep-merge in increasing\n\
2363 # precedence, so the roster can live once per machine in\n\
2364 # <config_dir>/magi/config.toml and each repo only states its own\n\
2365 # gate:\n\
2366 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2367 [vars]\n\
2368 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2369 # Single quotes inside the braces: teravars renders the raw file\n\
2370 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2371 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2372 );
2373 if detected.agents.is_empty() {
2374 s.push_str(
2375 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2376 # kind = claude | opencode | antigravity | codex | command\n\
2377 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2378 );
2379 } else {
2380 for a in &detected.agents {
2381 s.push_str("[[agents]]\n");
2382 s.push_str(&format!("id = {:?}\n", a.id));
2383 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2384 if let Some(m) = &a.model {
2385 s.push_str(&format!("model = {m:?}\n"));
2386 }
2387 s.push('\n');
2388 }
2389 }
2390 s.push_str(
2391 "# Leave a role list empty to rotate through the roster.\n\
2392 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2393 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2394 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2395 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2396 [roles]\n\
2397 implementers = []\n\
2398 judges = []\n\
2399 reviewers = []\n\
2400 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2401 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2402 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2403 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2404 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2405 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2406 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2407 [graph]\n\
2408 # Gate GitHub prose; secret redaction is always enabled.\n\
2409 github_text_guard = true\n\
2410 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2411 github_language = \"en\"\n\
2412 implementers = 3\n\
2413 judges = 3\n\
2414 deliberate_rounds = 1\n\
2415 reviewers = 3\n\
2416 review_rounds = 6\n\
2417 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2418 gate_fix_rounds = 1\n\
2419 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2420 rerun_flaky_checks = true\n\
2421 # Port the strengths judges named in the losing candidates onto the\n\
2422 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2423 graft_runner_up = true\n\
2424 max_parallel = 4\n\
2425 language = \"en\"\n\
2426 # One CLI conversation per seat: judges keep their own argument\n\
2427 # across deliberation, the fixer keeps its implementation context.\n\
2428 sessions = true\n\
2429 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2430 # the final gate inherit this value for compatibility.\n\
2431 timeout_review = 1200\n\
2432 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2433 # verification independent if timeout_review changes later.\n\
2434 # timeout_verify = 1200\n\
2435 # Longest a seat waits for the shared build cache before it is\n\
2436 # spawned. Never counted against an agent's own timeout; expiry\n\
2437 # holds the run (resumable) instead of failing the agent.\n\
2438 # timeout_resource_wait = 1800\n\n\
2439 # What the chat calls you (persona address and the Chat's turn label).\n\
2440 # [talk]\n\
2441 # operator_name = \"Commander\"\n\n\
2442 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2443 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2444 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2445 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2446 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2447 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2448 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2449 # [[talk.personas]]\n\
2450 # id = \"gendo\"\n\
2451 # name = \"Gendo Ikari\"\n\
2452 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2453 # icon = \"~/pictures/gendo.png\"\n\n\
2454 [verify]\n\
2455 # Run once per review round in the winner's worktree; failures are\n\
2456 # fed back to the fixer.\n\
2457 e2e = []\n\
2458 # Final gate. Every command must exit 0 before a merge.\n\
2459 gate = []\n\
2460 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2461 # before the gate; whatever they change becomes one commit. A failing\n\
2462 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2463 # gate (timeout_verify). Keep it light and idempotent.\n\
2464 # pre_gate = []\n\n\
2465 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2466 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2467 # before any agent or verify command touches it. `copy` reads from the\n\
2468 # primary checkout and never overwrites; `optional` skips a missing\n\
2469 # source. `run` goes through the shell with the worktree as cwd and\n\
2470 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2471 # the verify timeout). Setup must not edit tracked files, and what it\n\
2472 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2473 # layer only.\n\
2474 # [worktree]\n\
2475 # setup = [\n\
2476 # { copy = \".env.example -> .env\" },\n\
2477 # { copy = \".env.local\", optional = true },\n\
2478 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2479 # ]\n\n\
2480 [merge]\n\
2481 # none | local | pr\n\
2482 mode = \"none\"\n\
2483 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2484 [update]\n\
2485 # off | notify | install — checked in the background, throttled.\n\
2486 mode = \"notify\"\n\
2487 # interval = \"24h\"\n\n\
2488 [daemon]\n\
2489 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2490 # no new commit and no check changing state before `magi serve`\n\
2491 # notices and asks you. A failed check is rerun once on its own;\n\
2492 # still red after that escalates at once. 0 turns the watcher off.\n\
2493 # release_stall_minutes = 60\n\n\
2494 [release]\n\
2495 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2496 # Actions never run (private, no minutes): the release pull request\n\
2497 # does not wait for CI, you approve the merge in magi, and then\n\
2498 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2499 # runs `commands` from a clean checkout of the merge commit. A\n\
2500 # failure holds the release with a notice; it is never retried blind.\n\
2501 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2502 # mode = \"actions\"\n\
2503 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2504 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2505 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2506 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2507 # timeout_minutes = 30\n\
2508 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2509 # The first entry is the version of record and must be the file the\n\
2510 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2511 # rewritten to the same version. Paths are relative to the repository\n\
2512 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2513 # is not touched.\n\
2514 # version_files = [\n\
2515 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2516 # { path = \"package.json\", kind = \"json\" },\n\
2517 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2518 # ]\n",
2519 );
2520 s
2521 }
2522}
2523
2524pub fn which(program: &str) -> bool {
2526 find_program(program).is_some()
2527}
2528
2529pub fn find_program(program: &str) -> Option<PathBuf> {
2538 find_program_on(program, &std::env::var_os("PATH")?)
2539}
2540
2541pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2544 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2545 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2546}
2547
2548fn find_program_in(
2549 program: &str,
2550 paths: &std::ffi::OsStr,
2551 pathext: Option<&str>,
2552) -> Option<PathBuf> {
2553 let p = Path::new(program);
2554 if p.components().count() > 1 {
2555 return p.is_file().then(|| p.to_path_buf());
2556 }
2557 std::env::split_paths(paths).find_map(|dir| match pathext {
2558 Some(exts) => {
2559 let bare = dir.join(program);
2560 if p.extension().is_some() && bare.is_file() {
2561 return Some(bare);
2562 }
2563 exts.split(';')
2564 .filter(|e| !e.is_empty())
2565 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2566 .find(|c| c.is_file())
2567 }
2568 None => Some(dir.join(program)).filter(|c| c.is_file()),
2569 })
2570}
2571
2572const REPO_MARKER: &str = ".magi-repo";
2574
2575fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2576 use crate::proc::Quiet as _;
2577 #[cfg(test)]
2578 crate::web::request_cost::git();
2579 let out = std::process::Command::new("git")
2580 .args(args)
2581 .quiet()
2582 .current_dir(repo)
2583 .stdin(std::process::Stdio::null())
2584 .output()
2585 .ok()?;
2586 out.status
2587 .success()
2588 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2589}
2590
2591fn is_git_worktree(repo: &Path) -> bool {
2594 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2595}
2596
2597#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2600pub enum OwnerHold {
2601 LandApproval,
2603 HoldContestedMerge,
2605}
2606
2607impl OwnerHold {
2608 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2610
2611 pub fn key(self) -> &'static str {
2613 match self {
2614 Self::LandApproval => "land_approval",
2615 Self::HoldContestedMerge => "hold_contested_merge",
2616 }
2617 }
2618
2619 pub fn base_value(self, graph: &Graph) -> bool {
2621 match self {
2622 Self::LandApproval => graph.land_approval,
2623 Self::HoldContestedMerge => graph.hold_contested_merge,
2624 }
2625 }
2626}
2627
2628pub async fn branch_owner_holds(
2631 repo: &Path,
2632 head: &str,
2633) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2634 let mut holds = Vec::new();
2635 let mut diagnostics = Vec::new();
2636 if let Err(error) =
2639 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2640 {
2641 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2642 return (holds, diagnostics);
2643 }
2644 for file in ["magi.toml", ".magi/config.toml"] {
2645 let object = format!("{head}:{file}");
2646 let text = match crate::git::git(repo, &["show", &object]).await {
2647 Ok(text) => text,
2648 Err(error) => {
2649 let error = format!("{error:#}");
2651 if !error.contains("does not exist in")
2652 && !error.contains("exists on disk, but not in")
2653 {
2654 diagnostics.push(format!(
2655 "cannot read reviewed branch {file} at {head}: {error}"
2656 ));
2657 }
2658 continue;
2659 }
2660 };
2661 let value = match toml::from_str::<toml::Value>(&text) {
2662 Ok(value) => value,
2663 Err(error) => {
2664 diagnostics.push(format!(
2665 "cannot parse reviewed branch {file} at {head}: {error}"
2666 ));
2667 continue;
2668 }
2669 };
2670 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2671 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2672 }
2673 for hold in OwnerHold::ALL {
2674 if value
2675 .get("graph")
2676 .and_then(|g| g.get(hold.key()))
2677 .and_then(toml::Value::as_bool)
2678 == Some(true)
2679 {
2680 holds.push((hold, file.to_owned()));
2681 }
2682 }
2683 }
2684 (holds, diagnostics)
2685}
2686
2687#[derive(Deserialize, Default)]
2688struct ProbeMerge {
2689 base: Option<String>,
2690 remote: Option<String>,
2691}
2692
2693#[derive(Deserialize, Default)]
2694struct Probe {
2695 merge: Option<ProbeMerge>,
2696}
2697
2698fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2704 if !path.is_file() {
2705 return None;
2706 }
2707 let paths = [path.to_path_buf()];
2708 let mut engine = teravars::Engine::default();
2709 let mut ctx = Config::render_ctx(&paths);
2710 ctx.insert("repo", &repo.to_string_lossy());
2713 ctx.insert(
2714 "repo_name",
2715 &repo.file_name().unwrap_or_default().to_string_lossy(),
2716 );
2717 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2718 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2719 {
2720 return probe.merge;
2721 }
2722 let text = std::fs::read_to_string(path).ok()?;
2723 toml::from_str::<Probe>(&text).ok()?.merge
2724}
2725
2726fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2728 let mut remote = None;
2729 let mut base = None;
2730 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2731 sources.push(repo.join("magi.toml"));
2732 sources.push(repo.join(".magi").join("config.toml"));
2733 for path in sources {
2734 if let Some(m) = probe_merge(&path, repo) {
2735 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2736 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2737 }
2738 }
2739 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2740}
2741
2742fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2744 let (remote, base) = probe_remote_base(repo);
2745 let base = match base {
2746 Some(b) => b,
2747 None => {
2748 let head = format!("refs/remotes/{remote}/HEAD");
2749 git_out(repo, &["symbolic-ref", "--quiet", &head])
2750 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2751 .with_context(|| {
2752 format!(
2753 "cannot tell which branch of `{remote}` holds magi.toml: \
2754 set [merge] base, or run `git remote set-head {remote} -a`"
2755 )
2756 })?
2757 }
2758 };
2759 Ok((remote, base))
2760}
2761
2762fn fnv_hex(text: &str) -> String {
2763 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2764 for b in text.bytes() {
2765 hash ^= u64::from(b);
2766 hash = hash.wrapping_mul(0x0100_0000_01b3);
2767 }
2768 format!("{hash:016x}")
2769}
2770
2771fn declares_include(text: &str) -> bool {
2777 match toml::from_str::<toml::Table>(text) {
2778 Ok(table) => {
2779 table.contains_key("include")
2780 || table
2781 .get("teravars")
2782 .and_then(toml::Value::as_table)
2783 .is_some_and(|t| t.contains_key("include"))
2784 }
2785 Err(_) => text.contains("include"),
2786 }
2787}
2788
2789fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2792 use crate::proc::Quiet as _;
2793 #[cfg(test)]
2794 crate::web::request_cost::git();
2795 let mut archive = std::process::Command::new("git")
2796 .args(["archive", "--format=tar", sha])
2797 .quiet()
2798 .current_dir(repo)
2799 .stdin(std::process::Stdio::null())
2800 .stdout(std::process::Stdio::piped())
2801 .stderr(std::process::Stdio::null())
2802 .spawn()
2803 .context("running git archive")?;
2804 let tar = std::process::Command::new("tar")
2805 .arg("-x")
2806 .arg("-C")
2807 .arg(dest)
2808 .quiet()
2809 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2810 .output()
2811 .context("running tar")?;
2812 let status = archive.wait().context("waiting for git archive")?;
2813 if !status.success() || !tar.status.success() {
2814 bail!(
2815 "cannot unpack {sha} for the config's includes: {}",
2816 String::from_utf8_lossy(&tar.stderr).trim()
2817 );
2818 }
2819 Ok(())
2820}
2821
2822fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2825 let (remote, base) = resolve_remote_base(repo)?;
2826 let tracking = format!("refs/remotes/{remote}/{base}");
2827 let spec = format!("{tracking}^{{commit}}");
2828 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2829 .map(|s| s.trim().to_owned())
2830 .filter(|s| !s.is_empty())
2831 .with_context(|| {
2832 format!(
2833 "`{remote}/{base}` does not exist in this checkout; fetch it \
2834 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2835 a possibly stale local magi.toml instead"
2836 )
2837 })?;
2838 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2839 let rels = [".magi/config.toml", "magi.toml"];
2840 let mut texts: Vec<(&str, String)> = Vec::new();
2841 for rel in rels {
2842 let object = format!("{sha}:{rel}");
2843 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2844 continue;
2845 }
2846 let Some(text) = git_out(repo, &["show", &object]) else {
2847 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2848 };
2849 texts.push((rel, text));
2850 }
2851 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2852 let build = |root: &Path| -> Result<PathBuf> {
2856 let final_dir = root.join(&key);
2857 if !final_dir.is_dir() {
2858 std::fs::create_dir_all(root)?;
2859 let tmp = root.join(format!(
2860 "{key}.tmp-{}-{}",
2861 std::process::id(),
2862 std::time::SystemTime::now()
2863 .duration_since(std::time::UNIX_EPOCH)
2864 .map(|d| d.as_nanos())
2865 .unwrap_or_default()
2866 ));
2867 let filled = (|| -> Result<()> {
2868 std::fs::create_dir_all(&tmp)?;
2869 if wants_tree {
2870 extract_tree(repo, &sha, &tmp)?;
2871 }
2872 for (rel, text) in &texts {
2873 let file = tmp.join(rel);
2874 let parent = file.parent().unwrap_or(&tmp);
2875 std::fs::create_dir_all(parent)?;
2876 std::fs::write(&file, text)?;
2877 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2878 }
2879 Ok(())
2880 })();
2881 if let Err(e) = filled {
2882 let _ = std::fs::remove_dir_all(&tmp);
2883 return Err(e);
2884 }
2885 if std::fs::rename(&tmp, &final_dir).is_err() {
2886 let _ = std::fs::remove_dir_all(&tmp);
2888 if !final_dir.is_dir() {
2889 bail!("cannot place {}", final_dir.display());
2890 }
2891 }
2892 }
2893 Ok(final_dir)
2894 };
2895 let common = git_out(
2896 repo,
2897 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2898 )
2899 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2900 let dir = match common.map(|c| build(&c)) {
2901 Some(Ok(d)) => d,
2902 _ => build(&std::env::temp_dir().join("magi-config"))
2903 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2904 };
2905 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2906}
2907
2908#[cfg(test)]
2909mod tests {
2910 #[test]
2911 fn coordination_defaults_off_and_validates_rendered_layer_values() {
2912 let dir = tempfile::tempdir().unwrap();
2913 let machine = dir.path().join("machine.toml");
2914 let repo = dir.path().join("repo.toml");
2915 std::fs::write(&machine, "").unwrap();
2916 assert!(Config::default().coordination.is_none());
2917 assert!(Config::load(&machine).unwrap().coordination.is_none());
2918 std::fs::write(
2919 &machine,
2920 r#"
2921[vars]
2922contract = "updater.contract"
2923[coordination]
2924contract_file = "{{ vars.contract }}"
2925contract_token = "protocol-v1"
2926lock_file = "updater.lock"
2927"#,
2928 )
2929 .unwrap();
2930 let cfg = Config::load(&machine).unwrap();
2931 let policy = cfg.coordination.unwrap();
2932 assert_eq!(policy.contract_file, "updater.contract");
2933 assert_eq!(policy.contract_token, "protocol-v1");
2934 assert_eq!(policy.lock_file, "updater.lock");
2935 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
2936 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
2937 let policy = cfg.coordination.unwrap();
2938 assert_eq!(policy.contract_file, "updater.contract");
2939 assert_eq!(policy.lock_file, "repository.lock");
2940 std::fs::write(
2941 &repo,
2942 r#"
2943[vars]
2944bad = "../escape"
2945[coordination]
2946lock_file = "{{ vars.bad }}"
2947"#,
2948 )
2949 .unwrap();
2950 let error = Config::load_layers(&[machine, repo]).unwrap_err();
2951 assert!(format!("{error:#}").contains("coordination.lock_file"));
2952 }
2953
2954 #[test]
2955 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
2956 let dir = tempfile::tempdir().unwrap();
2957 let path = dir.path().join("config.toml");
2958 let valid = toml::toml! {
2959 [coordination]
2960 contract_file = "updater.contract"
2961 contract_token = "protocol-v1"
2962 lock_file = "updater.lock"
2963 };
2964 for key in ["contract_file", "lock_file"] {
2965 for bad in [
2966 "",
2967 " ",
2968 " file",
2969 "file ",
2970 "\tfile",
2971 "file\t",
2972 ".",
2973 "..",
2974 "file..name",
2975 "../escape",
2976 "a/b",
2977 "a\\b",
2978 "/absolute",
2979 "C:drive",
2980 "C:\\absolute",
2981 "nul\0name",
2982 ] {
2983 let mut table = valid.clone();
2984 table["coordination"][key] = bad.into();
2985 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2986 let error = Config::load(&path).unwrap_err();
2987 assert!(
2988 format!("{error:#}").contains(&format!("coordination.{key}")),
2989 "{bad:?}: {error:#}"
2990 );
2991 }
2992 }
2993 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
2994 let mut table = valid.clone();
2995 table["coordination"]["contract_token"] = bad.into();
2996 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2997 let error = Config::load(&path).unwrap_err();
2998 assert!(
2999 format!("{error:#}").contains("coordination.contract_token"),
3000 "{error:#}"
3001 );
3002 }
3003 for key in ["contract_file", "contract_token", "lock_file"] {
3004 let mut table = valid.clone();
3005 table["coordination"].as_table_mut().unwrap().remove(key);
3006 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3007 let error = Config::load(&path).unwrap_err();
3008 assert!(
3009 format!("{error:#}").contains(&format!("coordination.{key}")),
3010 "{error:#}"
3011 );
3012 }
3013 let mut table = valid;
3014 table["coordination"]
3015 .as_table_mut()
3016 .unwrap()
3017 .insert("typo".into(), "value".into());
3018 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3019 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
3020 }
3021
3022 #[test]
3023 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
3024 let mut cfg = Config::default();
3025 assert_eq!(
3026 cfg.context_window("claude-sonnet-4-5-20250929"),
3027 Some(200_000)
3028 );
3029 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
3030 assert_eq!(cfg.context_window("mystery-model"), None);
3031 cfg.context_windows
3032 .insert("claude-sonnet-4-5".into(), 1_000_000);
3033 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
3034 cfg.context_windows.insert("mystery".into(), 32_768);
3035 assert_eq!(
3037 cfg.context_window("claude-sonnet-4-5-20250929"),
3038 Some(1_000_000)
3039 );
3040 cfg.context_windows
3042 .insert("claude-sonnet-4-5-20250929".into(), 7);
3043 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
3044 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
3045 }
3046
3047 use super::*;
3048
3049 #[test]
3052 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
3053 let dir = tempfile::tempdir().unwrap();
3054 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
3055 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
3056 let paths = dir.path().as_os_str();
3057 assert_eq!(
3058 find_program_in("codex", paths, Some(".EXE;.CMD")),
3059 Some(dir.path().join("codex.cmd"))
3060 );
3061 assert_eq!(
3062 find_program_in("codex", paths, None),
3063 Some(dir.path().join("codex"))
3064 );
3065 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3066 }
3067
3068 fn spec(id: &str) -> AgentSpec {
3069 AgentSpec {
3070 id: id.to_owned(),
3071 kind: AgentKind::Command,
3072 model: None,
3073 command: vec!["true".to_owned()],
3074 extra_args: Vec::new(),
3075 env: BTreeMap::new(),
3076 prompt_delivery: None,
3077 max_turn_secs: None,
3078 }
3079 }
3080
3081 #[test]
3082 fn github_text_guard_defaults_on_and_can_be_disabled() {
3083 let default: Graph = toml::from_str("").unwrap();
3084 assert!(default.github_text_guard);
3085 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3086 assert!(!disabled.github_text_guard);
3087 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3088 assert!(!config.graph.github_text_guard);
3089 assert!(Config::starter_toml().contains("github_text_guard = true"));
3090 }
3091
3092 #[test]
3093 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3094 assert!(Graph::default().rerun_flaky_checks);
3095 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3096 assert!(!off.rerun_flaky_checks);
3097 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3098 }
3099
3100 #[test]
3101 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3102 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3107 assert_eq!(g.timeout_verify, None);
3108 assert_eq!(g.verify_timeout(), 3600);
3109 }
3110
3111 #[test]
3112 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3113 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3118 assert_eq!(g.timeout_review, 45);
3119 assert_eq!(
3120 g.verify_timeout(),
3121 45,
3122 "an omitted legacy value follows review"
3123 );
3124 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3125 .expect("parse explicit override");
3126 assert_eq!(explicit.verify_timeout(), 1200);
3127 }
3128
3129 #[test]
3130 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3131 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3132 assert_eq!(g.implementers, 4);
3133 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3134 assert_eq!(g.implementers, 5);
3135 }
3136
3137 fn layered(lower: &str, upper: &str) -> Result<Config> {
3138 let dir = tempfile::tempdir().unwrap();
3139 let a = dir.path().join("a.toml");
3140 let b = dir.path().join("b.toml");
3141 std::fs::write(&a, lower).unwrap();
3142 std::fs::write(&b, upper).unwrap();
3143 Config::load_layers(&[a, b])
3144 }
3145
3146 #[test]
3147 fn graph_implementers_higher_layer_wins_across_spellings() {
3148 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3149 assert_eq!(c.graph.implementers, 5);
3150 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3151 assert_eq!(c.graph.implementers, 5);
3152 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3153 assert_eq!(c.graph.implementers, 2);
3154 }
3155
3156 #[test]
3157 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3158 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3159 .unwrap_err()
3160 .to_string();
3161 assert!(
3162 err.contains("candidates") && err.contains("implementers"),
3163 "{err}"
3164 );
3165 assert!(err.contains("b.toml"), "{err}");
3166 }
3167
3168 #[test]
3169 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3170 let g: Graph =
3174 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3175 .expect("an old-shaped [graph] table must still parse");
3176 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3177 assert!(
3178 !g.e2e_every_round,
3179 "off by default, same as before this field existed"
3180 );
3181 }
3182
3183 #[test]
3184 fn empty_roles_rotate_judges_off_their_own_candidate() {
3185 let cfg = Config {
3188 agents: vec![spec("a"), spec("b"), spec("c")],
3189 graph: Graph {
3190 implementers: 3,
3191 ..Graph::default()
3192 },
3193 ..Config::default()
3194 };
3195 let roles = cfg.resolve_roles().unwrap();
3196 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3197 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3198 assert_eq!(impls, ["a", "b", "c"]);
3199 assert_eq!(judges, ["b", "c", "a"]);
3200 for (i, j) in judges.iter().enumerate() {
3201 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3202 }
3203 }
3204
3205 #[test]
3206 fn single_agent_roster_fills_every_seat() {
3207 let cfg = Config {
3208 agents: vec![spec("solo")],
3209 graph: Graph {
3210 implementers: 3,
3211 ..Graph::default()
3212 },
3213 ..Config::default()
3214 };
3215 let roles = cfg.resolve_roles().unwrap();
3216 assert_eq!(roles.implementers.len(), 3);
3217 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3218 }
3219
3220 #[test]
3221 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3222 let cfg = Config {
3227 agents: vec![spec("a"), spec("b"), spec("c")],
3228 graph: Graph {
3229 implementers: 1,
3230 ..Graph::default()
3231 },
3232 ..Config::default()
3233 };
3234 let roles = cfg.resolve_roles().unwrap();
3235 assert_eq!(roles.implementers.len(), 1);
3236 let roster: Vec<&str> = roles
3237 .implementer_roster
3238 .iter()
3239 .map(|a| a.id.as_str())
3240 .collect();
3241 assert_eq!(roster, ["a", "b", "c"]);
3242 }
3243
3244 #[test]
3245 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3246 let cfg = Config {
3247 agents: vec![spec("a"), spec("b"), spec("c")],
3248 roles: Roles {
3249 implementers: vec!["c".to_owned(), "a".to_owned()],
3250 ..Roles::default()
3251 },
3252 graph: Graph {
3253 implementers: 1,
3254 ..Graph::default()
3255 },
3256 ..Config::default()
3257 };
3258 let roles = cfg.resolve_roles().unwrap();
3259 assert_eq!(roles.implementers.len(), 1);
3261 assert_eq!(roles.implementers[0].id, "c");
3262 let roster: Vec<&str> = roles
3263 .implementer_roster
3264 .iter()
3265 .map(|a| a.id.as_str())
3266 .collect();
3267 assert_eq!(roster, ["c", "a"]);
3268 }
3269
3270 #[test]
3271 fn explicit_roles_win() {
3272 let cfg = Config {
3273 agents: vec![spec("a"), spec("b")],
3274 roles: Roles {
3275 implementers: vec!["b".to_owned()],
3276 judges: vec!["a".to_owned()],
3277 reviewers: Vec::new(),
3278 fixer: Some("a".into()),
3279 ..Roles::default()
3280 },
3281 ..Config::default()
3282 };
3283 let roles = cfg.resolve_roles().unwrap();
3284 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3285 assert!(roles.judges.iter().all(|a| a.id == "a"));
3286 let fixer = roles.fixer.unwrap();
3287 assert_eq!(fixer.len(), 1);
3288 assert_eq!(fixer[0].id, "a");
3289 assert_eq!(roles.conductor.id, "a");
3290 }
3291
3292 #[test]
3293 fn fixer_takes_a_string_or_an_ordered_chain() {
3294 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3295 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3296 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3297 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3298
3299 let resolve = |fixer: Option<AgentChoice>| {
3300 Config {
3301 agents: vec![spec("a"), spec("b"), spec("c")],
3302 roles: Roles {
3303 fixer,
3304 ..Roles::default()
3305 },
3306 ..Config::default()
3307 }
3308 .resolve_roles()
3309 };
3310 let ids = |r: &ResolvedRoles| -> Vec<String> {
3311 r.fixer
3312 .as_ref()
3313 .unwrap()
3314 .iter()
3315 .map(|s| s.id.clone())
3316 .collect()
3317 };
3318 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3320 assert!(resolve(None).unwrap().fixer.is_none());
3321 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3323 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3324 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3326 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3327 }
3328
3329 #[test]
3330 fn unknown_agent_id_is_an_error() {
3331 let cfg = Config {
3332 agents: vec![spec("a")],
3333 roles: Roles {
3334 judges: vec!["nope".to_owned()],
3335 ..Roles::default()
3336 },
3337 ..Config::default()
3338 };
3339 assert!(cfg.resolve_roles().is_err());
3340 }
3341
3342 #[test]
3343 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3344 let mut cfg = Config {
3345 agents: vec![spec("a"), spec("b")],
3346 ..Config::default()
3347 };
3348 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3349
3350 cfg.roles.conductor = Some("b".into());
3351 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3352
3353 cfg.roles.conductor = Some("missing".into());
3354 assert!(cfg.resolve_roles().is_err());
3355 }
3356
3357 #[test]
3358 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3359 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3360 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3361 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3362
3363 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3364 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3365 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3366
3367 for roles in [one, chain] {
3368 let text = toml::to_string(&roles).unwrap();
3369 let back: Roles = toml::from_str(&text).unwrap();
3370 assert_eq!(back.synthesizer, roles.synthesizer);
3371 assert_eq!(back.chatter, roles.chatter);
3372 }
3373 let text = toml::to_string(&Roles {
3374 conductor: Some("x".into()),
3375 ..Roles::default()
3376 })
3377 .unwrap();
3378 assert!(
3379 text.contains("conductor = \"x\""),
3380 "string stays a string: {text}"
3381 );
3382 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3383 }
3384
3385 #[test]
3386 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3387 for (text, ids) in [
3388 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3389 (
3390 r#"dupes_judge = ["first", "second"]"#,
3391 vec!["first", "second"],
3392 ),
3393 ("dupes_judge = []", vec![]),
3394 ] {
3395 let roles: Roles = toml::from_str(text).unwrap();
3396 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3397 let serialized = toml::to_string(&roles).unwrap();
3398 let back: Roles = toml::from_str(&serialized).unwrap();
3399 assert_eq!(back.dupes_judge, roles.dupes_judge);
3400 assert!(serialized.contains(text));
3401 }
3402 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3403 assert!(Roles::default().dupes_judge.is_none());
3404 assert!(Config::starter_toml().contains("# dupes_judge ="));
3405
3406 let mut cfg = Config {
3408 agents: vec![spec("a")],
3409 ..Config::default()
3410 };
3411 cfg.roles.dupes_judge = Some("missing".into());
3412 assert!(cfg.resolve_roles().is_ok());
3413 }
3414
3415 #[test]
3416 fn an_empty_choice_counts_as_unset() {
3417 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3418 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3419 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3420 }
3421
3422 #[test]
3423 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3424 let mut cfg = Config {
3430 agents: vec![spec("a"), spec("b")],
3431 ..Config::default()
3432 };
3433 let want = primary(cfg.roles.synthesizer.as_ref());
3434 assert_eq!(
3435 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3436 .unwrap()
3437 .id,
3438 "a",
3439 "unset falls back to agent::pick's own default order"
3440 );
3441
3442 cfg.roles.synthesizer = Some("b".into());
3443 let want = primary(cfg.roles.synthesizer.as_ref());
3444 assert_eq!(
3445 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3446 .unwrap()
3447 .id,
3448 "b",
3449 "the named agent wins over the default order"
3450 );
3451 }
3452
3453 #[test]
3454 fn empty_roster_is_an_error() {
3455 assert!(Config::default().resolve_roles().is_err());
3456 }
3457
3458 #[test]
3459 fn advise_defaults_to_on_with_three_proposals() {
3460 let g = Graph::default();
3461 assert!(g.advise);
3462 assert!(g.graft_runner_up, "graft is on by default");
3463 assert_eq!(g.advisors, 3);
3464 }
3465
3466 #[test]
3467 fn unset_advisors_falls_back_to_the_judge_roster() {
3468 let cfg = Config {
3469 agents: vec![spec("a"), spec("b")],
3470 roles: Roles {
3471 judges: vec!["b".to_owned()],
3472 ..Roles::default()
3473 },
3474 graph: Graph {
3475 advisors: 2,
3476 ..Graph::default()
3477 },
3478 ..Config::default()
3479 };
3480 let advisors = cfg.advisors().expect("advisors resolve");
3481 assert_eq!(advisors.len(), 2);
3482 assert!(
3483 advisors.iter().all(|a| a.id == "b"),
3484 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3485 );
3486 }
3487
3488 #[test]
3489 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3490 let cfg = Config {
3491 agents: vec![spec("a"), spec("b")],
3492 roles: Roles {
3493 judges: vec!["b".to_owned()],
3494 advisors: vec!["a".to_owned()],
3495 ..Roles::default()
3496 },
3497 graph: Graph {
3498 advisors: 2,
3499 ..Graph::default()
3500 },
3501 ..Config::default()
3502 };
3503 let advisors = cfg.advisors().expect("advisors resolve");
3504 assert!(advisors.iter().all(|a| a.id == "a"));
3505 }
3506
3507 #[test]
3513 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3514 let cfg = Config {
3515 agents: vec![spec("a"), spec("b"), spec("c")],
3516 graph: Graph {
3517 advisors: 3,
3518 judges: 3,
3519 ..Graph::default()
3520 },
3521 ..Config::default()
3522 };
3523 let advisors = cfg.advisors().expect("advisors resolve");
3524 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3525 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3526 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3527 assert_eq!(
3528 advisor_ids, judge_ids,
3529 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3530 );
3531 }
3532
3533 #[test]
3534 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3535 let cfg = Config {
3536 agents: vec![spec("a")],
3537 roles: Roles {
3538 advisors: vec!["nope".to_owned()],
3539 ..Roles::default()
3540 },
3541 graph: Graph {
3542 advisors: 1,
3543 ..Graph::default()
3544 },
3545 ..Config::default()
3546 };
3547 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3548 assert!(format!("{err:#}").contains("nope"));
3549 }
3550
3551 #[test]
3552 fn repos_default_to_no_roots_and_a_day_of_trust() {
3553 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3554 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3555 assert_eq!(Config::default().repos.fetch_interval, 600);
3556 }
3557
3558 #[test]
3559 fn a_config_file_with_no_repos_table_still_loads() {
3560 let dir = tempfile::tempdir().unwrap();
3561 let path = dir.path().join("magi.toml");
3562 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3563 let cfg = Config::load(&path).expect("must load without [repos]");
3564 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3565 assert_eq!(cfg.repos.scan_ttl, 86_400);
3566 }
3567
3568 #[test]
3583 fn a_test_build_does_not_read_the_operators_machine_config() {
3584 let repo = tempfile::tempdir().unwrap();
3585 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3586
3587 let layers = Config::layers(repo.path());
3588 assert_eq!(
3589 layers,
3590 vec![repo.path().join("magi.toml")],
3591 "only the fixture's own file may be a layer"
3592 );
3593 if let Some(real) = dirs::config_dir() {
3594 let machine = real.join("magi").join("config.toml");
3595 assert!(
3596 !layers.contains(&machine),
3597 "the operator's {} must not be a layer in a test build",
3598 machine.display()
3599 );
3600 }
3601 }
3602
3603 #[test]
3604 fn starter_toml_loads_through_teravars() {
3605 let dir = tempfile::tempdir().unwrap();
3606 let path = dir.path().join("magi.toml");
3607 std::fs::write(&path, Config::starter_toml()).unwrap();
3608 let parsed = Config::load(&path).expect("starter config must load");
3609 assert_eq!(parsed.graph.implementers, 3);
3610 assert_eq!(parsed.merge.mode, MergeMode::None);
3611 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3612 assert!(parsed.graph.sessions);
3613 assert!(parsed.graph.github_text_guard);
3614 assert_eq!(parsed.graph.timeout_review, 1200);
3615 assert_eq!(parsed.graph.verify_timeout(), 1200);
3616 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3617 }
3618
3619 #[test]
3620 fn release_defaults_to_actions_and_the_starter_documents_it() {
3621 let dir = tempfile::tempdir().unwrap();
3622 let path = dir.path().join("magi.toml");
3623 std::fs::write(&path, Config::starter_toml()).unwrap();
3624 let r = Config::load(&path).unwrap().release;
3625 assert_eq!(r.mode, ReleaseMode::Actions);
3626 assert!(!r.is_local());
3627 assert!(r.commands.is_empty());
3628 assert_eq!(r.timeout_minutes, 30);
3629 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3630 }
3631
3632 #[test]
3633 fn release_local_parses_and_unknown_keys_are_refused() {
3634 let dir = tempfile::tempdir().unwrap();
3635 let path = dir.path().join("magi.toml");
3636 std::fs::write(
3637 &path,
3638 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3639 )
3640 .unwrap();
3641 let r = Config::load(&path).unwrap().release;
3642 assert!(r.is_local());
3643 assert_eq!(r.commands.len(), 2);
3644 assert_eq!(r.timeout_minutes, 5);
3645 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3646 assert!(Config::load(&path).is_err());
3647 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3648 assert!(Config::load(&path).is_err());
3649 }
3650
3651 #[test]
3652 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3653 let dir = tempfile::tempdir().unwrap();
3654 let path = dir.path().join("magi.toml");
3655 std::fs::write(&path, Config::starter_toml()).unwrap();
3656 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3657 assert!(Config::starter_toml().contains("# pre_gate = []"));
3658 }
3659
3660 #[test]
3661 fn release_version_files_parse_default_empty_and_are_validated() {
3662 let dir = tempfile::tempdir().unwrap();
3663 let path = dir.path().join("magi.toml");
3664 std::fs::write(&path, "").unwrap();
3665 assert!(
3666 Config::load(&path)
3667 .unwrap()
3668 .release
3669 .version_files
3670 .is_empty()
3671 );
3672 std::fs::write(
3673 &path,
3674 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
3675 )
3676 .unwrap();
3677 let files = Config::load(&path).unwrap().release.version_files;
3678 assert_eq!(files.len(), 2);
3679 assert_eq!(files[1].kind, VersionKind::Json);
3680 for bad in [
3681 "{ path = \"package.json\", kind = \"json\" }",
3682 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
3683 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
3684 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
3685 ] {
3686 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
3687 assert!(Config::load(&path).is_err(), "{bad}");
3688 }
3689 assert!(Config::starter_toml().contains("# version_files = ["));
3690 }
3691
3692 #[test]
3693 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3694 let starter = Config::starter_toml();
3695 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3696 assert!(starter.contains("verification independent if timeout_review changes later"));
3697 assert!(starter.contains("# timeout_verify = 1200"));
3698 }
3699
3700 #[test]
3701 fn starter_toml_documents_chat_personas() {
3702 let starter = Config::starter_toml();
3703 assert!(starter.contains("# [[talk.personas]]"));
3704 assert!(starter.contains("tone only"));
3705 }
3706
3707 #[test]
3708 fn talk_personas_parse_and_are_validated() {
3709 let dir = tempfile::tempdir().unwrap();
3710 let path = dir.path().join("magi.toml");
3711 std::fs::write(
3712 &path,
3713 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3714 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3715 )
3716 .unwrap();
3717 let cfg = Config::load(&path).expect("loads");
3718 assert_eq!(cfg.talk.personas.len(), 2);
3719 let catalog = crate::persona::catalog(&cfg.talk.personas);
3720 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3721 assert_eq!(
3722 (rei.name.as_str(), rei.prompt.as_str()),
3723 ("Quiet", "Be brief.")
3724 );
3725 assert_eq!(catalog.last().unwrap().id, "gendo");
3726
3727 for (body, needle) in [
3728 (
3729 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3730 "empty `id`",
3731 ),
3732 (
3733 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3734 "empty `prompt`",
3735 ),
3736 (
3737 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3738 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3739 "more than once",
3740 ),
3741 (
3742 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3743 "cannot be redefined",
3744 ),
3745 ] {
3746 std::fs::write(&path, body).unwrap();
3747 let err = format!("{:#}", Config::load(&path).unwrap_err());
3748 assert!(err.contains(needle), "{needle}: {err}");
3749 }
3750 }
3751
3752 #[test]
3753 fn talk_operator_name_is_trimmed_and_validated() {
3754 let dir = tempfile::tempdir().unwrap();
3755 let path = dir.path().join("magi.toml");
3756 let load = |body: &str| {
3757 std::fs::write(&path, body).unwrap();
3758 Config::load(&path)
3759 };
3760 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3761 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3762 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3763 assert_eq!(blank.talk.operator_name(), None);
3764 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3765 let long = "x".repeat(65);
3766 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3767 }
3768
3769 #[test]
3770 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3771 let dir = tempfile::tempdir().unwrap();
3772 let load = |body: &str| {
3773 let path = dir.path().join("c.toml");
3774 std::fs::write(&path, body).unwrap();
3775 Config::load(&path)
3776 };
3777 let ok = load(
3778 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3779 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3780 )
3781 .unwrap();
3782 let c = crate::persona::catalog(&ok.talk.personas);
3783 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3784 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3785 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3786 let oversized = format!(
3787 "data:image/png;base64,{}",
3788 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3789 );
3790 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3791 for (id, fields) in [
3792 ("rei", ""),
3793 ("default", ""),
3794 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3795 ] {
3796 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3797 let cfg = load(&body).expect("bad icon must not invalidate config");
3798 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3799 assert_eq!(persona.id, id);
3800 assert!(crate::persona_icon::load(bad).is_err());
3801 }
3802 }
3803 let doc = Config::starter_toml();
3804 assert!(doc.contains("# icon = "));
3805 }
3806
3807 #[test]
3808 fn talk_personas_in_two_layers_are_refused() {
3809 let dir = tempfile::tempdir().unwrap();
3810 let machine = dir.path().join("machine.toml");
3811 let repo = dir.path().join("repo.toml");
3812 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3813 std::fs::write(&machine, one).unwrap();
3814 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3815 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3816 assert!(err.contains("talk.personas"), "{err}");
3817 }
3818
3819 #[test]
3820 fn starter_toml_documents_role_lists_as_backup_order() {
3821 let starter = Config::starter_toml();
3822 assert!(starter.contains("also an ordered backup list"));
3823 assert!(starter.contains("codex then sonnet are spares"));
3824 }
3825
3826 #[test]
3830 fn a_repository_can_declare_a_linear_history_merge_style() {
3831 let dir = tempfile::tempdir().unwrap();
3832 let path = dir.path().join("magi.toml");
3833 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3834 let parsed = Config::load(&path).expect("config must load");
3835 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3836 }
3837
3838 #[test]
3839 fn later_layers_win_and_vars_render() {
3840 let dir = tempfile::tempdir().unwrap();
3841 let machine = dir.path().join("machine.toml");
3842 let project = dir.path().join("magi.toml");
3843 std::fs::write(
3845 &machine,
3846 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3847 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3848 )
3849 .unwrap();
3850 std::fs::write(
3853 &project,
3854 "[vars]\ncache = \"/shared\"\n\n\
3855 [graph]\ncandidates = 2\n\n\
3856 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3857 )
3858 .unwrap();
3859
3860 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3861 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3862 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3863 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3864 assert_eq!(
3865 cfg.verify.gate,
3866 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3867 );
3868 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3870 }
3871
3872 #[test]
3873 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3874 let g = Graph::default();
3878 assert_eq!(g.timeout_talk, 3600);
3879
3880 let dir = tempfile::tempdir().unwrap();
3881 let path = dir.path().join("magi.toml");
3882 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3883 let cfg = Config::load(&path).expect("must load without timeout_talk set");
3884 assert_eq!(cfg.graph.timeout_talk, 3600);
3885 }
3886
3887 #[test]
3888 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
3889 let dir = tempfile::tempdir().unwrap();
3890 let path = dir.path().join("magi.toml");
3891 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
3892 let cfg = Config::load(&path).expect("must load");
3893 assert_eq!(cfg.graph.timeout_talk, 120);
3894 }
3895
3896 #[test]
3897 fn the_disk_defaults_are_the_measurements_made_up_front() {
3898 let cfg = Config::default();
3899 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
3900 assert!(cfg.disk.auto_fold);
3901 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
3902 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
3903 }
3904
3905 #[test]
3906 fn an_unset_disk_section_is_the_safe_default() {
3907 let dir = tempfile::tempdir().unwrap();
3908 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
3909 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
3910 assert_eq!(cfg.disk, Disk::default());
3911 }
3912
3913 #[test]
3914 fn env_is_available_to_templates_with_a_default() {
3915 let dir = tempfile::tempdir().unwrap();
3916 let path = dir.path().join("magi.toml");
3917 std::fs::write(
3925 &path,
3926 "[verify]\n\
3927 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
3928 \"populated={{ env | length > 0 }}\"]\n",
3929 )
3930 .unwrap();
3931 let cfg = Config::load(&path).expect("env lookup must render");
3932 assert_eq!(cfg.verify.gate[0], "cache=fallback");
3933 assert_eq!(cfg.verify.gate[1], "populated=true");
3934 }
3935
3936 #[test]
3937 fn a_broken_template_names_the_file() {
3938 let dir = tempfile::tempdir().unwrap();
3939 let path = dir.path().join("magi.toml");
3940 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
3941 let err = Config::load(&path).expect_err("must not silently ignore");
3942 assert!(err.to_string().contains("teravars"), "{err}");
3943 }
3944
3945 #[test]
3946 fn tera_syntax_in_comments_is_inert() {
3947 let dir = tempfile::tempdir().unwrap();
3951 let path = dir.path().join("magi.toml");
3952 std::fs::write(
3953 &path,
3954 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
3955 [graph]\ncandidates = 2\n",
3956 )
3957 .unwrap();
3958 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
3959 assert_eq!(cfg.graph.implementers, 2);
3960 }
3961
3962 #[test]
3963 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
3964 use std::time::Duration;
3965
3966 let mut s: AgentSpec =
3967 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
3968 let budget = Duration::from_millis(1500);
3969 assert_eq!(s.max_turn_secs, None);
3970 assert_eq!(s.turn_timeout(budget), budget);
3971 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
3972 for (cap, expected) in [
3973 (1, Duration::from_secs(1)),
3974 (2, budget),
3975 (0, Duration::ZERO),
3976 ] {
3977 s.max_turn_secs = Some(cap);
3978 let saved = toml::to_string(&s).unwrap();
3979 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
3980 assert_eq!(loaded.max_turn_secs, Some(cap));
3981 assert_eq!(loaded.turn_timeout(budget), expected);
3982 }
3983 }
3984
3985 #[test]
3986 fn opencode_defaults_to_file_delivery() {
3987 let mut s = spec("oc");
3988 s.kind = AgentKind::Opencode;
3989 assert_eq!(s.delivery(), Delivery::File);
3990 s.prompt_delivery = Some(Delivery::Argv);
3991 assert_eq!(s.delivery(), Delivery::Argv);
3992 }
3993 #[test]
3994 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
3995 let g = Graph::default();
4000 assert!(
4001 g.land,
4002 "stopping at an open PR left the watching to a human"
4003 );
4004 assert!(
4005 g.land_approval,
4006 "on-by-default land is only defensible while this is also on"
4007 );
4008 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
4009 assert!(
4010 g.hold_contested_merge,
4011 "a contested hand-off must still reach a human when approvals are off"
4012 );
4013 }
4014 #[test]
4015 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
4016 let dir = tempfile::tempdir().unwrap();
4020 let machine = dir.path().join("machine.toml");
4021 let repo = dir.path().join("magi.toml");
4022 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
4023 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
4024
4025 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4026 .expect_err("two layers naming one array must not merge silently");
4027 assert_eq!(
4028 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4029 "config-merge"
4030 );
4031 let err = err.to_string();
4032 assert!(err.contains("roles.implementers"), "{err}");
4033 assert!(err.contains("machine.toml"), "{err}");
4036 assert!(err.contains("magi.toml"), "{err}");
4037 }
4038
4039 #[test]
4040 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
4041 let dir = tempfile::tempdir().unwrap();
4044 let machine = dir.path().join("machine.toml");
4045 let repo = dir.path().join("magi.toml");
4046 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
4047 std::fs::write(
4048 &repo,
4049 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
4050 [roles]\nimplementers = [\"oc\"]\n",
4051 )
4052 .unwrap();
4053
4054 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
4055 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
4056 assert_eq!(cfg.roles.implementers, ["oc"]);
4057 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
4058 }
4059
4060 #[test]
4061 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
4062 let dir = tempfile::tempdir().unwrap();
4065 let machine = dir.path().join("machine.toml");
4066 let repo = dir.path().join("magi.toml");
4067 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4068 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4069
4070 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4071 assert_eq!(
4072 cfg.verify.gate,
4073 [
4074 "editorconfig-checker".to_owned(),
4075 "cargo make check".to_owned()
4076 ],
4077 "low-priority (machine) command first, high-priority (repo) command after"
4078 );
4079 }
4080
4081 fn load_one(body: &str) -> Result<Config> {
4082 let dir = tempfile::tempdir().unwrap();
4083 let path = dir.path().join("magi.toml");
4084 std::fs::write(&path, body).unwrap();
4085 Config::load_layers(&[path])
4086 }
4087
4088 #[test]
4089 fn worktree_setup_defaults_to_empty_and_parses_steps() {
4090 assert!(Config::default().worktree.setup.is_empty());
4091 let cfg = load_one(
4092 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
4093 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
4094 )
4095 .unwrap();
4096 assert_eq!(cfg.worktree.setup.len(), 3);
4097 assert!(cfg.worktree.setup[1].optional);
4098 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
4099 }
4100
4101 #[test]
4102 fn worktree_setup_rejects_malformed_steps() {
4103 for bad in [
4104 "{ copy = \"a\", run = \"b\" }",
4105 "{ optional = true }",
4106 "{ copy = \"a -> ../b\" }",
4107 "{ copy = \"a -> /abs\" }",
4108 "{ copy = \"a -> .git/config\" }",
4109 "{ run = \"b\", optional = true }",
4110 "{ copy = \"a\", timeout_secs = 3 }",
4111 "{ run = \"b\", bogus = 1 }",
4112 ] {
4113 let body = format!("[worktree]\nsetup = [{bad}]\n");
4114 assert!(load_one(&body).is_err(), "{bad}");
4115 }
4116 }
4117
4118 #[test]
4119 fn worktree_setup_in_two_layers_is_refused() {
4120 let dir = tempfile::tempdir().unwrap();
4121 let machine = dir.path().join("machine.toml");
4122 let repo = dir.path().join("magi.toml");
4123 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4124 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4125 assert!(Config::load_layers(&[machine, repo]).is_err());
4126 }
4127
4128 #[test]
4129 fn starter_toml_documents_worktree_setup() {
4130 let starter = Config::starter_toml();
4131 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4132 let body = starter.replace("# [worktree]", "[worktree]");
4134 let mut out = String::new();
4135 let mut live = false;
4136 for line in body.lines() {
4137 if line == "[worktree]" {
4138 live = true;
4139 } else if live && !line.starts_with("# ") {
4140 live = false;
4141 }
4142 out.push_str(&if live {
4143 line.replacen("# ", "", 1)
4144 } else {
4145 line.to_owned()
4146 });
4147 out.push('\n');
4148 }
4149 let cfg = load_one(&out).expect("uncommented example loads");
4150 assert_eq!(cfg.worktree.setup.len(), 3);
4151 }
4152
4153 #[test]
4154 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4155 let dir = tempfile::tempdir().unwrap();
4156 let machine = dir.path().join("machine.toml");
4157 let repo = dir.path().join("magi.toml");
4158 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4159 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4160
4161 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4162 assert_eq!(
4163 cfg.verify.e2e,
4164 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4165 );
4166 }
4167
4168 #[test]
4169 fn two_layers_declaring_repos_roots_are_both_scanned() {
4170 let dir = tempfile::tempdir().unwrap();
4171 let machine = dir.path().join("machine.toml");
4172 let repo = dir.path().join("magi.toml");
4173 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4174 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4175
4176 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4177 assert_eq!(
4178 cfg.repos.roots,
4179 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4180 );
4181 }
4182
4183 #[test]
4184 fn duplicate_gate_commands_across_layers_both_run() {
4185 let dir = tempfile::tempdir().unwrap();
4188 let machine = dir.path().join("machine.toml");
4189 let repo = dir.path().join("magi.toml");
4190 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4191 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4192
4193 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4194 assert_eq!(
4195 cfg.verify.gate,
4196 ["same-command".to_owned(), "same-command".to_owned()]
4197 );
4198 }
4199
4200 #[test]
4201 fn notify_command_is_still_refused_across_two_layers() {
4202 let dir = tempfile::tempdir().unwrap();
4204 let machine = dir.path().join("machine.toml");
4205 let repo = dir.path().join("magi.toml");
4206 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4207 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4208
4209 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4210 .expect_err("an argv split across layers must not concatenate");
4211 assert_eq!(
4212 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4213 "config-merge"
4214 );
4215 let err = err.to_string();
4216 assert!(err.contains("notify.command"), "{err}");
4217 assert!(err.contains("machine.toml"), "{err}");
4218 assert!(err.contains("magi.toml"), "{err}");
4219 }
4220
4221 #[test]
4222 fn one_layer_declaring_verify_gate_runs_unchanged() {
4223 let dir = tempfile::tempdir().unwrap();
4226 let path = dir.path().join("magi.toml");
4227 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4228
4229 let cfg = Config::load(&path).expect("single layer must still load");
4230 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4231 }
4232
4233 #[test]
4234 fn layered_parse_failures_name_the_failing_input() {
4235 let dir = tempfile::tempdir().unwrap();
4236 let a = dir.path().join("a.toml");
4237 let b = dir.path().join("b.toml");
4238 std::fs::write(&a, "[graph").unwrap();
4239 std::fs::write(&b, "[verify").unwrap();
4240 let paths = [a.clone(), b.clone()];
4241 let first = Config::load_layers(&paths).unwrap_err();
4242 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4243 assert_eq!(first_cause.stage, "config-parse");
4244 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4245 std::fs::write(&a, "").unwrap();
4246 let second = Config::load_layers(&paths).unwrap_err();
4247 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4248 assert_eq!(second_cause.stage, "config-parse");
4249 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4250 assert_ne!(first_cause.target, second_cause.target);
4251 }
4252
4253 #[test]
4254 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4255 let dir = tempfile::tempdir().unwrap();
4256 let machine = dir.path().join("machine.toml");
4257 let repo = dir.path().join("magi.toml");
4258 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4259 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4260 let paths = vec![machine.clone(), repo.clone()];
4261
4262 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4263 let described =
4264 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4265 assert!(described.contains("editorconfig-checker && cargo make check"));
4266 assert!(
4267 described.contains(&machine.display().to_string()),
4268 "{described}"
4269 );
4270 assert!(
4271 described.contains(&repo.display().to_string()),
4272 "{described}"
4273 );
4274
4275 let single = vec![repo.clone()];
4277 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4278 let solo_described =
4279 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4280 assert_eq!(solo_described, "cargo make check");
4281 }
4282
4283 mod remote_layers {
4284 use super::*;
4285
4286 fn git(dir: &Path, args: &[&str]) {
4287 use crate::proc::Quiet as _;
4288 let out = std::process::Command::new("git")
4289 .args(args)
4290 .quiet()
4291 .current_dir(dir)
4292 .output()
4293 .unwrap();
4294 assert!(out.status.success(), "git {args:?}: {out:?}");
4295 }
4296
4297 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4300 let tmp = tempfile::tempdir().unwrap();
4301 let bare = tmp.path().join("o.git");
4302 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4303 let repo = tmp.path().join("repo");
4304 std::fs::create_dir_all(&repo).unwrap();
4305 git(&repo, &["init", "-b", "trunk"]);
4306 git(&repo, &["config", "user.name", "t"]);
4307 git(&repo, &["config", "user.email", "t@example.com"]);
4308 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4309 git(&repo, &["add", "-A"]);
4310 git(&repo, &["commit", "-m", "x"]);
4311 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4312 git(&repo, &["push", "origin", "trunk"]);
4313 git(&repo, &["fetch", "origin"]);
4314 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4315 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4316 (tmp, repo)
4317 }
4318
4319 #[tokio::test]
4320 async fn branch_owner_holds_only_add_literal_true_values() {
4321 for (text, expected) in [
4322 ("[graph]\nland_approval = true\n", true),
4323 ("[graph]\nland_approval = false\n", false),
4324 ("[graph]\nland = true\n", false),
4325 ("[graph\n", false),
4326 ("[graph]\nland_approval = \"yes\"\n", false),
4327 ("[graph]\nland_approval = 1\n", false),
4328 ] {
4329 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4330 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4331 let (holds, _) = branch_owner_holds(&repo, &head).await;
4332 assert_eq!(
4333 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4334 expected
4335 );
4336 assert!(
4337 !holds
4338 .iter()
4339 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4340 );
4341 for base in [false, true] {
4342 let mut cfg = Config::default();
4343 cfg.graph.land_approval = base;
4344 let mut state = crate::run::RunState::new(
4345 repo.clone(),
4346 "trunk".into(),
4347 head.clone(),
4348 "review".into(),
4349 cfg,
4350 );
4351 state.observe_branch_owner_holds(&head).await;
4352 assert!(
4353 state.branch_owner_holds.is_empty(),
4354 "competition candidates are excluded"
4355 );
4356 state.reviewed_commits = Some(Vec::new());
4357 state.observe_branch_owner_holds(&head).await;
4358 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4359 }
4360 }
4361 }
4362
4363 #[tokio::test]
4364 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4365 let (_tmp, repo) = fixture(
4366 "[graph]\nland_approval = true\n",
4367 "[graph]\nland_approval = true\n",
4368 );
4369 git(&repo, &["rm", "magi.toml"]);
4370 std::fs::create_dir(repo.join(".magi")).unwrap();
4371 std::fs::write(
4372 repo.join(".magi/config.toml"),
4373 "[graph]\nhold_contested_merge = true\n",
4374 )
4375 .unwrap();
4376 git(&repo, &["add", "."]);
4377 git(&repo, &["commit", "-m", "nested hold"]);
4378 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4379 let (holds, _) = branch_owner_holds(&repo, &head).await;
4380 assert_eq!(
4381 holds,
4382 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4383 );
4384 let (holds, diagnostics) =
4385 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4386 assert!(holds.is_empty());
4387 assert!(!diagnostics.is_empty());
4388 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4389 assert!(holds.is_empty());
4390 assert!(!diagnostics.is_empty());
4391 for base in [false, true] {
4392 let mut cfg = Config::default();
4393 cfg.graph.land_approval = base;
4394 let mut state = crate::run::RunState::new(
4395 repo.clone(),
4396 "trunk".into(),
4397 head.clone(),
4398 "review".into(),
4399 cfg,
4400 );
4401 state.reviewed_commits = Some(Vec::new());
4402 state.observe_branch_owner_holds(&head).await;
4403 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4404 state
4405 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4406 .await;
4407 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4408 }
4409 }
4410
4411 #[test]
4412 fn reads_the_remote_blob_not_the_working_tree() {
4413 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4414 let (cfg, _) = Config::discover(&repo, None).unwrap();
4415 assert_eq!(cfg.graph.implementers, 2);
4416 }
4417
4418 #[test]
4419 fn detached_head_still_reads_the_remote() {
4420 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4421 git(&repo, &["checkout", "--detach"]);
4422 let (cfg, _) = Config::discover(&repo, None).unwrap();
4423 assert_eq!(cfg.graph.implementers, 2);
4424 }
4425
4426 #[test]
4427 fn a_missing_ref_is_an_error_not_a_fallback() {
4428 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4429 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4430 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4431 assert!(err.contains("origin"), "{err}");
4432 }
4433
4434 #[test]
4435 fn merge_base_in_the_checkout_locates_the_ref() {
4436 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4437 assert!(Config::discover(&repo, None).is_err());
4438 }
4439
4440 #[test]
4441 fn the_magi_dir_layer_is_read_too() {
4442 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4443 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4444 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4445 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4446 git(&repo, &["add", "-A"]);
4447 git(&repo, &["commit", "-m", "y"]);
4448 git(&repo, &["push", "origin", "trunk"]);
4449 git(&repo, &["fetch", "origin"]);
4450 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4451 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4452 assert_eq!(layers.len(), 2);
4453 }
4454
4455 #[test]
4456 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4457 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4458 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4459 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4460 git(&repo, &["add", "-A"]);
4461 git(&repo, &["commit", "-m", "inc"]);
4462 git(&repo, &["push", "origin", "trunk"]);
4463 git(&repo, &["fetch", "origin"]);
4464 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4466 let (cfg, _) = Config::discover(&repo, None).unwrap();
4467 assert_eq!(cfg.graph.implementers, 2);
4468 }
4469
4470 #[test]
4471 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4472 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4473 let m = t.path().join("machine.toml");
4474 std::fs::write(
4475 &m,
4476 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4477 )
4478 .unwrap();
4479 let (remote, base) = {
4480 let probe = probe_merge(&m, &repo).unwrap();
4481 (probe.remote, probe.base)
4482 };
4483 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4484 }
4485
4486 #[test]
4487 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4488 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4489 let m = t.path().join("machine.toml");
4490 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4491 let probe = probe_merge(&m, &repo).unwrap();
4492 assert_eq!(probe.base.as_deref(), Some("repo"));
4493 }
4494
4495 #[test]
4496 fn every_include_form_is_recognised() {
4497 assert!(declares_include("include = [\"a.toml\"]\n"));
4498 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4499 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4500 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4501 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4502 }
4503
4504 #[test]
4505 fn an_explicit_config_is_read_as_named() {
4506 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4507 let own = t.path().join("own.toml");
4508 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4509 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4510 assert_eq!(cfg.graph.implementers, 4);
4511 }
4512
4513 #[test]
4514 fn discover_fetched_fails_when_the_fetch_does() {
4515 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4516 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4517 let rt = tokio::runtime::Builder::new_current_thread()
4518 .enable_all()
4519 .build()
4520 .unwrap();
4521 let err = rt
4522 .block_on(Config::discover_fetched(&repo, None))
4523 .unwrap_err();
4524 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4525 }
4526
4527 #[test]
4528 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4529 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4530 let remote = tmp.path().join("o.git");
4531 let offline = tmp.path().join("offline.git");
4532 std::fs::rename(&remote, &offline).unwrap();
4533 let rt = tokio::runtime::Builder::new_current_thread()
4534 .enable_all()
4535 .build()
4536 .unwrap();
4537 let fetch = rt
4538 .block_on(Config::discover_fetched(&repo, None))
4539 .unwrap_err();
4540 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4541 assert_eq!(fetch_cause.stage, "config-fetch");
4542 assert_eq!(fetch_cause.target, "origin/trunk");
4543
4544 std::fs::rename(&offline, &remote).unwrap();
4545 let parse = rt
4546 .block_on(Config::discover_fetched(&repo, None))
4547 .unwrap_err();
4548 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4549 assert_eq!(parse_cause.stage, "config-parse");
4550 assert!(parse_cause.target.contains("magi.toml"));
4551 assert!(
4552 !parse_cause.target.contains("/magi/config/"),
4553 "cache commit paths are incidental"
4554 );
4555 assert_ne!(fetch_cause.stage, parse_cause.stage);
4556 }
4557
4558 #[test]
4559 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4560 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4563 git(&repo, &["remote", "set-head", "origin", "-d"]);
4564 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4565 git(
4566 &repo,
4567 &["config", "remote.origin.followRemoteHEAD", "never"],
4568 );
4569 let rt = tokio::runtime::Builder::new_current_thread()
4570 .enable_all()
4571 .build()
4572 .unwrap();
4573 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4574 assert_eq!(cfg.graph.implementers, 2);
4575 }
4576
4577 #[test]
4578 fn a_non_git_directory_reads_its_files() {
4579 let dir = tempfile::tempdir().unwrap();
4580 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4581 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4582 assert_eq!(cfg.graph.implementers, 4);
4583 }
4584 }
4585
4586 #[test]
4587 fn github_language_defaults_to_english_and_accepts_japanese() {
4588 let default: Graph = toml::from_str("").unwrap();
4589 assert_eq!(default.github_language, "en");
4590 assert!(default.github_english() && default.language_gate());
4591 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4592 assert!(!ja.github_english() && !ja.language_gate());
4593 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4595 assert!(only_ops.language_gate());
4596 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4597 assert!(!off.language_gate() && off.github_english());
4598 assert!(Config::starter_toml().contains("github_language = \"en\""));
4599 }
4600}