1use std::collections::BTreeMap;
44use std::path::{Path, PathBuf};
45
46use anyhow::{Context as _, Result, bail};
47use serde::{Deserialize, Serialize};
48
49#[derive(Debug, thiserror::Error)]
52#[error("{stage}: {target}")]
53pub(crate) struct ConfigFailure {
54 pub(crate) stage: &'static str,
55 pub(crate) target: String,
56}
57
58impl ConfigFailure {
59 fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
60 let stage = match error {
61 teravars::Error::Io(_) => "config-read",
62 teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
63 teravars::Error::Render(_) => "config-template",
64 teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
65 "config-include"
66 }
67 _ => "config-render",
68 };
69 Self::layers(stage, paths)
70 }
71
72 fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
73 let targets: Vec<_> = paths
74 .iter()
75 .map(|path| {
76 path.ancestors()
79 .find(|p| p.join(REPO_MARKER).is_file())
80 .and_then(|root| path.strip_prefix(root).ok())
81 .unwrap_or(path)
82 .to_string_lossy()
83 .into_owned()
84 })
85 .collect();
86 Self {
87 stage,
88 target: serde_json::to_string(&targets).expect("config paths"),
89 }
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
95#[serde(rename_all = "lowercase")]
96pub enum AgentKind {
97 Claude,
99 Opencode,
101 Antigravity,
105 Codex,
109 Omp,
115 Command,
117}
118
119impl AgentKind {
120 pub fn program(self) -> Option<&'static str> {
122 match self {
123 Self::Claude => Some("claude"),
124 Self::Opencode => Some("opencode"),
125 Self::Antigravity => Some("agy"),
126 Self::Codex => Some("codex"),
127 Self::Omp => Some("omp"),
128 Self::Command => None,
129 }
130 }
131
132 pub fn as_str(self) -> &'static str {
134 match self {
135 Self::Claude => "claude",
136 Self::Opencode => "opencode",
137 Self::Antigravity => "antigravity",
138 Self::Codex => "codex",
139 Self::Omp => "omp",
140 Self::Command => "command",
141 }
142 }
143
144 pub const ALL: [Self; 6] = [
152 Self::Claude,
153 Self::Opencode,
154 Self::Antigravity,
155 Self::Codex,
156 Self::Omp,
157 Self::Command,
158 ];
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
163#[serde(rename_all = "lowercase")]
164pub enum Delivery {
165 Stdin,
167 Argv,
169 File,
171}
172
173#[derive(Debug, Clone, Deserialize, Serialize)]
175#[serde(deny_unknown_fields)]
176pub struct AgentSpec {
177 pub id: String,
179 pub kind: AgentKind,
181 #[serde(default)]
183 pub model: Option<String>,
184 #[serde(default)]
187 pub command: Vec<String>,
188 #[serde(default)]
190 pub extra_args: Vec<String>,
191 #[serde(default)]
193 pub env: BTreeMap<String, String>,
194 #[serde(default)]
196 pub prompt_delivery: Option<Delivery>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub max_turn_secs: Option<u64>,
201}
202
203impl AgentSpec {
204 pub fn turn_timeout(&self, budget: std::time::Duration) -> std::time::Duration {
206 self.max_turn_secs.map_or(budget, |secs| {
207 budget.min(std::time::Duration::from_secs(secs))
208 })
209 }
210
211 pub fn delivery(&self) -> Delivery {
217 self.prompt_delivery.unwrap_or(match self.kind {
218 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
219 AgentKind::Codex => Delivery::Stdin,
223 AgentKind::Omp => Delivery::Stdin,
227 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
228 })
229 }
230
231 pub fn display(&self) -> String {
233 match &self.model {
234 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
235 None => format!("{} ({})", self.id, self.kind.as_str()),
236 }
237 }
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
247#[serde(untagged)]
248pub enum AgentChoice {
249 One(String),
251 Chain(Vec<String>),
253}
254
255impl AgentChoice {
256 pub fn ids(&self) -> Vec<&str> {
258 let all: Vec<&str> = match self {
259 Self::One(id) => vec![id.as_str()],
260 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
261 };
262 all.into_iter()
263 .map(str::trim)
264 .filter(|id| !id.is_empty())
265 .collect()
266 }
267
268 pub fn primary(&self) -> Option<&str> {
270 self.ids().into_iter().next()
271 }
272}
273
274impl From<&str> for AgentChoice {
275 fn from(id: &str) -> Self {
276 Self::One(id.to_owned())
277 }
278}
279
280pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
282 choice.and_then(AgentChoice::primary)
283}
284
285#[derive(Debug, Clone, Default, Deserialize, Serialize)]
288#[serde(deny_unknown_fields, default)]
289pub struct Roles {
290 pub implementers: Vec<String>,
292 pub judges: Vec<String>,
294 pub reviewers: Vec<String>,
296 pub fixer: Option<AgentChoice>,
305 pub chatter: Option<AgentChoice>,
319 pub dupes_judge: Option<AgentChoice>,
323 pub conductor: Option<AgentChoice>,
336 pub advisors: Vec<String>,
347 pub synthesizer: Option<AgentChoice>,
360 pub language_judge: Option<AgentChoice>,
369}
370
371#[derive(Debug, Clone, Deserialize, Serialize)]
373#[serde(deny_unknown_fields, default)]
374pub struct Graph {
375 #[serde(rename = "editing_network", skip_serializing)]
379 pub retired_editing_network: Option<serde::de::IgnoredAny>,
380 pub github_text_guard: bool,
382 pub github_language: String,
388 #[serde(alias = "candidates")]
420 pub implementers: usize,
421 #[serde(default)]
423 pub selected_implementer: Option<String>,
424 pub judges: usize,
426 pub deliberate_rounds: usize,
428 pub reviewers: usize,
436 pub review_rounds: usize,
438 pub gate_fix_rounds: usize,
444 pub max_parallel: usize,
446 pub language: String,
448 pub sessions: bool,
456 pub timeout_implement: u64,
458 pub timeout_judge: u64,
460 pub timeout_review: u64,
462 pub timeout_verify: Option<u64>,
471 pub timeout_fix: u64,
473 pub timeout_talk: u64,
481 pub timeout_resource_wait: u64,
490 pub retries: usize,
492 pub worktree_root: Option<PathBuf>,
494 pub land: bool,
507 pub land_rounds: usize,
509 pub rerun_flaky_checks: bool,
517 pub land_approval: bool,
528 pub hold_contested_merge: bool,
539 pub question_routing: bool,
542 pub file_followups: bool,
549 pub release_deputy_followups: bool,
557 pub answer_timeout: u64,
561 pub incomplete_review: IncompleteReviewPolicy,
564 pub e2e_every_round: bool,
582 pub rerun_failed_e2e: bool,
594 pub advise: bool,
608 pub advisors: usize,
613 pub graft_runner_up: bool,
622}
623
624impl Default for Graph {
625 fn default() -> Self {
626 Self {
627 github_text_guard: true,
628 github_language: "en".into(),
629 implementers: 1,
630 selected_implementer: None,
631 retired_editing_network: None,
632 judges: 3,
633 deliberate_rounds: 1,
634 reviewers: 3,
635 review_rounds: 6,
636 gate_fix_rounds: 1,
637 max_parallel: 4,
638 language: "en".to_owned(),
639 sessions: true,
640 timeout_implement: 3600,
641 timeout_judge: 1200,
642 timeout_review: 1200,
643 timeout_verify: None,
644 timeout_fix: 1800,
645 timeout_talk: 3600,
646 timeout_resource_wait: 1800,
647 retries: 1,
648 worktree_root: None,
649 land: true,
650 land_rounds: 4,
651 rerun_flaky_checks: true,
652 land_approval: true,
653 hold_contested_merge: true,
654 question_routing: true,
655 file_followups: true,
656 release_deputy_followups: true,
657 answer_timeout: 86_400,
658 incomplete_review: IncompleteReviewPolicy::Block,
659 e2e_every_round: false,
660 rerun_failed_e2e: true,
661 advise: true,
662 advisors: 3,
663 graft_runner_up: true,
664 }
665 }
666}
667
668impl Graph {
669 pub fn verify_timeout(&self) -> u64 {
673 self.timeout_verify.unwrap_or(self.timeout_review)
674 }
675
676 pub fn language_gate(&self) -> bool {
679 self.github_text_guard && self.github_english()
680 }
681
682 pub fn github_english(&self) -> bool {
684 crate::lang::is_english(&self.github_language)
685 }
686}
687
688#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
695#[serde(rename_all = "lowercase")]
696pub enum IncompleteReviewPolicy {
697 Block,
701 Warn,
706}
707
708#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
710#[serde(rename_all = "lowercase")]
711pub enum LeakPolicy {
712 Warn,
714 Redact,
716 Fail,
718}
719
720#[derive(Debug, Clone, Deserialize, Serialize)]
727#[serde(deny_unknown_fields, default)]
728pub struct Blind {
729 pub commit_msg_hook: bool,
732 pub strip_lines: Vec<String>,
736 pub vendor_tokens: Vec<String>,
738 pub on_leak: LeakPolicy,
740 pub seed: Option<u64>,
743}
744
745impl Default for Blind {
746 fn default() -> Self {
747 Self {
748 commit_msg_hook: true,
749 strip_lines: [
750 "Co-Authored-By:",
751 "Signed-off-by:",
752 "Assisted-by:",
753 "Generated-by:",
754 "Generated with",
755 "\u{1f916}",
756 ]
757 .iter()
758 .map(|s| (*s).to_owned())
759 .collect(),
760 vendor_tokens: [
761 "claude",
762 "anthropic",
763 "codex",
764 "openai",
765 "chatgpt",
766 "gemini",
767 "grok",
768 "xai",
769 "copilot",
770 "opencode",
771 "qoder",
772 "cursor",
773 "\u{1f916}",
774 ]
775 .iter()
776 .map(|s| (*s).to_owned())
777 .collect(),
778 on_leak: LeakPolicy::Warn,
779 seed: None,
780 }
781 }
782}
783
784#[derive(Debug, Clone, Default, Deserialize, Serialize)]
786#[serde(deny_unknown_fields, default)]
787pub struct Verify {
788 pub e2e: Vec<String>,
791 pub gate: Vec<String>,
793 #[serde(default)]
804 pub pre_gate: Vec<String>,
805 pub shell: Option<Vec<String>>,
808}
809
810impl Verify {
811 pub fn cache_dir(&self) -> Option<PathBuf> {
817 self.e2e
818 .iter()
819 .chain(self.gate.iter())
820 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
821 }
822
823 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
826 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
827 crate::cache::extract_manifest_paths(&all)
828 }
829}
830
831#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
833#[serde(deny_unknown_fields, default)]
834pub struct Worktree {
835 pub setup: Vec<SetupStep>,
838 pub pre_clean: Vec<PreCleanStep>,
840}
841
842#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
844#[serde(deny_unknown_fields)]
845pub struct PreCleanStep {
846 pub run: String,
848 pub timeout_secs: Option<u64>,
850}
851
852#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
854#[serde(deny_unknown_fields, default)]
855pub struct SetupStep {
856 pub copy: Option<String>,
859 pub optional: bool,
861 pub run: Option<String>,
863 pub timeout_secs: Option<u64>,
866}
867
868impl Worktree {
869 pub fn validate(&self) -> Result<()> {
871 for (i, step) in self.pre_clean.iter().enumerate() {
872 if step.run.trim().is_empty() || step.timeout_secs == Some(0) {
873 bail!(
874 "[worktree] pre_clean step {} requires a nonempty run and positive timeout",
875 i + 1
876 );
877 }
878 }
879 for (i, step) in self.setup.iter().enumerate() {
880 let n = i + 1;
881 match (&step.copy, &step.run) {
882 (Some(c), None) => {
883 if step.timeout_secs.is_some() {
884 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
885 }
886 crate::worktree_setup::validate_copy(c)
887 .with_context(|| format!("[worktree] setup step {n}"))?;
888 }
889 (None, Some(r)) => {
890 if r.trim().is_empty() {
891 bail!("[worktree] setup step {n}: `run` is empty");
892 }
893 if step.optional {
894 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
895 }
896 }
897 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
898 }
899 }
900 Ok(())
901 }
902}
903
904#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
914#[serde(deny_unknown_fields, default)]
915pub struct Disk {
916 pub min_free_bytes: u64,
925 pub auto_fold: bool,
931 pub fold_grace_secs: u64,
939 pub cache_limit_bytes: u64,
951 pub worktree_limit_bytes: u64,
953 pub worktree_reclaim_bytes: u64,
957 pub retained_attempt_limit: usize,
961}
962
963impl Default for Disk {
964 fn default() -> Self {
965 Self {
966 min_free_bytes: 8 * 1024 * 1024 * 1024,
967 auto_fold: true,
968 fold_grace_secs: 6 * 60 * 60,
969 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
970 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
971 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
972 retained_attempt_limit: 8,
973 }
974 }
975}
976
977#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
979#[serde(rename_all = "lowercase")]
980pub enum MergeMode {
981 None,
984 Local,
987 Pr,
991}
992
993#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
1007#[serde(rename_all = "lowercase")]
1008pub enum MergeStyle {
1009 #[default]
1014 Merge,
1015 Squash,
1021 Rebase,
1027}
1028
1029#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1031#[serde(rename_all = "lowercase")]
1032pub enum MergeCi {
1033 #[default]
1035 Expected,
1036 None,
1038}
1039
1040impl MergeCi {
1041 pub fn expectation(self) -> crate::land::CiExpectation {
1043 match self {
1044 Self::Expected => crate::land::CiExpectation::Expected,
1045 Self::None => crate::land::CiExpectation::Absent,
1046 }
1047 }
1048}
1049
1050#[derive(Debug, Clone, Deserialize, Serialize)]
1052#[serde(deny_unknown_fields, default)]
1053pub struct Merge {
1054 pub mode: MergeMode,
1057 pub ci: MergeCi,
1059 pub base: Option<String>,
1061 pub style: MergeStyle,
1064 pub remote: String,
1066 pub release_bump: bool,
1079}
1080
1081impl Default for Merge {
1082 fn default() -> Self {
1083 Self {
1084 mode: MergeMode::None,
1085 ci: MergeCi::Expected,
1086 base: None,
1087 style: MergeStyle::default(),
1088 remote: "origin".to_owned(),
1089 release_bump: true,
1090 }
1091 }
1092}
1093
1094#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1096#[serde(rename_all = "lowercase")]
1097pub enum UpdateMode {
1098 Off,
1100 Notify,
1103 Install,
1105}
1106
1107#[derive(Debug, Clone, Deserialize, Serialize)]
1109#[serde(deny_unknown_fields, default)]
1110pub struct Update {
1111 pub mode: UpdateMode,
1113 pub interval: Option<String>,
1115 pub auto_restart: bool,
1117}
1118
1119impl Default for Update {
1120 fn default() -> Self {
1121 Self {
1122 mode: UpdateMode::Notify,
1123 interval: None,
1124 auto_restart: false,
1125 }
1126 }
1127}
1128
1129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1131#[serde(rename_all = "lowercase")]
1132pub enum ReleaseMode {
1133 #[default]
1136 Actions,
1137 Local,
1142}
1143
1144#[derive(Debug, Clone, Deserialize, Serialize)]
1146#[serde(deny_unknown_fields, default)]
1147pub struct Release {
1148 pub mode: ReleaseMode,
1151 pub commands: Vec<String>,
1158 pub timeout_minutes: u64,
1160 pub version_files: Vec<VersionFile>,
1168}
1169
1170#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1172#[serde(rename_all = "lowercase")]
1173pub enum VersionKind {
1174 Cargo,
1176 Json,
1178}
1179
1180#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1182#[serde(deny_unknown_fields)]
1183pub struct VersionFile {
1184 pub path: String,
1186 pub kind: VersionKind,
1188}
1189
1190impl Default for Release {
1191 fn default() -> Self {
1192 Self {
1193 mode: ReleaseMode::Actions,
1194 commands: Vec::new(),
1195 timeout_minutes: 30,
1196 version_files: Vec::new(),
1197 }
1198 }
1199}
1200
1201impl Release {
1202 pub fn validate(&self) -> Result<()> {
1204 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1205 }
1206
1207 pub fn is_local(&self) -> bool {
1209 self.mode == ReleaseMode::Local
1210 }
1211}
1212
1213#[derive(Debug, Clone, Deserialize, Serialize)]
1215#[serde(try_from = "CoordinationFields")]
1216pub struct Coordination {
1217 pub contract_file: String,
1219 pub contract_token: String,
1221 pub lock_file: String,
1223}
1224
1225#[derive(Deserialize, Default)]
1226#[serde(deny_unknown_fields, default)]
1227struct CoordinationFields {
1228 contract_file: String,
1229 contract_token: String,
1230 lock_file: String,
1231}
1232
1233impl TryFrom<CoordinationFields> for Coordination {
1234 type Error = anyhow::Error;
1235
1236 fn try_from(fields: CoordinationFields) -> Result<Self> {
1237 for (key, name) in [
1238 ("coordination.contract_file", &fields.contract_file),
1239 ("coordination.lock_file", &fields.lock_file),
1240 ] {
1241 if name.trim().is_empty()
1242 || name != name.trim()
1243 || name == "."
1244 || name.contains("..")
1245 || name.contains(['/', '\\', ':', '\0'])
1246 {
1247 bail!(
1248 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1249 );
1250 }
1251 }
1252 let token = &fields.contract_token;
1253 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1254 bail!(
1255 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1256 );
1257 }
1258 Ok(Self {
1259 contract_file: fields.contract_file,
1260 contract_token: fields.contract_token,
1261 lock_file: fields.lock_file,
1262 })
1263 }
1264}
1265
1266#[cfg(test)]
1267pub(crate) fn test_coordination() -> Option<Coordination> {
1268 Some(Coordination {
1269 contract_file: "updater.contract".into(),
1270 contract_token: "test-protocol-v1".into(),
1271 lock_file: "updater.lock".into(),
1272 })
1273}
1274
1275#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1277#[serde(deny_unknown_fields, default)]
1278pub struct Config {
1279 pub coordination: Option<Coordination>,
1281 pub agents: Vec<AgentSpec>,
1283 pub roles: Roles,
1285 pub graph: Graph,
1287 pub blind: Blind,
1289 pub verify: Verify,
1291 pub worktree: Worktree,
1293 pub disk: Disk,
1295 pub merge: Merge,
1297 pub update: Update,
1299 pub prompts: Prompts,
1301 pub notify: Notify,
1303 pub repos: Repos,
1306 pub talk: Talk,
1308 pub daemon: Daemon,
1310 pub release: Release,
1312 pub context_windows: BTreeMap<String, u64>,
1315}
1316
1317const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1327 ("claude-opus-4", 200_000),
1328 ("claude-sonnet-4", 200_000),
1329 ("claude-haiku-4", 200_000),
1330 ("claude-3", 200_000),
1331 ("opus", 200_000),
1332 ("sonnet", 200_000),
1333 ("haiku", 200_000),
1334 ("gpt-5", 400_000),
1335 ("gpt-4.1", 1_000_000),
1336 ("gpt-4o", 128_000),
1337 ("o3", 200_000),
1338 ("o4-mini", 200_000),
1339 ("gemini-2.5", 1_000_000),
1340 ("deepseek", 128_000),
1341];
1342
1343impl Config {
1344 pub fn context_window(&self, model: &str) -> Option<u64> {
1349 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1350 let mut best: Option<(usize, u64)> = None;
1351 for (key, window) in entries {
1352 if key == model {
1353 return Some(window);
1354 }
1355 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1356 best = Some((key.len(), window));
1357 }
1358 }
1359 best.map(|(_, w)| w)
1360 }
1361 lookup(
1362 model,
1363 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1364 )
1365 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1366 }
1367}
1368
1369#[derive(Debug, Clone, Deserialize, Serialize)]
1379#[serde(deny_unknown_fields, default)]
1380pub struct Daemon {
1381 pub max_concurrent_runs: usize,
1402 pub pause_for_interrupts: bool,
1418 pub max_deputies: usize,
1425 pub release_stall_minutes: u64,
1432}
1433
1434impl Default for Daemon {
1435 fn default() -> Self {
1436 Self {
1437 max_concurrent_runs: 1,
1438 pause_for_interrupts: false,
1439 max_deputies: 2,
1440 release_stall_minutes: 60,
1441 }
1442 }
1443}
1444
1445#[derive(Debug, Clone, Deserialize, Serialize)]
1457#[serde(deny_unknown_fields, default)]
1458pub struct Repos {
1459 pub roots: Vec<PathBuf>,
1463 pub auto_clone: bool,
1465 pub clone_command: Option<Vec<String>>,
1469 pub scan_ttl: u64,
1476 pub fetch_interval: u64,
1481}
1482
1483impl Default for Repos {
1484 fn default() -> Self {
1485 Self {
1486 roots: Vec::new(),
1487 auto_clone: false,
1488 clone_command: None,
1489 scan_ttl: 86_400,
1490 fetch_interval: 600,
1491 }
1492 }
1493}
1494
1495#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1511#[serde(deny_unknown_fields, default)]
1512pub struct Prompts {
1513 pub all: String,
1515 pub implement: String,
1517 pub judge: String,
1519 pub review: String,
1521 pub fix: String,
1523}
1524
1525impl Prompts {
1526 pub fn overlay(&self, node: &str) -> Option<String> {
1531 let specific = match node {
1532 "implement" => &self.implement,
1533 "judge" | "vote" | "deliberate" => &self.judge,
1534 "review" => &self.review,
1535 "fix" => &self.fix,
1536 _ => "",
1537 };
1538 let mut parts: Vec<&str> = Vec::new();
1539 for p in [self.all.trim(), specific.trim()] {
1540 if !p.is_empty() {
1541 parts.push(p);
1542 }
1543 }
1544 if parts.is_empty() {
1545 return None;
1546 }
1547 Some(parts.join("\n\n"))
1548 }
1549}
1550
1551#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1558#[serde(deny_unknown_fields, default)]
1559pub struct Notify {
1560 pub command: Vec<String>,
1563}
1564
1565#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1567#[serde(deny_unknown_fields, default)]
1568pub struct Talk {
1569 pub allow_write: bool,
1578 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1580 pub standing_authorization: bool,
1581 pub personas: Vec<PersonaSpec>,
1586 pub operator_name: Option<String>,
1590}
1591
1592pub const OPERATOR_NAME_MAX: usize = 64;
1594
1595impl Talk {
1596 pub fn operator_name(&self) -> Option<&str> {
1598 self.operator_name
1599 .as_deref()
1600 .map(str::trim)
1601 .filter(|n| !n.is_empty())
1602 }
1603}
1604
1605#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1607#[serde(deny_unknown_fields)]
1608pub struct PersonaSpec {
1609 pub id: String,
1611 #[serde(default)]
1614 pub name: String,
1615 #[serde(default)]
1618 pub prompt: String,
1619 #[serde(default, skip_serializing_if = "Option::is_none")]
1623 pub icon: Option<String>,
1624}
1625
1626#[derive(Debug, Clone)]
1628pub struct ResolvedRoles {
1629 pub implementers: Vec<AgentSpec>,
1631 pub judges: Vec<AgentSpec>,
1633 pub reviewers: Vec<AgentSpec>,
1635 pub fixer: Option<Vec<AgentSpec>>,
1640 pub conductor: AgentSpec,
1642 pub implementer_roster: Vec<AgentSpec>,
1650 pub judge_roster: Vec<AgentSpec>,
1654 pub reviewer_roster: Vec<AgentSpec>,
1656}
1657
1658fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1665 let mut out = Vec::new();
1666 for (k, v) in table {
1667 if prefix.is_empty() && k == "vars" {
1668 continue;
1669 }
1670 let path = if prefix.is_empty() {
1671 k.clone()
1672 } else {
1673 format!("{prefix}.{k}")
1674 };
1675 match v {
1676 toml::Value::Array(_) => out.push(path),
1677 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1678 _ => {}
1679 }
1680 }
1681 out
1682}
1683
1684#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1686enum ArrayMerge {
1687 Append,
1691 Replace,
1694}
1695
1696fn array_merge_policy(key: &str) -> ArrayMerge {
1735 match key {
1736 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1737 _ => ArrayMerge::Replace,
1738 }
1739}
1740
1741impl Config {
1742 pub fn load(path: &Path) -> Result<Self> {
1745 Self::load_layers(&[path.to_path_buf()])
1746 }
1747
1748 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1758 let mut ctx = teravars::system_context();
1759 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1760 ctx.insert("env", &env);
1761 if let Some(last) = paths.last()
1762 && let Some(dir) = last.parent()
1763 {
1764 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1767 .map(|s| PathBuf::from(s.trim()))
1768 .unwrap_or_else(|_| dir.to_path_buf());
1769 ctx.insert("repo", &dir.to_string_lossy());
1770 ctx.insert(
1771 "repo_name",
1772 &dir.file_name().unwrap_or_default().to_string_lossy(),
1773 );
1774 }
1775 ctx
1776 }
1777
1778 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1786 Self::load_layers_with_machine(paths, Self::machine_layer())
1787 }
1788
1789 fn load_layers_with_machine(paths: &[PathBuf], machine: Option<PathBuf>) -> Result<Self> {
1790 let mut engine = teravars::Engine::default();
1791 let ctx = Self::render_ctx(paths);
1792 if paths.len() > 1 {
1793 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1794 if error.downcast_ref::<ConfigFailure>().is_some() {
1795 error
1796 } else {
1797 let message = error.to_string();
1800 error
1801 .context(ConfigFailure::layers("config-merge", paths))
1802 .context(message)
1803 }
1804 })?;
1805 }
1806 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1807 .map_err(|error| {
1808 let cause = ConfigFailure::render(&error, paths);
1809 anyhow::Error::new(error).context(cause)
1810 })
1811 .with_context(|| {
1812 format!(
1813 "rendering config via teravars: {}",
1814 paths
1815 .iter()
1816 .map(|p| p.display().to_string())
1817 .collect::<Vec<_>>()
1818 .join(", ")
1819 )
1820 })?;
1821 let mut table = merged.config;
1822 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1823 let standing = table
1826 .get_mut("talk")
1827 .and_then(toml::Value::as_table_mut)
1828 .and_then(|talk| talk.remove("standing_authorization"));
1829 let standing = if standing.is_some()
1830 && let Some(machine) = machine.filter(|machine| paths.contains(machine))
1831 {
1832 let machine_paths = [machine];
1833 let mut engine = teravars::Engine::default();
1834 let layer = teravars::load_merged(
1835 &machine_paths,
1836 &mut engine,
1837 &Self::render_ctx(&machine_paths),
1838 )
1839 .context("read machine standing authorization")?;
1840 layer
1841 .config
1842 .get("talk")
1843 .and_then(|talk| talk.get("standing_authorization"))
1844 .map(|value| {
1845 value.as_bool().context(
1846 "[talk] standing_authorization in the machine layer must be a boolean",
1847 )
1848 })
1849 .transpose()?
1850 .unwrap_or(false)
1851 } else {
1852 false
1853 };
1854 table.remove("vars");
1857 let detect_agents = !table.contains_key("agents");
1861 let mut cfg: Self = toml::Value::Table(table)
1862 .try_into()
1863 .context("deserializing magi config")
1864 .context(ConfigFailure::layers("config-deserialize", paths))?;
1865 cfg.talk.standing_authorization = standing;
1866 if !cfg.graph.question_routing {
1867 tracing::warn!(
1868 "[graph] question_routing is retired and ignored; task inquiries always use their chat"
1869 );
1870 }
1871 crate::persona::validate(&cfg.talk.personas)?;
1872 cfg.worktree.validate()?;
1873 cfg.release.validate()?;
1874 if let Some(name) = cfg.talk.operator_name() {
1875 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1876 bail!(
1877 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1878 );
1879 }
1880 }
1881 if detect_agents {
1882 cfg.agents = Self::autodetected().agents;
1883 }
1884 Ok(cfg)
1885 }
1886
1887 fn normalize_renamed_keys(
1895 paths: &[PathBuf],
1896 engine: &mut teravars::Engine,
1897 ctx: &teravars::Context,
1898 table: &mut toml::map::Map<String, toml::Value>,
1899 ) -> Result<()> {
1900 let both = matches!(
1901 table.get("graph"),
1902 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1903 );
1904 if !both {
1905 return Ok(());
1906 }
1907 let mut winner: Option<toml::Value> = None;
1908 for path in paths {
1909 let one = teravars::load_merged([path], engine, ctx)
1910 .map_err(|error| {
1911 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1912 anyhow::Error::new(error).context(cause)
1913 })
1914 .with_context(|| format!("rendering {}", path.display()))?;
1915 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1916 continue;
1917 };
1918 if g.contains_key("candidates") && g.contains_key("implementers") {
1919 bail!(
1920 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1921 path.display()
1922 );
1923 }
1924 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1925 winner = Some(v.clone());
1926 }
1927 }
1928 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1929 g.remove("candidates");
1930 if let Some(v) = winner {
1931 g.insert("implementers".to_owned(), v);
1932 }
1933 }
1934 Ok(())
1935 }
1936
1937 fn refuse_split_arrays(
1961 paths: &[PathBuf],
1962 engine: &mut teravars::Engine,
1963 ctx: &teravars::Context,
1964 ) -> Result<()> {
1965 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1966 for path in paths {
1967 let one = teravars::load_merged([path], engine, ctx)
1968 .map_err(|error| {
1969 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1970 anyhow::Error::new(error).context(cause)
1971 })
1972 .with_context(|| format!("rendering {}", path.display()))?;
1973 for key in array_keys(&one.config, "") {
1974 if array_merge_policy(&key) == ArrayMerge::Append {
1975 continue;
1976 }
1977 if let Some(first) = seen.get(&key) {
1978 bail!(
1979 "`{key}` is an array declared in two config layers:\n \
1980 {}\n {}\nteravars appends arrays when it merges, so \
1981 magi would run the concatenation of both - which is \
1982 not what either file says. Declare `{key}` in exactly \
1983 one of them.",
1984 first.display(),
1985 path.display()
1986 );
1987 }
1988 seen.insert(key, path.clone());
1989 }
1990 }
1991 Ok(())
1992 }
1993
1994 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
2016 let mut engine = teravars::Engine::default();
2017 let ctx = Self::render_ctx(paths);
2018 let mut out = Vec::new();
2019 for path in paths {
2020 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
2021 continue;
2022 };
2023 let mut cur = &one.config;
2024 let mut found = None;
2025 let parts: Vec<&str> = key.split('.').collect();
2026 for (i, part) in parts.iter().enumerate() {
2027 match cur.get(*part) {
2028 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
2029 found = Some(a);
2030 break;
2031 }
2032 Some(toml::Value::Table(t)) => cur = t,
2033 _ => break,
2034 }
2035 }
2036 let Some(values) = found else { continue };
2037 let strings: Vec<String> = values
2038 .iter()
2039 .filter_map(|v| v.as_str().map(str::to_owned))
2040 .collect();
2041 if !strings.is_empty() {
2042 out.push((path.clone(), strings));
2043 }
2044 }
2045 out
2046 }
2047
2048 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
2054 let mut engine = teravars::Engine::default();
2055 let ctx = Self::render_ctx(paths);
2056 paths
2057 .iter()
2058 .map(|path| {
2059 let one = teravars::load_merged([path], &mut engine, &ctx)
2060 .map(|m| m.config)
2061 .with_context(|| format!("rendering {}", path.display()));
2062 (path.clone(), one)
2063 })
2064 .collect()
2065 }
2066
2067 pub fn describe_composed(
2077 paths: &[PathBuf],
2078 commands: &[String],
2079 key: &str,
2080 empty: &str,
2081 ) -> String {
2082 if commands.is_empty() {
2083 return empty.to_owned();
2084 }
2085 let joined = commands.join(" && ");
2086 let provenance = Self::array_provenance(paths, key);
2087 if provenance.len() <= 1 {
2088 return joined;
2089 }
2090 let mut out = joined;
2091 for (path, cmds) in &provenance {
2092 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2093 }
2094 out
2095 }
2096
2097 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2104 #[cfg(test)]
2105 crate::web::request_cost::discovery();
2106 if let Some(p) = explicit {
2107 let paths = vec![p.to_path_buf()];
2108 return Ok((Self::load_layers(&paths)?, paths));
2109 }
2110 let paths = Self::layers_checked(repo)?;
2111 if paths.is_empty() {
2112 return Ok((Self::autodetected(), paths));
2113 }
2114 Ok((Self::load_layers(&paths)?, paths))
2115 }
2116
2117 pub async fn discover_fetched(
2120 repo: &Path,
2121 explicit: Option<&Path>,
2122 ) -> Result<(Self, Vec<PathBuf>)> {
2123 if explicit.is_none() && is_git_worktree(repo) {
2124 let (remote, cfg_base) = probe_remote_base(repo);
2128 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2129 .await
2130 .with_context(|| ConfigFailure {
2131 stage: "config-base",
2132 target: remote.clone(),
2133 })?;
2134 let out = crate::git::fetch(repo, &remote, &base)
2135 .await
2136 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2137 .with_context(|| ConfigFailure {
2138 stage: "config-fetch",
2139 target: format!("{remote}/{base}"),
2140 })?;
2141 if !out.ok() {
2142 return Err(anyhow::anyhow!(
2143 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2144 out.stderr.lines().next().unwrap_or("").trim()
2145 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2146 }
2147 if cfg_base.is_none() {
2148 crate::git::ensure_remote_head(repo, &remote, &base).await;
2149 }
2150 }
2151 Self::discover(repo, explicit).map_err(|error| {
2152 if error.downcast_ref::<ConfigFailure>().is_some() {
2153 error
2154 } else {
2155 error.context(ConfigFailure {
2156 stage: "config-load",
2157 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2158 })
2159 }
2160 })
2161 }
2162
2163 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2165 if !is_git_worktree(repo) {
2166 return Ok(Self::layers(repo));
2167 }
2168 let mut paths: Vec<PathBuf> = Self::machine_layer()
2169 .into_iter()
2170 .filter(|p| p.is_file())
2171 .collect();
2172 paths.extend(Self::repo_layers(repo)?);
2173 Ok(paths)
2174 }
2175
2176 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2178 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2179 if let Some(root) = cached {
2180 let relative = path.strip_prefix(root).unwrap_or(path);
2181 let reference = resolve_remote_base(repo)
2182 .map(|(remote, base)| format!("{remote}/{base}"))
2183 .unwrap_or_else(|_| "remote base".to_owned());
2184 format!(
2185 "{} at {reference} (including its includes)",
2186 repo.join(relative).display()
2187 )
2188 } else {
2189 format!("{} (including its includes)", path.display())
2190 }
2191 }
2192
2193 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2196 if !is_git_worktree(repo) {
2197 return Ok([
2198 repo.join(".magi").join("config.toml"),
2199 repo.join("magi.toml"),
2200 ]
2201 .into_iter()
2202 .filter(|p| p.is_file())
2203 .collect());
2204 }
2205 remote_layers(repo)
2206 }
2207
2208 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2228
2229 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2234 let mut paths = Vec::new();
2235 paths.extend(Self::machine_layer());
2236 paths.push(repo.join(".magi").join("config.toml"));
2237 paths.push(repo.join("magi.toml"));
2238 paths.retain(|p| p.is_file());
2239 paths
2240 }
2241
2242 #[cfg(test)]
2249 pub(crate) fn machine_layer() -> Option<PathBuf> {
2250 std::env::var(Self::CONFIG_DIR_ENV)
2251 .ok()
2252 .filter(|dir| !dir.trim().is_empty())
2253 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2254 }
2255
2256 #[cfg(not(test))]
2258 pub(crate) fn machine_layer() -> Option<PathBuf> {
2259 match std::env::var(Self::CONFIG_DIR_ENV) {
2260 Ok(dir) if dir.trim().is_empty() => None,
2262 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2263 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2264 }
2265 }
2266
2267 pub fn autodetected() -> Self {
2269 let mut cfg = Self::default();
2270 for (kind, id, model) in [
2271 (AgentKind::Claude, "opus", Some("opus")),
2272 (AgentKind::Claude, "sonnet", Some("sonnet")),
2273 (AgentKind::Antigravity, "antigravity", None),
2274 (AgentKind::Opencode, "opencode", None),
2275 (AgentKind::Codex, "codex", None),
2276 (AgentKind::Omp, "omp", None),
2277 ] {
2278 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2279 cfg.agents.push(AgentSpec {
2280 id: id.to_owned(),
2281 kind,
2282 model: model.map(str::to_owned),
2283 command: Vec::new(),
2284 extra_args: Vec::new(),
2285 env: BTreeMap::new(),
2286 prompt_delivery: None,
2287 max_turn_secs: None,
2288 });
2289 }
2290 }
2291 cfg
2292 }
2293
2294 pub fn cache_dir(&self) -> Option<PathBuf> {
2297 self.verify.cache_dir()
2298 }
2299
2300 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2302 self.agents
2303 .iter()
2304 .find(|a| a.id == id)
2305 .with_context(|| format!("no agent with id `{id}` in the roster"))
2306 }
2307
2308 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2315 let mut out = Vec::with_capacity(count);
2316 for i in 0..count {
2317 let spec = if ids.is_empty() {
2318 self.agents[(i + offset) % self.agents.len()].clone()
2319 } else {
2320 self.agent(&ids[i % ids.len()])?.clone()
2321 };
2322 out.push(spec);
2323 }
2324 Ok(out)
2325 }
2326
2327 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2334 if ids.is_empty() {
2335 Ok(self.agents.clone())
2336 } else {
2337 ids.iter().map(|id| self.agent(id).cloned()).collect()
2338 }
2339 }
2340
2341 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2348 if self.agents.is_empty() {
2349 bail!(
2350 "agent roster is empty: no agent CLI found on PATH and no \
2351 [[agents]] in the config. Run `magi init` to write a starter \
2352 magi.toml."
2353 );
2354 }
2355 let pinned = self
2356 .graph
2357 .selected_implementer
2358 .as_ref()
2359 .map(|id| self.agent(id).cloned())
2360 .transpose()?;
2361 Ok(ResolvedRoles {
2362 implementers: match &pinned {
2363 Some(agent) => vec![agent.clone()],
2364 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2365 },
2366 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2367 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2368 fixer: match self.roles.fixer.as_ref() {
2369 Some(choice) => Some(crate::agent::pick_chain(
2372 &self.agents,
2373 Some(choice),
2374 &|_| true,
2375 "fixer",
2376 )?),
2377 None => None,
2378 },
2379 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2384 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2385 Some(ids) if !ids.is_empty() => ids
2388 .iter()
2389 .find_map(|id| self.agent(id).ok())
2390 .cloned()
2391 .with_context(|| {
2392 format!("[roles] conductor names no agent in the roster: {ids:?}")
2393 })?,
2394 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2399 .unwrap_or_else(|_| self.agents[0].clone()),
2400 },
2401 implementer_roster: match pinned {
2402 Some(agent) => vec![agent],
2403 None => self.full_roster(&self.roles.implementers)?,
2404 },
2405 judge_roster: self.full_roster(&self.roles.judges)?,
2406 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2407 })
2408 }
2409
2410 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2432 if self.agents.is_empty() {
2433 bail!(
2434 "agent roster is empty: no agent CLI found on PATH and no \
2435 [[agents]] in the config. Run `magi init` to write a starter \
2436 magi.toml."
2437 );
2438 }
2439 if !self.roles.advisors.is_empty() {
2440 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2441 }
2442 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2443 }
2444
2445 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2449 if self.roles.advisors.is_empty() {
2450 self.full_roster(&self.roles.judges)
2451 } else {
2452 self.full_roster(&self.roles.advisors)
2453 }
2454 }
2455
2456 pub fn shell(&self) -> Vec<String> {
2458 if let Some(s) = &self.verify.shell {
2459 return s.clone();
2460 }
2461 if which("sh") {
2462 vec!["sh".to_owned(), "-c".to_owned()]
2463 } else {
2464 vec!["cmd".to_owned(), "/C".to_owned()]
2465 }
2466 }
2467
2468 pub fn starter_toml() -> String {
2470 let detected = Self::autodetected();
2471 let mut s = String::from(
2472 "# magi — blind multi-agent implementation competition.\n\
2473 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2474 # -> blind judging -> deliberation -> private final vote\n\
2475 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2476 #\n\
2477 # Rendered by teravars: a `[vars]` table, env\n\
2478 # and system lookups, and `include = [...]` all work. Tera\n\
2479 # braces are live everywhere in this file, but comments are\n\
2480 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2481 # may quote `{{ ... }}` freely.\n\
2482 #\n\
2483 # Layers deep-merge in increasing\n\
2484 # precedence, so the roster can live once per machine in\n\
2485 # <config_dir>/magi/config.toml and each repo only states its own\n\
2486 # gate:\n\
2487 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2488 [vars]\n\
2489 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2490 # Single quotes inside the braces: teravars renders the raw file\n\
2491 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2492 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2493 );
2494 if detected.agents.is_empty() {
2495 s.push_str(
2496 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2497 # kind = claude | opencode | antigravity | codex | command\n\
2498 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2499 );
2500 } else {
2501 for a in &detected.agents {
2502 s.push_str("[[agents]]\n");
2503 s.push_str(&format!("id = {:?}\n", a.id));
2504 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2505 if let Some(m) = &a.model {
2506 s.push_str(&format!("model = {m:?}\n"));
2507 }
2508 s.push('\n');
2509 }
2510 }
2511 s.push_str(
2512 "# Leave a role list empty to rotate through the roster.\n\
2513 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2514 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2515 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2516 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2517 [roles]\n\
2518 implementers = []\n\
2519 judges = []\n\
2520 reviewers = []\n\
2521 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2522 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2523 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2524 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2525 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2526 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2527 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2528 [graph]\n\
2529 # Gate GitHub prose; secret redaction is always enabled.\n\
2530 github_text_guard = true\n\
2531 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2532 github_language = \"en\"\n\
2533 implementers = 3\n\
2534 judges = 3\n\
2535 deliberate_rounds = 1\n\
2536 reviewers = 3\n\
2537 review_rounds = 6\n\
2538 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2539 gate_fix_rounds = 1\n\
2540 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2541 rerun_flaky_checks = true\n\
2542 # Rerun a failed verify.e2e once on the same commit before deciding; a pass is recorded as a flake and filed once as a task.\n\
2543 rerun_failed_e2e = true\n\
2544 # Port the strengths judges named in the losing candidates onto the\n\
2545 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2546 graft_runner_up = true\n\
2547 max_parallel = 4\n\
2548 language = \"en\"\n\
2549 # One CLI conversation per seat: judges keep their own argument\n\
2550 # across deliberation, the fixer keeps its implementation context.\n\
2551 sessions = true\n\
2552 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2553 # the final gate inherit this value for compatibility.\n\
2554 timeout_review = 1200\n\
2555 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2556 # verification independent if timeout_review changes later.\n\
2557 # timeout_verify = 1200\n\
2558 # Longest a seat waits for the shared build cache before it is\n\
2559 # spawned. Never counted against an agent's own timeout; expiry\n\
2560 # holds the run (resumable) instead of failing the agent.\n\
2561 # timeout_resource_wait = 1800\n\n\
2562 # What the chat calls you (persona address and the Chat's turn label).\n\
2563 # [talk]\n\
2564 # standing_authorization = false # machine layer only; bounded chat recovery\n\
2565 # operator_name = \"Commander\"\n\n\
2566 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2567 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2568 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2569 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2570 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2571 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2572 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2573 # [[talk.personas]]\n\
2574 # id = \"gendo\"\n\
2575 # name = \"Gendo Ikari\"\n\
2576 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2577 # icon = \"~/pictures/gendo.png\"\n\n\
2578 [verify]\n\
2579 # Run once per review round in the winner's worktree; failures are\n\
2580 # fed back to the fixer.\n\
2581 e2e = []\n\
2582 # Final gate. Every command must exit 0 before a merge.\n\
2583 gate = []\n\
2584 # Mechanical fixers (formatters) run in the winner's worktree before\n\
2585 # e2e and before the gate; whatever they change becomes one commit. A\n\
2586 # failing command only warns - the gate stays the arbiter. Same timeout\n\
2587 # as the gate (timeout_verify). Keep it light and idempotent.\n\
2588 # pre_gate = []\n\n\
2589 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2590 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2591 # before any agent or verify command touches it. `copy` reads from the\n\
2592 # primary checkout and never overwrites; `optional` skips a missing\n\
2593 # source. `run` goes through the shell with the worktree as cwd and\n\
2594 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2595 # the verify timeout). Setup must not edit tracked files, and what it\n\
2596 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2597 # layer only.\n\
2598 # [worktree]\n\
2599 # setup = [\n\
2600 # { copy = \".env.example -> .env\" },\n\
2601 # { copy = \".env.local\", optional = true },\n\
2602 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2603 # ]\n\
2604 # pre_clean = [] # Repeatable cleanup before owned clean -fdx.\n\n\
2605 [merge]\n\
2606 # none | local | pr\n\
2607 mode = \"none\"\n\
2608 # expected (default) | none. Set none only in repository config without CI.\n\
2609 # Ignores all check statuses; reviews and approval still apply.\n\
2610 # ci = \"expected\"\n\
2611 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2612 [update]\n\
2613 # off | notify | install — checked in the background, throttled.\n\
2614 mode = \"notify\"\n\
2615 # interval = \"24h\"\n\n\
2616 # Opt-in: magi web updates and restarts only after runs/chats finish.\n\
2617 # auto_restart = false\n\
2618 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2619 # Standalone magi serve cannot restart. Busy work waits indefinitely.\n\
2620 # Failed tags are skipped until process restart or a different tag.\n\
2621 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2622 [daemon]\n\
2623 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2624 # no new commit and no check changing state before `magi serve`\n\
2625 # notices and asks you. A failed check is rerun once on its own;\n\
2626 # still red after that escalates at once. 0 turns the watcher off.\n\
2627 # release_stall_minutes = 60\n\n\
2628 [release]\n\
2629 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2630 # Actions never run (private, no minutes): the release pull request\n\
2631 # does not wait for CI, you approve the merge in magi, and then\n\
2632 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2633 # runs `commands` from a clean checkout of the merge commit. A\n\
2634 # failure holds the release with a notice; it is never retried blind.\n\
2635 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2636 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2637 # mode = \"actions\"\n\
2638 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2639 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2640 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2641 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2642 # timeout_minutes = 30\n\
2643 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2644 # The first entry is the version of record and must be the file the\n\
2645 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2646 # rewritten to the same version. Paths are relative to the repository\n\
2647 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2648 # is not touched.\n\
2649 # version_files = [\n\
2650 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2651 # { path = \"package.json\", kind = \"json\" },\n\
2652 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2653 # ]\n",
2654 );
2655 s
2656 }
2657}
2658
2659pub fn which(program: &str) -> bool {
2661 find_program(program).is_some()
2662}
2663
2664pub fn find_program(program: &str) -> Option<PathBuf> {
2673 find_program_on(program, &std::env::var_os("PATH")?)
2674}
2675
2676pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2679 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2680 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2681}
2682
2683fn find_program_in(
2684 program: &str,
2685 paths: &std::ffi::OsStr,
2686 pathext: Option<&str>,
2687) -> Option<PathBuf> {
2688 let p = Path::new(program);
2689 if p.components().count() > 1 {
2690 return p.is_file().then(|| p.to_path_buf());
2691 }
2692 std::env::split_paths(paths).find_map(|dir| match pathext {
2693 Some(exts) => {
2694 let bare = dir.join(program);
2695 if p.extension().is_some() && bare.is_file() {
2696 return Some(bare);
2697 }
2698 exts.split(';')
2699 .filter(|e| !e.is_empty())
2700 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2701 .find(|c| c.is_file())
2702 }
2703 None => Some(dir.join(program)).filter(|c| c.is_file()),
2704 })
2705}
2706
2707const REPO_MARKER: &str = ".magi-repo";
2709
2710fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2711 use crate::proc::Quiet as _;
2712 #[cfg(test)]
2713 crate::web::request_cost::git();
2714 let out = std::process::Command::new("git")
2715 .args(args)
2716 .quiet()
2717 .current_dir(repo)
2718 .stdin(std::process::Stdio::null())
2719 .output()
2720 .ok()?;
2721 out.status
2722 .success()
2723 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2724}
2725
2726fn is_git_worktree(repo: &Path) -> bool {
2729 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2730}
2731
2732#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2735pub enum OwnerHold {
2736 LandApproval,
2738 HoldContestedMerge,
2740}
2741
2742impl OwnerHold {
2743 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2745
2746 pub fn key(self) -> &'static str {
2748 match self {
2749 Self::LandApproval => "land_approval",
2750 Self::HoldContestedMerge => "hold_contested_merge",
2751 }
2752 }
2753
2754 pub fn base_value(self, graph: &Graph) -> bool {
2756 match self {
2757 Self::LandApproval => graph.land_approval,
2758 Self::HoldContestedMerge => graph.hold_contested_merge,
2759 }
2760 }
2761}
2762
2763pub async fn branch_owner_holds(
2766 repo: &Path,
2767 head: &str,
2768) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2769 let mut holds = Vec::new();
2770 let mut diagnostics = Vec::new();
2771 if let Err(error) =
2774 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2775 {
2776 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2777 return (holds, diagnostics);
2778 }
2779 for file in ["magi.toml", ".magi/config.toml"] {
2780 let object = format!("{head}:{file}");
2781 let text = match crate::git::git(repo, &["show", &object]).await {
2782 Ok(text) => text,
2783 Err(error) => {
2784 let error = format!("{error:#}");
2786 if !error.contains("does not exist in")
2787 && !error.contains("exists on disk, but not in")
2788 {
2789 diagnostics.push(format!(
2790 "cannot read reviewed branch {file} at {head}: {error}"
2791 ));
2792 }
2793 continue;
2794 }
2795 };
2796 let value = match toml::from_str::<toml::Value>(&text) {
2797 Ok(value) => value,
2798 Err(error) => {
2799 diagnostics.push(format!(
2800 "cannot parse reviewed branch {file} at {head}: {error}"
2801 ));
2802 continue;
2803 }
2804 };
2805 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2806 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2807 }
2808 for hold in OwnerHold::ALL {
2809 if value
2810 .get("graph")
2811 .and_then(|g| g.get(hold.key()))
2812 .and_then(toml::Value::as_bool)
2813 == Some(true)
2814 {
2815 holds.push((hold, file.to_owned()));
2816 }
2817 }
2818 }
2819 (holds, diagnostics)
2820}
2821
2822#[derive(Deserialize, Default)]
2823struct ProbeMerge {
2824 base: Option<String>,
2825 remote: Option<String>,
2826}
2827
2828#[derive(Deserialize, Default)]
2829struct Probe {
2830 merge: Option<ProbeMerge>,
2831}
2832
2833fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2839 if !path.is_file() {
2840 return None;
2841 }
2842 let paths = [path.to_path_buf()];
2843 let mut engine = teravars::Engine::default();
2844 let mut ctx = Config::render_ctx(&paths);
2845 ctx.insert("repo", &repo.to_string_lossy());
2848 ctx.insert(
2849 "repo_name",
2850 &repo.file_name().unwrap_or_default().to_string_lossy(),
2851 );
2852 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2853 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2854 {
2855 return probe.merge;
2856 }
2857 let text = std::fs::read_to_string(path).ok()?;
2858 toml::from_str::<Probe>(&text).ok()?.merge
2859}
2860
2861fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2863 let mut remote = None;
2864 let mut base = None;
2865 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2866 sources.push(repo.join("magi.toml"));
2867 sources.push(repo.join(".magi").join("config.toml"));
2868 for path in sources {
2869 if let Some(m) = probe_merge(&path, repo) {
2870 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2871 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2872 }
2873 }
2874 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2875}
2876
2877fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2879 let (remote, base) = probe_remote_base(repo);
2880 let base = match base {
2881 Some(b) => b,
2882 None => {
2883 let head = format!("refs/remotes/{remote}/HEAD");
2884 git_out(repo, &["symbolic-ref", "--quiet", &head])
2885 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2886 .with_context(|| {
2887 format!(
2888 "cannot tell which branch of `{remote}` holds magi.toml: \
2889 set [merge] base, or run `git remote set-head {remote} -a`"
2890 )
2891 })?
2892 }
2893 };
2894 Ok((remote, base))
2895}
2896
2897fn fnv_hex(text: &str) -> String {
2898 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2899 for b in text.bytes() {
2900 hash ^= u64::from(b);
2901 hash = hash.wrapping_mul(0x0100_0000_01b3);
2902 }
2903 format!("{hash:016x}")
2904}
2905
2906fn declares_include(text: &str) -> bool {
2912 match toml::from_str::<toml::Table>(text) {
2913 Ok(table) => {
2914 table.contains_key("include")
2915 || table
2916 .get("teravars")
2917 .and_then(toml::Value::as_table)
2918 .is_some_and(|t| t.contains_key("include"))
2919 }
2920 Err(_) => text.contains("include"),
2921 }
2922}
2923
2924fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2927 use crate::proc::Quiet as _;
2928 #[cfg(test)]
2929 crate::web::request_cost::git();
2930 let mut archive = std::process::Command::new("git")
2931 .args(["archive", "--format=tar", sha])
2932 .quiet()
2933 .current_dir(repo)
2934 .stdin(std::process::Stdio::null())
2935 .stdout(std::process::Stdio::piped())
2936 .stderr(std::process::Stdio::null())
2937 .spawn()
2938 .context("running git archive")?;
2939 let tar = std::process::Command::new("tar")
2940 .arg("-x")
2941 .arg("-C")
2942 .arg(dest)
2943 .quiet()
2944 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2945 .output()
2946 .context("running tar")?;
2947 let status = archive.wait().context("waiting for git archive")?;
2948 if !status.success() || !tar.status.success() {
2949 bail!(
2950 "cannot unpack {sha} for the config's includes: {}",
2951 String::from_utf8_lossy(&tar.stderr).trim()
2952 );
2953 }
2954 Ok(())
2955}
2956
2957fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2960 let (remote, base) = resolve_remote_base(repo)?;
2961 let tracking = format!("refs/remotes/{remote}/{base}");
2962 let spec = format!("{tracking}^{{commit}}");
2963 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2964 .map(|s| s.trim().to_owned())
2965 .filter(|s| !s.is_empty())
2966 .with_context(|| {
2967 format!(
2968 "`{remote}/{base}` does not exist in this checkout; fetch it \
2969 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2970 a possibly stale local magi.toml instead"
2971 )
2972 })?;
2973 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2974 let rels = [".magi/config.toml", "magi.toml"];
2975 let mut texts: Vec<(&str, String)> = Vec::new();
2976 for rel in rels {
2977 let object = format!("{sha}:{rel}");
2978 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2979 continue;
2980 }
2981 let Some(text) = git_out(repo, &["show", &object]) else {
2982 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2983 };
2984 texts.push((rel, text));
2985 }
2986 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2987 let build = |root: &Path| -> Result<PathBuf> {
2991 let final_dir = root.join(&key);
2992 if !final_dir.is_dir() {
2993 std::fs::create_dir_all(root)?;
2994 let tmp = root.join(format!(
2995 "{key}.tmp-{}-{}",
2996 std::process::id(),
2997 std::time::SystemTime::now()
2998 .duration_since(std::time::UNIX_EPOCH)
2999 .map(|d| d.as_nanos())
3000 .unwrap_or_default()
3001 ));
3002 let filled = (|| -> Result<()> {
3003 std::fs::create_dir_all(&tmp)?;
3004 if wants_tree {
3005 extract_tree(repo, &sha, &tmp)?;
3006 }
3007 for (rel, text) in &texts {
3008 let file = tmp.join(rel);
3009 let parent = file.parent().unwrap_or(&tmp);
3010 std::fs::create_dir_all(parent)?;
3011 std::fs::write(&file, text)?;
3012 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
3013 }
3014 Ok(())
3015 })();
3016 if let Err(e) = filled {
3017 let _ = std::fs::remove_dir_all(&tmp);
3018 return Err(e);
3019 }
3020 if std::fs::rename(&tmp, &final_dir).is_err() {
3021 let _ = std::fs::remove_dir_all(&tmp);
3023 if !final_dir.is_dir() {
3024 bail!("cannot place {}", final_dir.display());
3025 }
3026 }
3027 }
3028 Ok(final_dir)
3029 };
3030 let common = git_out(
3031 repo,
3032 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
3033 )
3034 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
3035 let dir = match common.map(|c| build(&c)) {
3036 Some(Ok(d)) => d,
3037 _ => build(&std::env::temp_dir().join("magi-config"))
3038 .with_context(|| format!("extracting config from {remote}/{base}"))?,
3039 };
3040 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
3041}
3042
3043#[cfg(test)]
3044mod tests {
3045 #[test]
3046 fn standing_authorization_is_only_from_the_named_machine_layer() {
3047 let dir = tempfile::tempdir().unwrap();
3048 let machine = dir.path().join("machine.toml");
3049 let repo = dir.path().join("magi.toml");
3050 std::fs::write(&machine, "[talk]\nstanding_authorization = false\n").unwrap();
3051 std::fs::write(&repo, "[talk]\nstanding_authorization = true\n").unwrap();
3052 let layers = [machine.clone(), repo.clone()];
3053 let load = |paths| Config::load_layers_with_machine(paths, Some(machine.clone())).unwrap();
3054 assert!(!load(&layers).talk.standing_authorization);
3055 assert!(
3056 !load(std::slice::from_ref(&repo))
3057 .talk
3058 .standing_authorization
3059 );
3060 std::fs::write(&machine, "[talk]\nstanding_authorization = true\n").unwrap();
3061 std::fs::write(&repo, "[talk]\nstanding_authorization = false\n").unwrap();
3062 assert!(load(&layers).talk.standing_authorization);
3063 }
3064
3065 #[test]
3066 fn run_records_with_the_retired_editing_network_key_still_load() {
3067 for value in ["enabled", "restricted"] {
3069 let mut graph = serde_json::to_value(Graph::default()).unwrap();
3070 graph["editing_network"] = serde_json::json!(value);
3071 let back: Graph = serde_json::from_value(graph).unwrap();
3072 assert!(
3073 serde_json::to_value(&back)
3074 .unwrap()
3075 .get("editing_network")
3076 .is_none()
3077 );
3078 let from_toml: Graph = toml::from_str(&format!("editing_network = {value:?}")).unwrap();
3079 assert!(
3080 !toml::to_string(&from_toml)
3081 .unwrap()
3082 .contains("editing_network")
3083 );
3084 }
3085 }
3086
3087 #[test]
3088 fn coordination_defaults_off_and_validates_rendered_layer_values() {
3089 let dir = tempfile::tempdir().unwrap();
3090 let machine = dir.path().join("machine.toml");
3091 let repo = dir.path().join("repo.toml");
3092 std::fs::write(&machine, "").unwrap();
3093 assert!(Config::default().coordination.is_none());
3094 assert!(Config::load(&machine).unwrap().coordination.is_none());
3095 std::fs::write(
3096 &machine,
3097 r#"
3098[vars]
3099contract = "updater.contract"
3100[coordination]
3101contract_file = "{{ vars.contract }}"
3102contract_token = "protocol-v1"
3103lock_file = "updater.lock"
3104"#,
3105 )
3106 .unwrap();
3107 let cfg = Config::load(&machine).unwrap();
3108 let policy = cfg.coordination.unwrap();
3109 assert_eq!(policy.contract_file, "updater.contract");
3110 assert_eq!(policy.contract_token, "protocol-v1");
3111 assert_eq!(policy.lock_file, "updater.lock");
3112 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
3113 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
3114 let policy = cfg.coordination.unwrap();
3115 assert_eq!(policy.contract_file, "updater.contract");
3116 assert_eq!(policy.lock_file, "repository.lock");
3117 std::fs::write(
3118 &repo,
3119 r#"
3120[vars]
3121bad = "../escape"
3122[coordination]
3123lock_file = "{{ vars.bad }}"
3124"#,
3125 )
3126 .unwrap();
3127 let error = Config::load_layers(&[machine, repo]).unwrap_err();
3128 assert!(format!("{error:#}").contains("coordination.lock_file"));
3129 }
3130
3131 #[test]
3132 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
3133 let dir = tempfile::tempdir().unwrap();
3134 let path = dir.path().join("config.toml");
3135 let valid = toml::toml! {
3136 [coordination]
3137 contract_file = "updater.contract"
3138 contract_token = "protocol-v1"
3139 lock_file = "updater.lock"
3140 };
3141 for key in ["contract_file", "lock_file"] {
3142 for bad in [
3143 "",
3144 " ",
3145 " file",
3146 "file ",
3147 "\tfile",
3148 "file\t",
3149 ".",
3150 "..",
3151 "file..name",
3152 "../escape",
3153 "a/b",
3154 "a\\b",
3155 "/absolute",
3156 "C:drive",
3157 "C:\\absolute",
3158 "nul\0name",
3159 ] {
3160 let mut table = valid.clone();
3161 table["coordination"][key] = bad.into();
3162 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3163 let error = Config::load(&path).unwrap_err();
3164 assert!(
3165 format!("{error:#}").contains(&format!("coordination.{key}")),
3166 "{bad:?}: {error:#}"
3167 );
3168 }
3169 }
3170 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
3171 let mut table = valid.clone();
3172 table["coordination"]["contract_token"] = bad.into();
3173 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3174 let error = Config::load(&path).unwrap_err();
3175 assert!(
3176 format!("{error:#}").contains("coordination.contract_token"),
3177 "{error:#}"
3178 );
3179 }
3180 for key in ["contract_file", "contract_token", "lock_file"] {
3181 let mut table = valid.clone();
3182 table["coordination"].as_table_mut().unwrap().remove(key);
3183 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3184 let error = Config::load(&path).unwrap_err();
3185 assert!(
3186 format!("{error:#}").contains(&format!("coordination.{key}")),
3187 "{error:#}"
3188 );
3189 }
3190 let mut table = valid;
3191 table["coordination"]
3192 .as_table_mut()
3193 .unwrap()
3194 .insert("typo".into(), "value".into());
3195 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3196 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
3197 }
3198
3199 #[test]
3200 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
3201 let mut cfg = Config::default();
3202 assert_eq!(
3203 cfg.context_window("claude-sonnet-4-5-20250929"),
3204 Some(200_000)
3205 );
3206 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
3207 assert_eq!(cfg.context_window("mystery-model"), None);
3208 cfg.context_windows
3209 .insert("claude-sonnet-4-5".into(), 1_000_000);
3210 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
3211 cfg.context_windows.insert("mystery".into(), 32_768);
3212 assert_eq!(
3214 cfg.context_window("claude-sonnet-4-5-20250929"),
3215 Some(1_000_000)
3216 );
3217 cfg.context_windows
3219 .insert("claude-sonnet-4-5-20250929".into(), 7);
3220 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
3221 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
3222 }
3223
3224 use super::*;
3225
3226 #[test]
3229 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
3230 let dir = tempfile::tempdir().unwrap();
3231 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
3232 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
3233 let paths = dir.path().as_os_str();
3234 assert_eq!(
3235 find_program_in("codex", paths, Some(".EXE;.CMD")),
3236 Some(dir.path().join("codex.cmd"))
3237 );
3238 assert_eq!(
3239 find_program_in("codex", paths, None),
3240 Some(dir.path().join("codex"))
3241 );
3242 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3243 }
3244
3245 fn spec(id: &str) -> AgentSpec {
3246 AgentSpec {
3247 id: id.to_owned(),
3248 kind: AgentKind::Command,
3249 model: None,
3250 command: vec!["true".to_owned()],
3251 extra_args: Vec::new(),
3252 env: BTreeMap::new(),
3253 prompt_delivery: None,
3254 max_turn_secs: None,
3255 }
3256 }
3257
3258 #[test]
3259 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
3260 let default: Merge = toml::from_str("").unwrap();
3261 assert_eq!(default.ci, MergeCi::Expected);
3262 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
3263 assert_eq!(
3264 config.merge.ci.expectation(),
3265 crate::land::CiExpectation::Absent
3266 );
3267 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
3268 assert!(Config::starter_toml().contains("# ci = \"expected\""));
3269 }
3270
3271 #[test]
3272 fn github_text_guard_defaults_on_and_can_be_disabled() {
3273 let default: Graph = toml::from_str("").unwrap();
3274 assert!(default.github_text_guard);
3275 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3276 assert!(!disabled.github_text_guard);
3277 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3278 assert!(!config.graph.github_text_guard);
3279 assert!(Config::starter_toml().contains("github_text_guard = true"));
3280 }
3281
3282 #[test]
3283 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3284 assert!(Graph::default().rerun_flaky_checks);
3285 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3286 assert!(!off.rerun_flaky_checks);
3287 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3288 }
3289
3290 #[test]
3291 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3292 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3297 assert_eq!(g.timeout_verify, None);
3298 assert_eq!(g.verify_timeout(), 3600);
3299 }
3300
3301 #[test]
3302 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3303 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3308 assert_eq!(g.timeout_review, 45);
3309 assert_eq!(
3310 g.verify_timeout(),
3311 45,
3312 "an omitted legacy value follows review"
3313 );
3314 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3315 .expect("parse explicit override");
3316 assert_eq!(explicit.verify_timeout(), 1200);
3317 }
3318
3319 #[test]
3320 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3321 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3322 assert_eq!(g.implementers, 4);
3323 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3324 assert_eq!(g.implementers, 5);
3325 }
3326
3327 fn layered(lower: &str, upper: &str) -> Result<Config> {
3328 let dir = tempfile::tempdir().unwrap();
3329 let a = dir.path().join("a.toml");
3330 let b = dir.path().join("b.toml");
3331 std::fs::write(&a, lower).unwrap();
3332 std::fs::write(&b, upper).unwrap();
3333 Config::load_layers(&[a, b])
3334 }
3335
3336 #[test]
3337 fn graph_implementers_higher_layer_wins_across_spellings() {
3338 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3339 assert_eq!(c.graph.implementers, 5);
3340 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3341 assert_eq!(c.graph.implementers, 5);
3342 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3343 assert_eq!(c.graph.implementers, 2);
3344 }
3345
3346 #[test]
3347 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3348 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3349 .unwrap_err()
3350 .to_string();
3351 assert!(
3352 err.contains("candidates") && err.contains("implementers"),
3353 "{err}"
3354 );
3355 assert!(err.contains("b.toml"), "{err}");
3356 }
3357
3358 #[test]
3359 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3360 let g: Graph =
3364 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3365 .expect("an old-shaped [graph] table must still parse");
3366 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3367 assert!(
3368 !g.e2e_every_round,
3369 "off by default, same as before this field existed"
3370 );
3371 }
3372
3373 #[test]
3374 fn empty_roles_rotate_judges_off_their_own_candidate() {
3375 let cfg = Config {
3378 agents: vec![spec("a"), spec("b"), spec("c")],
3379 graph: Graph {
3380 implementers: 3,
3381 ..Graph::default()
3382 },
3383 ..Config::default()
3384 };
3385 let roles = cfg.resolve_roles().unwrap();
3386 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3387 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3388 assert_eq!(impls, ["a", "b", "c"]);
3389 assert_eq!(judges, ["b", "c", "a"]);
3390 for (i, j) in judges.iter().enumerate() {
3391 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3392 }
3393 }
3394
3395 #[test]
3396 fn single_agent_roster_fills_every_seat() {
3397 let cfg = Config {
3398 agents: vec![spec("solo")],
3399 graph: Graph {
3400 implementers: 3,
3401 ..Graph::default()
3402 },
3403 ..Config::default()
3404 };
3405 let roles = cfg.resolve_roles().unwrap();
3406 assert_eq!(roles.implementers.len(), 3);
3407 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3408 }
3409
3410 #[test]
3411 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3412 let cfg = Config {
3417 agents: vec![spec("a"), spec("b"), spec("c")],
3418 graph: Graph {
3419 implementers: 1,
3420 ..Graph::default()
3421 },
3422 ..Config::default()
3423 };
3424 let roles = cfg.resolve_roles().unwrap();
3425 assert_eq!(roles.implementers.len(), 1);
3426 let roster: Vec<&str> = roles
3427 .implementer_roster
3428 .iter()
3429 .map(|a| a.id.as_str())
3430 .collect();
3431 assert_eq!(roster, ["a", "b", "c"]);
3432 }
3433
3434 #[test]
3435 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3436 let cfg = Config {
3437 agents: vec![spec("a"), spec("b"), spec("c")],
3438 roles: Roles {
3439 implementers: vec!["c".to_owned(), "a".to_owned()],
3440 ..Roles::default()
3441 },
3442 graph: Graph {
3443 implementers: 1,
3444 ..Graph::default()
3445 },
3446 ..Config::default()
3447 };
3448 let roles = cfg.resolve_roles().unwrap();
3449 assert_eq!(roles.implementers.len(), 1);
3451 assert_eq!(roles.implementers[0].id, "c");
3452 let roster: Vec<&str> = roles
3453 .implementer_roster
3454 .iter()
3455 .map(|a| a.id.as_str())
3456 .collect();
3457 assert_eq!(roster, ["c", "a"]);
3458 }
3459
3460 #[test]
3461 fn explicit_roles_win() {
3462 let cfg = Config {
3463 agents: vec![spec("a"), spec("b")],
3464 roles: Roles {
3465 implementers: vec!["b".to_owned()],
3466 judges: vec!["a".to_owned()],
3467 reviewers: Vec::new(),
3468 fixer: Some("a".into()),
3469 ..Roles::default()
3470 },
3471 ..Config::default()
3472 };
3473 let roles = cfg.resolve_roles().unwrap();
3474 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3475 assert!(roles.judges.iter().all(|a| a.id == "a"));
3476 let fixer = roles.fixer.unwrap();
3477 assert_eq!(fixer.len(), 1);
3478 assert_eq!(fixer[0].id, "a");
3479 assert_eq!(roles.conductor.id, "a");
3480 }
3481
3482 #[test]
3483 fn fixer_takes_a_string_or_an_ordered_chain() {
3484 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3485 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3486 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3487 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3488
3489 let resolve = |fixer: Option<AgentChoice>| {
3490 Config {
3491 agents: vec![spec("a"), spec("b"), spec("c")],
3492 roles: Roles {
3493 fixer,
3494 ..Roles::default()
3495 },
3496 ..Config::default()
3497 }
3498 .resolve_roles()
3499 };
3500 let ids = |r: &ResolvedRoles| -> Vec<String> {
3501 r.fixer
3502 .as_ref()
3503 .unwrap()
3504 .iter()
3505 .map(|s| s.id.clone())
3506 .collect()
3507 };
3508 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3510 assert!(resolve(None).unwrap().fixer.is_none());
3511 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3513 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3514 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3516 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3517 }
3518
3519 #[test]
3520 fn unknown_agent_id_is_an_error() {
3521 let cfg = Config {
3522 agents: vec![spec("a")],
3523 roles: Roles {
3524 judges: vec!["nope".to_owned()],
3525 ..Roles::default()
3526 },
3527 ..Config::default()
3528 };
3529 assert!(cfg.resolve_roles().is_err());
3530 }
3531
3532 #[test]
3533 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3534 let mut cfg = Config {
3535 agents: vec![spec("a"), spec("b")],
3536 ..Config::default()
3537 };
3538 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3539
3540 cfg.roles.conductor = Some("b".into());
3541 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3542
3543 cfg.roles.conductor = Some("missing".into());
3544 assert!(cfg.resolve_roles().is_err());
3545 }
3546
3547 #[test]
3548 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3549 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3550 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3551 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3552
3553 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3554 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3555 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3556
3557 for roles in [one, chain] {
3558 let text = toml::to_string(&roles).unwrap();
3559 let back: Roles = toml::from_str(&text).unwrap();
3560 assert_eq!(back.synthesizer, roles.synthesizer);
3561 assert_eq!(back.chatter, roles.chatter);
3562 }
3563 let text = toml::to_string(&Roles {
3564 conductor: Some("x".into()),
3565 ..Roles::default()
3566 })
3567 .unwrap();
3568 assert!(
3569 text.contains("conductor = \"x\""),
3570 "string stays a string: {text}"
3571 );
3572 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3573 }
3574
3575 #[test]
3576 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3577 for (text, ids) in [
3578 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3579 (
3580 r#"dupes_judge = ["first", "second"]"#,
3581 vec!["first", "second"],
3582 ),
3583 ("dupes_judge = []", vec![]),
3584 ] {
3585 let roles: Roles = toml::from_str(text).unwrap();
3586 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3587 let serialized = toml::to_string(&roles).unwrap();
3588 let back: Roles = toml::from_str(&serialized).unwrap();
3589 assert_eq!(back.dupes_judge, roles.dupes_judge);
3590 assert!(serialized.contains(text));
3591 }
3592 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3593 assert!(Roles::default().dupes_judge.is_none());
3594 assert!(Config::starter_toml().contains("# dupes_judge ="));
3595
3596 let mut cfg = Config {
3598 agents: vec![spec("a")],
3599 ..Config::default()
3600 };
3601 cfg.roles.dupes_judge = Some("missing".into());
3602 assert!(cfg.resolve_roles().is_ok());
3603 }
3604
3605 #[test]
3606 fn an_empty_choice_counts_as_unset() {
3607 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3608 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3609 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3610 }
3611
3612 #[test]
3613 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3614 let mut cfg = Config {
3620 agents: vec![spec("a"), spec("b")],
3621 ..Config::default()
3622 };
3623 let want = primary(cfg.roles.synthesizer.as_ref());
3624 assert_eq!(
3625 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3626 .unwrap()
3627 .id,
3628 "a",
3629 "unset falls back to agent::pick's own default order"
3630 );
3631
3632 cfg.roles.synthesizer = Some("b".into());
3633 let want = primary(cfg.roles.synthesizer.as_ref());
3634 assert_eq!(
3635 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3636 .unwrap()
3637 .id,
3638 "b",
3639 "the named agent wins over the default order"
3640 );
3641 }
3642
3643 #[test]
3644 fn empty_roster_is_an_error() {
3645 assert!(Config::default().resolve_roles().is_err());
3646 }
3647
3648 #[test]
3649 fn advise_defaults_to_on_with_three_proposals() {
3650 let g = Graph::default();
3651 assert!(g.advise);
3652 assert!(g.graft_runner_up, "graft is on by default");
3653 assert_eq!(g.advisors, 3);
3654 }
3655
3656 #[test]
3657 fn unset_advisors_falls_back_to_the_judge_roster() {
3658 let cfg = Config {
3659 agents: vec![spec("a"), spec("b")],
3660 roles: Roles {
3661 judges: vec!["b".to_owned()],
3662 ..Roles::default()
3663 },
3664 graph: Graph {
3665 advisors: 2,
3666 ..Graph::default()
3667 },
3668 ..Config::default()
3669 };
3670 let advisors = cfg.advisors().expect("advisors resolve");
3671 assert_eq!(advisors.len(), 2);
3672 assert!(
3673 advisors.iter().all(|a| a.id == "b"),
3674 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3675 );
3676 }
3677
3678 #[test]
3679 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3680 let cfg = Config {
3681 agents: vec![spec("a"), spec("b")],
3682 roles: Roles {
3683 judges: vec!["b".to_owned()],
3684 advisors: vec!["a".to_owned()],
3685 ..Roles::default()
3686 },
3687 graph: Graph {
3688 advisors: 2,
3689 ..Graph::default()
3690 },
3691 ..Config::default()
3692 };
3693 let advisors = cfg.advisors().expect("advisors resolve");
3694 assert!(advisors.iter().all(|a| a.id == "a"));
3695 }
3696
3697 #[test]
3703 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3704 let cfg = Config {
3705 agents: vec![spec("a"), spec("b"), spec("c")],
3706 graph: Graph {
3707 advisors: 3,
3708 judges: 3,
3709 ..Graph::default()
3710 },
3711 ..Config::default()
3712 };
3713 let advisors = cfg.advisors().expect("advisors resolve");
3714 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3715 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3716 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3717 assert_eq!(
3718 advisor_ids, judge_ids,
3719 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3720 );
3721 }
3722
3723 #[test]
3724 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3725 let cfg = Config {
3726 agents: vec![spec("a")],
3727 roles: Roles {
3728 advisors: vec!["nope".to_owned()],
3729 ..Roles::default()
3730 },
3731 graph: Graph {
3732 advisors: 1,
3733 ..Graph::default()
3734 },
3735 ..Config::default()
3736 };
3737 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3738 assert!(format!("{err:#}").contains("nope"));
3739 }
3740
3741 #[test]
3742 fn repos_default_to_no_roots_and_a_day_of_trust() {
3743 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3744 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3745 assert_eq!(Config::default().repos.fetch_interval, 600);
3746 assert!(!Config::default().repos.auto_clone);
3747 assert!(Config::default().repos.clone_command.is_none());
3748 }
3749
3750 #[test]
3751 fn a_config_file_with_no_repos_table_still_loads() {
3752 let dir = tempfile::tempdir().unwrap();
3753 let path = dir.path().join("magi.toml");
3754 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3755 let cfg = Config::load(&path).expect("must load without [repos]");
3756 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3757 assert_eq!(cfg.repos.scan_ttl, 86_400);
3758 }
3759
3760 #[test]
3775 fn a_test_build_does_not_read_the_operators_machine_config() {
3776 let repo = tempfile::tempdir().unwrap();
3777 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3778
3779 let layers = Config::layers(repo.path());
3780 assert_eq!(
3781 layers,
3782 vec![repo.path().join("magi.toml")],
3783 "only the fixture's own file may be a layer"
3784 );
3785 if let Some(real) = dirs::config_dir() {
3786 let machine = real.join("magi").join("config.toml");
3787 assert!(
3788 !layers.contains(&machine),
3789 "the operator's {} must not be a layer in a test build",
3790 machine.display()
3791 );
3792 }
3793 }
3794
3795 #[test]
3796 fn auto_upgrade_config_defaults_and_opt_in() {
3797 let default: Update = toml::from_str("").unwrap();
3798 assert!(!default.auto_restart);
3799 assert_eq!(default.mode, UpdateMode::Notify);
3800 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
3801 assert!(enabled.auto_restart);
3802 assert_eq!(enabled.interval.as_deref(), Some("2h"));
3803 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
3804 }
3805
3806 #[test]
3807 fn starter_toml_loads_through_teravars() {
3808 let dir = tempfile::tempdir().unwrap();
3809 let path = dir.path().join("magi.toml");
3810 std::fs::write(&path, Config::starter_toml()).unwrap();
3811 let parsed = Config::load(&path).expect("starter config must load");
3812 assert_eq!(parsed.graph.implementers, 3);
3813 assert_eq!(parsed.merge.mode, MergeMode::None);
3814 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3815 assert!(parsed.graph.sessions);
3816 assert!(parsed.graph.github_text_guard);
3817 assert_eq!(parsed.graph.timeout_review, 1200);
3818 assert_eq!(parsed.graph.verify_timeout(), 1200);
3819 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3820 }
3821
3822 #[test]
3823 fn release_defaults_to_actions_and_the_starter_documents_it() {
3824 let dir = tempfile::tempdir().unwrap();
3825 let path = dir.path().join("magi.toml");
3826 std::fs::write(&path, Config::starter_toml()).unwrap();
3827 let r = Config::load(&path).unwrap().release;
3828 assert_eq!(r.mode, ReleaseMode::Actions);
3829 assert!(!r.is_local());
3830 assert!(r.commands.is_empty());
3831 assert_eq!(r.timeout_minutes, 30);
3832 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3833 }
3834
3835 #[test]
3836 fn release_local_parses_and_unknown_keys_are_refused() {
3837 let dir = tempfile::tempdir().unwrap();
3838 let path = dir.path().join("magi.toml");
3839 std::fs::write(
3840 &path,
3841 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3842 )
3843 .unwrap();
3844 let r = Config::load(&path).unwrap().release;
3845 assert!(r.is_local());
3846 assert_eq!(r.commands.len(), 2);
3847 assert_eq!(r.timeout_minutes, 5);
3848 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3849 assert!(Config::load(&path).is_err());
3850 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3851 assert!(Config::load(&path).is_err());
3852 }
3853
3854 #[test]
3855 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3856 let dir = tempfile::tempdir().unwrap();
3857 let path = dir.path().join("magi.toml");
3858 std::fs::write(&path, Config::starter_toml()).unwrap();
3859 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3860 assert!(Config::starter_toml().contains("# pre_gate = []"));
3861 }
3862
3863 #[test]
3864 fn release_version_files_parse_default_empty_and_are_validated() {
3865 let dir = tempfile::tempdir().unwrap();
3866 let path = dir.path().join("magi.toml");
3867 std::fs::write(&path, "").unwrap();
3868 assert!(
3869 Config::load(&path)
3870 .unwrap()
3871 .release
3872 .version_files
3873 .is_empty()
3874 );
3875 std::fs::write(
3876 &path,
3877 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
3878 )
3879 .unwrap();
3880 let files = Config::load(&path).unwrap().release.version_files;
3881 assert_eq!(files.len(), 2);
3882 assert_eq!(files[1].kind, VersionKind::Json);
3883 for bad in [
3884 "{ path = \"package.json\", kind = \"json\" }",
3885 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
3886 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
3887 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
3888 ] {
3889 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
3890 assert!(Config::load(&path).is_err(), "{bad}");
3891 }
3892 assert!(Config::starter_toml().contains("# version_files = ["));
3893 }
3894
3895 #[test]
3896 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3897 let starter = Config::starter_toml();
3898 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3899 assert!(starter.contains("verification independent if timeout_review changes later"));
3900 assert!(starter.contains("# timeout_verify = 1200"));
3901 }
3902
3903 #[test]
3904 fn starter_toml_documents_chat_personas() {
3905 let starter = Config::starter_toml();
3906 assert!(starter.contains("# [[talk.personas]]"));
3907 assert!(starter.contains("tone only"));
3908 }
3909
3910 #[test]
3911 fn talk_personas_parse_and_are_validated() {
3912 let dir = tempfile::tempdir().unwrap();
3913 let path = dir.path().join("magi.toml");
3914 std::fs::write(
3915 &path,
3916 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3917 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3918 )
3919 .unwrap();
3920 let cfg = Config::load(&path).expect("loads");
3921 assert_eq!(cfg.talk.personas.len(), 2);
3922 let catalog = crate::persona::catalog(&cfg.talk.personas);
3923 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3924 assert_eq!(
3925 (rei.name.as_str(), rei.prompt.as_str()),
3926 ("Quiet", "Be brief.")
3927 );
3928 assert_eq!(catalog.last().unwrap().id, "gendo");
3929
3930 for (body, needle) in [
3931 (
3932 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3933 "empty `id`",
3934 ),
3935 (
3936 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3937 "empty `prompt`",
3938 ),
3939 (
3940 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3941 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3942 "more than once",
3943 ),
3944 (
3945 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3946 "cannot be redefined",
3947 ),
3948 ] {
3949 std::fs::write(&path, body).unwrap();
3950 let err = format!("{:#}", Config::load(&path).unwrap_err());
3951 assert!(err.contains(needle), "{needle}: {err}");
3952 }
3953 }
3954
3955 #[test]
3956 fn talk_operator_name_is_trimmed_and_validated() {
3957 let dir = tempfile::tempdir().unwrap();
3958 let path = dir.path().join("magi.toml");
3959 let load = |body: &str| {
3960 std::fs::write(&path, body).unwrap();
3961 Config::load(&path)
3962 };
3963 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3964 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3965 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3966 assert_eq!(blank.talk.operator_name(), None);
3967 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3968 let long = "x".repeat(65);
3969 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3970 }
3971
3972 #[test]
3973 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3974 let dir = tempfile::tempdir().unwrap();
3975 let load = |body: &str| {
3976 let path = dir.path().join("c.toml");
3977 std::fs::write(&path, body).unwrap();
3978 Config::load(&path)
3979 };
3980 let ok = load(
3981 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3982 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3983 )
3984 .unwrap();
3985 let c = crate::persona::catalog(&ok.talk.personas);
3986 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3987 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3988 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3989 let oversized = format!(
3990 "data:image/png;base64,{}",
3991 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3992 );
3993 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3994 for (id, fields) in [
3995 ("rei", ""),
3996 ("default", ""),
3997 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3998 ] {
3999 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
4000 let cfg = load(&body).expect("bad icon must not invalidate config");
4001 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
4002 assert_eq!(persona.id, id);
4003 assert!(crate::persona_icon::load(bad).is_err());
4004 }
4005 }
4006 let doc = Config::starter_toml();
4007 assert!(doc.contains("# icon = "));
4008 }
4009
4010 #[test]
4011 fn talk_personas_in_two_layers_are_refused() {
4012 let dir = tempfile::tempdir().unwrap();
4013 let machine = dir.path().join("machine.toml");
4014 let repo = dir.path().join("repo.toml");
4015 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
4016 std::fs::write(&machine, one).unwrap();
4017 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
4018 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
4019 assert!(err.contains("talk.personas"), "{err}");
4020 }
4021
4022 #[test]
4023 fn starter_toml_documents_role_lists_as_backup_order() {
4024 let starter = Config::starter_toml();
4025 assert!(starter.contains("also an ordered backup list"));
4026 assert!(starter.contains("codex then sonnet are spares"));
4027 }
4028
4029 #[test]
4033 fn a_repository_can_declare_a_linear_history_merge_style() {
4034 let dir = tempfile::tempdir().unwrap();
4035 let path = dir.path().join("magi.toml");
4036 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
4037 let parsed = Config::load(&path).expect("config must load");
4038 assert_eq!(parsed.merge.style, MergeStyle::Squash);
4039 }
4040
4041 #[test]
4042 fn later_layers_win_and_vars_render() {
4043 let dir = tempfile::tempdir().unwrap();
4044 let machine = dir.path().join("machine.toml");
4045 let project = dir.path().join("magi.toml");
4046 std::fs::write(
4048 &machine,
4049 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
4050 [graph]\ncandidates = 3\nmax_parallel = 8\n",
4051 )
4052 .unwrap();
4053 std::fs::write(
4056 &project,
4057 "[vars]\ncache = \"/shared\"\n\n\
4058 [graph]\ncandidates = 2\n\n\
4059 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
4060 )
4061 .unwrap();
4062
4063 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
4064 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
4065 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
4066 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
4067 assert_eq!(
4068 cfg.verify.gate,
4069 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
4070 );
4071 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
4073 }
4074
4075 #[test]
4076 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
4077 let g = Graph::default();
4081 assert_eq!(g.timeout_talk, 3600);
4082
4083 let dir = tempfile::tempdir().unwrap();
4084 let path = dir.path().join("magi.toml");
4085 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4086 let cfg = Config::load(&path).expect("must load without timeout_talk set");
4087 assert_eq!(cfg.graph.timeout_talk, 3600);
4088 }
4089
4090 #[test]
4091 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
4092 let dir = tempfile::tempdir().unwrap();
4093 let path = dir.path().join("magi.toml");
4094 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
4095 let cfg = Config::load(&path).expect("must load");
4096 assert_eq!(cfg.graph.timeout_talk, 120);
4097 }
4098
4099 #[test]
4100 fn the_disk_defaults_are_the_measurements_made_up_front() {
4101 let cfg = Config::default();
4102 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
4103 assert!(cfg.disk.auto_fold);
4104 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
4105 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
4106 }
4107
4108 #[test]
4109 fn an_unset_disk_section_is_the_safe_default() {
4110 let dir = tempfile::tempdir().unwrap();
4111 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
4112 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
4113 assert_eq!(cfg.disk, Disk::default());
4114 }
4115
4116 #[test]
4117 fn env_is_available_to_templates_with_a_default() {
4118 let dir = tempfile::tempdir().unwrap();
4119 let path = dir.path().join("magi.toml");
4120 std::fs::write(
4128 &path,
4129 "[verify]\n\
4130 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
4131 \"populated={{ env | length > 0 }}\"]\n",
4132 )
4133 .unwrap();
4134 let cfg = Config::load(&path).expect("env lookup must render");
4135 assert_eq!(cfg.verify.gate[0], "cache=fallback");
4136 assert_eq!(cfg.verify.gate[1], "populated=true");
4137 }
4138
4139 #[test]
4140 fn a_broken_template_names_the_file() {
4141 let dir = tempfile::tempdir().unwrap();
4142 let path = dir.path().join("magi.toml");
4143 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
4144 let err = Config::load(&path).expect_err("must not silently ignore");
4145 assert!(err.to_string().contains("teravars"), "{err}");
4146 }
4147
4148 #[test]
4149 fn tera_syntax_in_comments_is_inert() {
4150 let dir = tempfile::tempdir().unwrap();
4154 let path = dir.path().join("magi.toml");
4155 std::fs::write(
4156 &path,
4157 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
4158 [graph]\ncandidates = 2\n",
4159 )
4160 .unwrap();
4161 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
4162 assert_eq!(cfg.graph.implementers, 2);
4163 }
4164
4165 #[test]
4166 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
4167 use std::time::Duration;
4168
4169 let mut s: AgentSpec =
4170 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
4171 let budget = Duration::from_millis(1500);
4172 assert_eq!(s.max_turn_secs, None);
4173 assert_eq!(s.turn_timeout(budget), budget);
4174 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
4175 for (cap, expected) in [
4176 (1, Duration::from_secs(1)),
4177 (2, budget),
4178 (0, Duration::ZERO),
4179 ] {
4180 s.max_turn_secs = Some(cap);
4181 let saved = toml::to_string(&s).unwrap();
4182 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
4183 assert_eq!(loaded.max_turn_secs, Some(cap));
4184 assert_eq!(loaded.turn_timeout(budget), expected);
4185 }
4186 }
4187
4188 #[test]
4189 fn opencode_defaults_to_file_delivery() {
4190 let mut s = spec("oc");
4191 s.kind = AgentKind::Opencode;
4192 assert_eq!(s.delivery(), Delivery::File);
4193 s.prompt_delivery = Some(Delivery::Argv);
4194 assert_eq!(s.delivery(), Delivery::Argv);
4195 }
4196 #[test]
4197 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
4198 let g = Graph::default();
4203 assert!(
4204 g.land,
4205 "stopping at an open PR left the watching to a human"
4206 );
4207 assert!(
4208 g.land_approval,
4209 "on-by-default land is only defensible while this is also on"
4210 );
4211 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
4212 assert!(
4213 g.hold_contested_merge,
4214 "a contested hand-off must still reach a human when approvals are off"
4215 );
4216 }
4217 #[test]
4218 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
4219 let dir = tempfile::tempdir().unwrap();
4223 let machine = dir.path().join("machine.toml");
4224 let repo = dir.path().join("magi.toml");
4225 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
4226 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
4227
4228 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4229 .expect_err("two layers naming one array must not merge silently");
4230 assert_eq!(
4231 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4232 "config-merge"
4233 );
4234 let err = err.to_string();
4235 assert!(err.contains("roles.implementers"), "{err}");
4236 assert!(err.contains("machine.toml"), "{err}");
4239 assert!(err.contains("magi.toml"), "{err}");
4240 }
4241
4242 #[test]
4243 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
4244 let dir = tempfile::tempdir().unwrap();
4247 let machine = dir.path().join("machine.toml");
4248 let repo = dir.path().join("magi.toml");
4249 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
4250 std::fs::write(
4251 &repo,
4252 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
4253 [roles]\nimplementers = [\"oc\"]\n",
4254 )
4255 .unwrap();
4256
4257 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
4258 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
4259 assert_eq!(cfg.roles.implementers, ["oc"]);
4260 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
4261 }
4262
4263 #[test]
4264 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
4265 let dir = tempfile::tempdir().unwrap();
4268 let machine = dir.path().join("machine.toml");
4269 let repo = dir.path().join("magi.toml");
4270 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4271 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4272
4273 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4274 assert_eq!(
4275 cfg.verify.gate,
4276 [
4277 "editorconfig-checker".to_owned(),
4278 "cargo make check".to_owned()
4279 ],
4280 "low-priority (machine) command first, high-priority (repo) command after"
4281 );
4282 }
4283
4284 fn load_one(body: &str) -> Result<Config> {
4285 let dir = tempfile::tempdir().unwrap();
4286 let path = dir.path().join("magi.toml");
4287 std::fs::write(&path, body).unwrap();
4288 Config::load_layers(&[path])
4289 }
4290
4291 #[test]
4292 fn pre_clean_config_is_strict_and_single_layer() {
4293 assert!(Config::default().worktree.pre_clean.is_empty());
4294 let good = load_one("[worktree]\npre_clean = [{run = 'cleanup', timeout_secs = 60}]\n");
4295 assert_eq!(good.unwrap().worktree.pre_clean[0].timeout_secs, Some(60));
4296 for bad in [
4297 "{}",
4298 "{run = ''}",
4299 "{run = ' ', timeout_secs = 2}",
4300 "{run = 'x', timeout_secs = 0}",
4301 "{run = 'x', timeout_secs = -1}",
4302 "{copy = 'cache'}",
4303 "{run = 'x', optional = true}",
4304 "'x'",
4305 ] {
4306 assert!(
4307 load_one(&format!("[worktree]\npre_clean = [{bad}]\n")).is_err(),
4308 "{bad}"
4309 );
4310 }
4311 let dir = tempfile::tempdir().unwrap();
4312 let a = dir.path().join("a.toml");
4313 let b = dir.path().join("b.toml");
4314 for path in [&a, &b] {
4315 std::fs::write(path, "[worktree]\npre_clean = [{run = 'cleanup'}]\n").unwrap();
4316 }
4317 assert!(
4318 Config::load_layers(&[a, b])
4319 .unwrap_err()
4320 .to_string()
4321 .contains("worktree.pre_clean")
4322 );
4323 }
4324
4325 #[test]
4326 fn worktree_setup_defaults_to_empty_and_parses_steps() {
4327 assert!(Config::default().worktree.setup.is_empty());
4328 let cfg = load_one(
4329 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
4330 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
4331 )
4332 .unwrap();
4333 assert_eq!(cfg.worktree.setup.len(), 3);
4334 assert!(cfg.worktree.setup[1].optional);
4335 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
4336 }
4337
4338 #[test]
4339 fn worktree_setup_rejects_malformed_steps() {
4340 for bad in [
4341 "{ copy = \"a\", run = \"b\" }",
4342 "{ optional = true }",
4343 "{ copy = \"a -> ../b\" }",
4344 "{ copy = \"a -> /abs\" }",
4345 "{ copy = \"a -> .git/config\" }",
4346 "{ run = \"b\", optional = true }",
4347 "{ copy = \"a\", timeout_secs = 3 }",
4348 "{ run = \"b\", bogus = 1 }",
4349 ] {
4350 let body = format!("[worktree]\nsetup = [{bad}]\n");
4351 assert!(load_one(&body).is_err(), "{bad}");
4352 }
4353 }
4354
4355 #[test]
4356 fn worktree_setup_in_two_layers_is_refused() {
4357 let dir = tempfile::tempdir().unwrap();
4358 let machine = dir.path().join("machine.toml");
4359 let repo = dir.path().join("magi.toml");
4360 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4361 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4362 assert!(Config::load_layers(&[machine, repo]).is_err());
4363 }
4364
4365 #[test]
4366 fn starter_toml_documents_worktree_setup() {
4367 let starter = Config::starter_toml();
4368 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4369 let body = starter.replace("# [worktree]", "[worktree]");
4371 let mut out = String::new();
4372 let mut live = false;
4373 for line in body.lines() {
4374 if line == "[worktree]" {
4375 live = true;
4376 } else if live && !line.starts_with("# ") {
4377 live = false;
4378 }
4379 out.push_str(&if live {
4380 line.replacen("# ", "", 1)
4381 } else {
4382 line.to_owned()
4383 });
4384 out.push('\n');
4385 }
4386 let cfg = load_one(&out).expect("uncommented example loads");
4387 assert_eq!(cfg.worktree.setup.len(), 3);
4388 }
4389
4390 #[test]
4391 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4392 let dir = tempfile::tempdir().unwrap();
4393 let machine = dir.path().join("machine.toml");
4394 let repo = dir.path().join("magi.toml");
4395 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4396 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4397
4398 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4399 assert_eq!(
4400 cfg.verify.e2e,
4401 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4402 );
4403 }
4404
4405 #[test]
4406 fn two_layers_declaring_repos_roots_are_both_scanned() {
4407 let dir = tempfile::tempdir().unwrap();
4408 let machine = dir.path().join("machine.toml");
4409 let repo = dir.path().join("magi.toml");
4410 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4411 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4412
4413 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4414 assert_eq!(
4415 cfg.repos.roots,
4416 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4417 );
4418 }
4419
4420 #[test]
4421 fn duplicate_gate_commands_across_layers_both_run() {
4422 let dir = tempfile::tempdir().unwrap();
4425 let machine = dir.path().join("machine.toml");
4426 let repo = dir.path().join("magi.toml");
4427 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4428 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4429
4430 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4431 assert_eq!(
4432 cfg.verify.gate,
4433 ["same-command".to_owned(), "same-command".to_owned()]
4434 );
4435 }
4436
4437 #[test]
4438 fn notify_command_is_still_refused_across_two_layers() {
4439 let dir = tempfile::tempdir().unwrap();
4441 let machine = dir.path().join("machine.toml");
4442 let repo = dir.path().join("magi.toml");
4443 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4444 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4445
4446 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4447 .expect_err("an argv split across layers must not concatenate");
4448 assert_eq!(
4449 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4450 "config-merge"
4451 );
4452 let err = err.to_string();
4453 assert!(err.contains("notify.command"), "{err}");
4454 assert!(err.contains("machine.toml"), "{err}");
4455 assert!(err.contains("magi.toml"), "{err}");
4456 }
4457
4458 #[test]
4459 fn one_layer_declaring_verify_gate_runs_unchanged() {
4460 let dir = tempfile::tempdir().unwrap();
4463 let path = dir.path().join("magi.toml");
4464 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4465
4466 let cfg = Config::load(&path).expect("single layer must still load");
4467 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4468 }
4469
4470 #[test]
4471 fn layered_parse_failures_name_the_failing_input() {
4472 let dir = tempfile::tempdir().unwrap();
4473 let a = dir.path().join("a.toml");
4474 let b = dir.path().join("b.toml");
4475 std::fs::write(&a, "[graph").unwrap();
4476 std::fs::write(&b, "[verify").unwrap();
4477 let paths = [a.clone(), b.clone()];
4478 let first = Config::load_layers(&paths).unwrap_err();
4479 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4480 assert_eq!(first_cause.stage, "config-parse");
4481 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4482 std::fs::write(&a, "").unwrap();
4483 let second = Config::load_layers(&paths).unwrap_err();
4484 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4485 assert_eq!(second_cause.stage, "config-parse");
4486 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4487 assert_ne!(first_cause.target, second_cause.target);
4488 }
4489
4490 #[test]
4491 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4492 let dir = tempfile::tempdir().unwrap();
4493 let machine = dir.path().join("machine.toml");
4494 let repo = dir.path().join("magi.toml");
4495 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4496 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4497 let paths = vec![machine.clone(), repo.clone()];
4498
4499 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4500 let described =
4501 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4502 assert!(described.contains("editorconfig-checker && cargo make check"));
4503 assert!(
4504 described.contains(&machine.display().to_string()),
4505 "{described}"
4506 );
4507 assert!(
4508 described.contains(&repo.display().to_string()),
4509 "{described}"
4510 );
4511
4512 let single = vec![repo.clone()];
4514 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4515 let solo_described =
4516 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4517 assert_eq!(solo_described, "cargo make check");
4518 }
4519
4520 mod remote_layers {
4521 use super::*;
4522
4523 fn git(dir: &Path, args: &[&str]) {
4524 use crate::proc::Quiet as _;
4525 let out = std::process::Command::new("git")
4526 .args(args)
4527 .quiet()
4528 .current_dir(dir)
4529 .output()
4530 .unwrap();
4531 assert!(out.status.success(), "git {args:?}: {out:?}");
4532 }
4533
4534 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4537 let tmp = tempfile::tempdir().unwrap();
4538 let bare = tmp.path().join("o.git");
4539 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4540 let repo = tmp.path().join("repo");
4541 std::fs::create_dir_all(&repo).unwrap();
4542 git(&repo, &["init", "-b", "trunk"]);
4543 git(&repo, &["config", "user.name", "t"]);
4544 git(&repo, &["config", "user.email", "t@example.com"]);
4545 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4546 git(&repo, &["add", "-A"]);
4547 git(&repo, &["commit", "-m", "x"]);
4548 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4549 git(&repo, &["push", "origin", "trunk"]);
4550 git(&repo, &["fetch", "origin"]);
4551 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4552 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4553 (tmp, repo)
4554 }
4555
4556 #[tokio::test]
4557 async fn branch_owner_holds_only_add_literal_true_values() {
4558 for (text, expected) in [
4559 ("[graph]\nland_approval = true\n", true),
4560 ("[graph]\nland_approval = false\n", false),
4561 ("[graph]\nland = true\n", false),
4562 ("[graph\n", false),
4563 ("[graph]\nland_approval = \"yes\"\n", false),
4564 ("[graph]\nland_approval = 1\n", false),
4565 ] {
4566 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4567 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4568 let (holds, _) = branch_owner_holds(&repo, &head).await;
4569 assert_eq!(
4570 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4571 expected
4572 );
4573 assert!(
4574 !holds
4575 .iter()
4576 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4577 );
4578 for base in [false, true] {
4579 let mut cfg = Config::default();
4580 cfg.graph.land_approval = base;
4581 let mut state = crate::run::RunState::new(
4582 repo.clone(),
4583 "trunk".into(),
4584 head.clone(),
4585 "review".into(),
4586 cfg,
4587 );
4588 state.observe_branch_owner_holds(&head).await;
4589 assert!(
4590 state.branch_owner_holds.is_empty(),
4591 "competition candidates are excluded"
4592 );
4593 state.reviewed_commits = Some(Vec::new());
4594 state.observe_branch_owner_holds(&head).await;
4595 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4596 }
4597 }
4598 }
4599
4600 #[tokio::test]
4601 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4602 let (_tmp, repo) = fixture(
4603 "[graph]\nland_approval = true\n",
4604 "[graph]\nland_approval = true\n",
4605 );
4606 git(&repo, &["rm", "magi.toml"]);
4607 std::fs::create_dir(repo.join(".magi")).unwrap();
4608 std::fs::write(
4609 repo.join(".magi/config.toml"),
4610 "[graph]\nhold_contested_merge = true\n",
4611 )
4612 .unwrap();
4613 git(&repo, &["add", "."]);
4614 git(&repo, &["commit", "-m", "nested hold"]);
4615 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4616 let (holds, _) = branch_owner_holds(&repo, &head).await;
4617 assert_eq!(
4618 holds,
4619 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4620 );
4621 let (holds, diagnostics) =
4622 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4623 assert!(holds.is_empty());
4624 assert!(!diagnostics.is_empty());
4625 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4626 assert!(holds.is_empty());
4627 assert!(!diagnostics.is_empty());
4628 for base in [false, true] {
4629 let mut cfg = Config::default();
4630 cfg.graph.land_approval = base;
4631 let mut state = crate::run::RunState::new(
4632 repo.clone(),
4633 "trunk".into(),
4634 head.clone(),
4635 "review".into(),
4636 cfg,
4637 );
4638 state.reviewed_commits = Some(Vec::new());
4639 state.observe_branch_owner_holds(&head).await;
4640 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4641 state
4642 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4643 .await;
4644 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4645 }
4646 }
4647
4648 #[test]
4649 fn reads_the_remote_blob_not_the_working_tree() {
4650 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4651 let (cfg, _) = Config::discover(&repo, None).unwrap();
4652 assert_eq!(cfg.graph.implementers, 2);
4653 }
4654
4655 #[test]
4656 fn detached_head_still_reads_the_remote() {
4657 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4658 git(&repo, &["checkout", "--detach"]);
4659 let (cfg, _) = Config::discover(&repo, None).unwrap();
4660 assert_eq!(cfg.graph.implementers, 2);
4661 }
4662
4663 #[test]
4664 fn a_missing_ref_is_an_error_not_a_fallback() {
4665 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4666 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4667 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4668 assert!(err.contains("origin"), "{err}");
4669 }
4670
4671 #[test]
4672 fn merge_base_in_the_checkout_locates_the_ref() {
4673 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4674 assert!(Config::discover(&repo, None).is_err());
4675 }
4676
4677 #[test]
4678 fn the_magi_dir_layer_is_read_too() {
4679 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4680 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4681 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4682 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4683 git(&repo, &["add", "-A"]);
4684 git(&repo, &["commit", "-m", "y"]);
4685 git(&repo, &["push", "origin", "trunk"]);
4686 git(&repo, &["fetch", "origin"]);
4687 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4688 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4689 assert_eq!(layers.len(), 2);
4690 }
4691
4692 #[test]
4693 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4694 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4695 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4696 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4697 git(&repo, &["add", "-A"]);
4698 git(&repo, &["commit", "-m", "inc"]);
4699 git(&repo, &["push", "origin", "trunk"]);
4700 git(&repo, &["fetch", "origin"]);
4701 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4703 let (cfg, _) = Config::discover(&repo, None).unwrap();
4704 assert_eq!(cfg.graph.implementers, 2);
4705 }
4706
4707 #[test]
4708 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4709 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4710 let m = t.path().join("machine.toml");
4711 std::fs::write(
4712 &m,
4713 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4714 )
4715 .unwrap();
4716 let (remote, base) = {
4717 let probe = probe_merge(&m, &repo).unwrap();
4718 (probe.remote, probe.base)
4719 };
4720 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4721 }
4722
4723 #[test]
4724 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4725 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4726 let m = t.path().join("machine.toml");
4727 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4728 let probe = probe_merge(&m, &repo).unwrap();
4729 assert_eq!(probe.base.as_deref(), Some("repo"));
4730 }
4731
4732 #[test]
4733 fn every_include_form_is_recognised() {
4734 assert!(declares_include("include = [\"a.toml\"]\n"));
4735 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4736 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4737 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4738 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4739 }
4740
4741 #[test]
4742 fn an_explicit_config_is_read_as_named() {
4743 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4744 let own = t.path().join("own.toml");
4745 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4746 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4747 assert_eq!(cfg.graph.implementers, 4);
4748 }
4749
4750 #[test]
4751 fn discover_fetched_fails_when_the_fetch_does() {
4752 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4753 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4754 let rt = tokio::runtime::Builder::new_current_thread()
4755 .enable_all()
4756 .build()
4757 .unwrap();
4758 let err = rt
4759 .block_on(Config::discover_fetched(&repo, None))
4760 .unwrap_err();
4761 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4762 }
4763
4764 #[test]
4765 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4766 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4767 let remote = tmp.path().join("o.git");
4768 let offline = tmp.path().join("offline.git");
4769 std::fs::rename(&remote, &offline).unwrap();
4770 let rt = tokio::runtime::Builder::new_current_thread()
4771 .enable_all()
4772 .build()
4773 .unwrap();
4774 let fetch = rt
4775 .block_on(Config::discover_fetched(&repo, None))
4776 .unwrap_err();
4777 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4778 assert_eq!(fetch_cause.stage, "config-fetch");
4779 assert_eq!(fetch_cause.target, "origin/trunk");
4780
4781 std::fs::rename(&offline, &remote).unwrap();
4782 let parse = rt
4783 .block_on(Config::discover_fetched(&repo, None))
4784 .unwrap_err();
4785 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4786 assert_eq!(parse_cause.stage, "config-parse");
4787 assert!(parse_cause.target.contains("magi.toml"));
4788 assert!(
4789 !parse_cause.target.contains("/magi/config/"),
4790 "cache commit paths are incidental"
4791 );
4792 assert_ne!(fetch_cause.stage, parse_cause.stage);
4793 }
4794
4795 #[test]
4796 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4797 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4800 git(&repo, &["remote", "set-head", "origin", "-d"]);
4801 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4802 git(
4803 &repo,
4804 &["config", "remote.origin.followRemoteHEAD", "never"],
4805 );
4806 let rt = tokio::runtime::Builder::new_current_thread()
4807 .enable_all()
4808 .build()
4809 .unwrap();
4810 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4811 assert_eq!(cfg.graph.implementers, 2);
4812 }
4813
4814 #[test]
4815 fn a_non_git_directory_reads_its_files() {
4816 let dir = tempfile::tempdir().unwrap();
4817 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4818 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4819 assert_eq!(cfg.graph.implementers, 4);
4820 }
4821 }
4822
4823 #[test]
4824 fn github_language_defaults_to_english_and_accepts_japanese() {
4825 let default: Graph = toml::from_str("").unwrap();
4826 assert_eq!(default.github_language, "en");
4827 assert!(default.github_english() && default.language_gate());
4828 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4829 assert!(!ja.github_english() && !ja.language_gate());
4830 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4832 assert!(only_ops.language_gate());
4833 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4834 assert!(!off.language_gate() && off.github_english());
4835 assert!(Config::starter_toml().contains("github_language = \"en\""));
4836 }
4837}