1use std::collections::BTreeMap;
47use std::path::{Path, PathBuf};
48
49use anyhow::{Context as _, Result, bail};
50use serde::{Deserialize, Serialize};
51
52#[derive(Debug, thiserror::Error)]
55#[error("{stage}: {target}")]
56pub(crate) struct ConfigFailure {
57 pub(crate) stage: &'static str,
58 pub(crate) target: String,
59}
60
61impl ConfigFailure {
62 fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
63 let stage = match error {
64 teravars::Error::Io(_) => "config-read",
65 teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
66 teravars::Error::Render(_) => "config-template",
67 teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
68 "config-include"
69 }
70 _ => "config-render",
71 };
72 Self::layers(stage, paths)
73 }
74
75 fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
76 let targets: Vec<_> = paths
77 .iter()
78 .map(|path| {
79 path.ancestors()
82 .find(|p| p.join(REPO_MARKER).is_file())
83 .and_then(|root| path.strip_prefix(root).ok())
84 .unwrap_or(path)
85 .to_string_lossy()
86 .into_owned()
87 })
88 .collect();
89 Self {
90 stage,
91 target: serde_json::to_string(&targets).expect("config paths"),
92 }
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
98#[serde(rename_all = "lowercase")]
99pub enum AgentKind {
100 Claude,
102 Opencode,
104 Antigravity,
108 Codex,
112 Omp,
118 Command,
120}
121
122impl AgentKind {
123 pub fn program(self) -> Option<&'static str> {
125 match self {
126 Self::Claude => Some("claude"),
127 Self::Opencode => Some("opencode"),
128 Self::Antigravity => Some("agy"),
129 Self::Codex => Some("codex"),
130 Self::Omp => Some("omp"),
131 Self::Command => None,
132 }
133 }
134
135 pub fn as_str(self) -> &'static str {
137 match self {
138 Self::Claude => "claude",
139 Self::Opencode => "opencode",
140 Self::Antigravity => "antigravity",
141 Self::Codex => "codex",
142 Self::Omp => "omp",
143 Self::Command => "command",
144 }
145 }
146
147 pub const ALL: [Self; 6] = [
155 Self::Claude,
156 Self::Opencode,
157 Self::Antigravity,
158 Self::Codex,
159 Self::Omp,
160 Self::Command,
161 ];
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
166#[serde(rename_all = "lowercase")]
167pub enum Delivery {
168 Stdin,
170 Argv,
172 File,
174}
175
176#[derive(Debug, Clone, Deserialize, Serialize)]
178#[serde(deny_unknown_fields)]
179pub struct AgentSpec {
180 pub id: String,
182 pub kind: AgentKind,
184 #[serde(default)]
186 pub model: Option<String>,
187 #[serde(default)]
190 pub command: Vec<String>,
191 #[serde(default)]
193 pub extra_args: Vec<String>,
194 #[serde(default)]
196 pub env: BTreeMap<String, String>,
197 #[serde(default)]
199 pub prompt_delivery: Option<Delivery>,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub max_turn_secs: Option<u64>,
204}
205
206impl AgentSpec {
207 pub fn turn_timeout(&self, budget: std::time::Duration) -> std::time::Duration {
209 self.max_turn_secs.map_or(budget, |secs| {
210 budget.min(std::time::Duration::from_secs(secs))
211 })
212 }
213
214 pub fn delivery(&self) -> Delivery {
220 self.prompt_delivery.unwrap_or(match self.kind {
221 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
222 AgentKind::Codex => Delivery::Stdin,
226 AgentKind::Omp => Delivery::Stdin,
230 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
231 })
232 }
233
234 pub fn display(&self) -> String {
236 match &self.model {
237 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
238 None => format!("{} ({})", self.id, self.kind.as_str()),
239 }
240 }
241}
242
243#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
250#[serde(untagged)]
251pub enum AgentChoice {
252 One(String),
254 Chain(Vec<String>),
256}
257
258impl AgentChoice {
259 pub fn ids(&self) -> Vec<&str> {
261 let all: Vec<&str> = match self {
262 Self::One(id) => vec![id.as_str()],
263 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
264 };
265 all.into_iter()
266 .map(str::trim)
267 .filter(|id| !id.is_empty())
268 .collect()
269 }
270
271 pub fn primary(&self) -> Option<&str> {
273 self.ids().into_iter().next()
274 }
275}
276
277impl From<&str> for AgentChoice {
278 fn from(id: &str) -> Self {
279 Self::One(id.to_owned())
280 }
281}
282
283pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
285 choice.and_then(AgentChoice::primary)
286}
287
288#[derive(Debug, Clone, Default, Deserialize, Serialize)]
291#[serde(deny_unknown_fields, default)]
292pub struct Roles {
293 pub implementers: Vec<String>,
295 pub judges: Vec<String>,
297 pub reviewers: Vec<String>,
299 pub fixer: Option<AgentChoice>,
308 pub chatter: Option<AgentChoice>,
322 pub dupes_judge: Option<AgentChoice>,
326 pub conductor: Option<AgentChoice>,
339 pub advisors: Vec<String>,
350 pub synthesizer: Option<AgentChoice>,
363 pub language_judge: Option<AgentChoice>,
372}
373
374#[derive(Debug, Clone, Deserialize, Serialize)]
376#[serde(deny_unknown_fields, default)]
377pub struct Graph {
378 #[serde(rename = "editing_network", skip_serializing)]
382 pub retired_editing_network: Option<serde::de::IgnoredAny>,
383 pub github_text_guard: bool,
385 pub github_language: String,
391 #[serde(alias = "candidates")]
423 pub implementers: usize,
424 #[serde(default)]
426 pub selected_implementer: Option<String>,
427 pub judges: usize,
429 pub deliberate_rounds: usize,
431 pub reviewers: usize,
439 pub review_rounds: usize,
441 pub gate_fix_rounds: usize,
447 pub max_parallel: usize,
449 pub language: String,
451 pub sessions: bool,
459 pub timeout_implement: u64,
461 pub timeout_judge: u64,
463 pub timeout_review: u64,
465 pub timeout_verify: Option<u64>,
474 pub timeout_fix: u64,
476 pub timeout_talk: u64,
484 pub timeout_resource_wait: u64,
493 pub retries: usize,
495 pub worktree_root: Option<PathBuf>,
497 pub land: bool,
510 pub land_rounds: usize,
512 pub rerun_flaky_checks: bool,
520 pub land_approval: bool,
531 pub hold_contested_merge: bool,
542 pub question_routing: bool,
545 pub file_followups: bool,
552 pub release_deputy_followups: bool,
560 pub answer_timeout: u64,
564 pub incomplete_review: IncompleteReviewPolicy,
567 pub e2e_every_round: bool,
585 pub rerun_failed_e2e: bool,
597 pub advise: bool,
611 pub advisors: usize,
616 pub graft_runner_up: bool,
625}
626
627impl Default for Graph {
628 fn default() -> Self {
629 Self {
630 github_text_guard: true,
631 github_language: "en".into(),
632 implementers: 1,
633 selected_implementer: None,
634 retired_editing_network: None,
635 judges: 3,
636 deliberate_rounds: 1,
637 reviewers: 3,
638 review_rounds: 6,
639 gate_fix_rounds: 1,
640 max_parallel: 4,
641 language: "en".to_owned(),
642 sessions: true,
643 timeout_implement: 3600,
644 timeout_judge: 1200,
645 timeout_review: 1200,
646 timeout_verify: None,
647 timeout_fix: 1800,
648 timeout_talk: 3600,
649 timeout_resource_wait: 1800,
650 retries: 1,
651 worktree_root: None,
652 land: true,
653 land_rounds: 4,
654 rerun_flaky_checks: true,
655 land_approval: true,
656 hold_contested_merge: true,
657 question_routing: true,
658 file_followups: true,
659 release_deputy_followups: true,
660 answer_timeout: 86_400,
661 incomplete_review: IncompleteReviewPolicy::Block,
662 e2e_every_round: false,
663 rerun_failed_e2e: true,
664 advise: true,
665 advisors: 3,
666 graft_runner_up: true,
667 }
668 }
669}
670
671impl Graph {
672 pub fn verify_timeout(&self) -> u64 {
676 self.timeout_verify.unwrap_or(self.timeout_review)
677 }
678
679 pub fn language_gate(&self) -> bool {
682 self.github_text_guard && self.github_english()
683 }
684
685 pub fn github_english(&self) -> bool {
687 crate::lang::is_english(&self.github_language)
688 }
689}
690
691#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
698#[serde(rename_all = "lowercase")]
699pub enum IncompleteReviewPolicy {
700 Block,
704 Warn,
709}
710
711#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
713#[serde(rename_all = "lowercase")]
714pub enum LeakPolicy {
715 Warn,
717 Redact,
719 Fail,
721}
722
723#[derive(Debug, Clone, Deserialize, Serialize)]
730#[serde(deny_unknown_fields, default)]
731pub struct Blind {
732 pub commit_msg_hook: bool,
735 pub strip_lines: Vec<String>,
739 pub vendor_tokens: Vec<String>,
741 pub on_leak: LeakPolicy,
743 pub seed: Option<u64>,
746}
747
748impl Default for Blind {
749 fn default() -> Self {
750 Self {
751 commit_msg_hook: true,
752 strip_lines: [
753 "Co-Authored-By:",
754 "Signed-off-by:",
755 "Assisted-by:",
756 "Generated-by:",
757 "Generated with",
758 "\u{1f916}",
759 ]
760 .iter()
761 .map(|s| (*s).to_owned())
762 .collect(),
763 vendor_tokens: [
764 "claude",
765 "anthropic",
766 "codex",
767 "openai",
768 "chatgpt",
769 "gemini",
770 "grok",
771 "xai",
772 "copilot",
773 "opencode",
774 "qoder",
775 "cursor",
776 "\u{1f916}",
777 ]
778 .iter()
779 .map(|s| (*s).to_owned())
780 .collect(),
781 on_leak: LeakPolicy::Warn,
782 seed: None,
783 }
784 }
785}
786
787#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, clap::ValueEnum)]
789#[serde(rename_all = "snake_case")]
790pub enum BuildCache {
791 #[default]
793 Shared,
794 Isolated,
796}
797
798impl std::fmt::Display for BuildCache {
799 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
800 f.write_str(match self {
801 Self::Shared => "shared",
802 Self::Isolated => "isolated",
803 })
804 }
805}
806
807#[derive(Debug, Clone, Default, Deserialize, Serialize)]
809#[serde(deny_unknown_fields, default)]
810pub struct Verify {
811 pub build_cache: BuildCache,
813 pub e2e: Vec<String>,
816 pub gate: Vec<String>,
818 #[serde(default)]
829 pub pre_gate: Vec<String>,
830 pub shell: Option<Vec<String>>,
833}
834
835impl Verify {
836 pub fn cache_dir(&self) -> Option<PathBuf> {
842 self.e2e
843 .iter()
844 .chain(self.gate.iter())
845 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
846 }
847
848 pub fn cargo_targets(&self) -> Vec<crate::cache::Target> {
851 use crate::cache::Target;
852 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
853 let mut targets: Vec<_> = crate::cache::extract_manifest_paths(&all)
854 .into_iter()
855 .map(Target::Manifest)
856 .collect();
857 for dir in all
858 .iter()
859 .chain(&self.pre_gate)
860 .filter_map(|cmd| crate::build_target::command::directory(cmd))
861 {
862 let target = Target::Directory(dir);
863 if !targets.contains(&target) {
864 targets.push(target);
865 }
866 }
867 targets
868 }
869}
870
871#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
873#[serde(deny_unknown_fields, default)]
874pub struct Worktree {
875 pub setup: Vec<SetupStep>,
878 pub pre_clean: Vec<PreCleanStep>,
880}
881
882#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
884#[serde(deny_unknown_fields)]
885pub struct PreCleanStep {
886 pub run: String,
888 pub timeout_secs: Option<u64>,
890}
891
892#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
894#[serde(deny_unknown_fields, default)]
895pub struct SetupStep {
896 pub copy: Option<String>,
899 pub optional: bool,
901 pub run: Option<String>,
903 pub timeout_secs: Option<u64>,
906}
907
908impl Worktree {
909 pub fn validate(&self) -> Result<()> {
911 for (i, step) in self.pre_clean.iter().enumerate() {
912 if step.run.trim().is_empty() || step.timeout_secs == Some(0) {
913 bail!(
914 "[worktree] pre_clean step {} requires a nonempty run and positive timeout",
915 i + 1
916 );
917 }
918 }
919 for (i, step) in self.setup.iter().enumerate() {
920 let n = i + 1;
921 match (&step.copy, &step.run) {
922 (Some(c), None) => {
923 if step.timeout_secs.is_some() {
924 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
925 }
926 crate::worktree_setup::validate_copy(c)
927 .with_context(|| format!("[worktree] setup step {n}"))?;
928 }
929 (None, Some(r)) => {
930 if r.trim().is_empty() {
931 bail!("[worktree] setup step {n}: `run` is empty");
932 }
933 if step.optional {
934 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
935 }
936 }
937 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
938 }
939 }
940 Ok(())
941 }
942}
943
944#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
954#[serde(deny_unknown_fields, default)]
955pub struct Disk {
956 pub min_free_bytes: u64,
965 #[serde(skip_serializing_if = "Option::is_none")]
995 pub reclaim_free_bytes: Option<u64>,
996 pub auto_fold: bool,
1002 pub fold_grace_secs: u64,
1010 pub cache_limit_bytes: u64,
1022 pub worktree_limit_bytes: u64,
1024 pub worktree_reclaim_bytes: u64,
1028 pub retained_attempt_limit: usize,
1032}
1033
1034impl Disk {
1035 pub fn reclaim_threshold(&self) -> u64 {
1041 let floor = self.min_free_bytes;
1042 self.reclaim_free_bytes
1043 .map_or_else(|| floor.saturating_mul(2), |own| own.max(floor))
1044 }
1045}
1046
1047impl Default for Disk {
1048 fn default() -> Self {
1049 Self {
1050 min_free_bytes: 8 * 1024 * 1024 * 1024,
1051 reclaim_free_bytes: None,
1052 auto_fold: true,
1053 fold_grace_secs: 6 * 60 * 60,
1054 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
1055 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
1056 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
1057 retained_attempt_limit: 8,
1058 }
1059 }
1060}
1061
1062#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1064#[serde(rename_all = "lowercase")]
1065pub enum MergeMode {
1066 None,
1069 Local,
1072 Pr,
1076}
1077
1078#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
1092#[serde(rename_all = "lowercase")]
1093pub enum MergeStyle {
1094 #[default]
1099 Merge,
1100 Squash,
1106 Rebase,
1112}
1113
1114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1116#[serde(rename_all = "lowercase")]
1117pub enum MergeCi {
1118 #[default]
1120 Expected,
1121 None,
1123}
1124
1125impl MergeCi {
1126 pub fn expectation(self) -> crate::land::CiExpectation {
1128 match self {
1129 Self::Expected => crate::land::CiExpectation::Expected,
1130 Self::None => crate::land::CiExpectation::Absent,
1131 }
1132 }
1133}
1134
1135#[derive(Debug, Clone, Deserialize, Serialize)]
1137#[serde(deny_unknown_fields, default)]
1138pub struct Merge {
1139 pub mode: MergeMode,
1142 pub ci: MergeCi,
1144 pub base: Option<String>,
1146 pub style: MergeStyle,
1149 pub remote: String,
1151 pub release_bump: bool,
1164}
1165
1166impl Default for Merge {
1167 fn default() -> Self {
1168 Self {
1169 mode: MergeMode::None,
1170 ci: MergeCi::Expected,
1171 base: None,
1172 style: MergeStyle::default(),
1173 remote: "origin".to_owned(),
1174 release_bump: true,
1175 }
1176 }
1177}
1178
1179#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1181#[serde(rename_all = "lowercase")]
1182pub enum UpdateMode {
1183 Off,
1185 Notify,
1188 Install,
1190}
1191
1192#[derive(Debug, Clone, Deserialize, Serialize)]
1194#[serde(deny_unknown_fields, default)]
1195pub struct Update {
1196 pub mode: UpdateMode,
1198 pub interval: Option<String>,
1200 pub auto_restart: bool,
1202}
1203
1204impl Default for Update {
1205 fn default() -> Self {
1206 Self {
1207 mode: UpdateMode::Notify,
1208 interval: None,
1209 auto_restart: false,
1210 }
1211 }
1212}
1213
1214#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1216#[serde(rename_all = "lowercase")]
1217pub enum ReleaseMode {
1218 #[default]
1221 Actions,
1222 Local,
1227}
1228
1229#[derive(Debug, Clone, Deserialize, Serialize)]
1231#[serde(deny_unknown_fields, default)]
1232pub struct Release {
1233 pub mode: ReleaseMode,
1236 pub commands: Vec<String>,
1243 pub timeout_minutes: u64,
1245 pub version_files: Vec<VersionFile>,
1253}
1254
1255#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1257#[serde(rename_all = "lowercase")]
1258pub enum VersionKind {
1259 Cargo,
1261 Json,
1263}
1264
1265#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1267#[serde(deny_unknown_fields)]
1268pub struct VersionFile {
1269 pub path: String,
1271 pub kind: VersionKind,
1273}
1274
1275impl Default for Release {
1276 fn default() -> Self {
1277 Self {
1278 mode: ReleaseMode::Actions,
1279 commands: Vec::new(),
1280 timeout_minutes: 30,
1281 version_files: Vec::new(),
1282 }
1283 }
1284}
1285
1286impl Release {
1287 pub fn validate(&self) -> Result<()> {
1289 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1290 }
1291
1292 pub fn is_local(&self) -> bool {
1294 self.mode == ReleaseMode::Local
1295 }
1296}
1297
1298#[derive(Debug, Clone, Deserialize, Serialize)]
1300#[serde(try_from = "CoordinationFields")]
1301pub struct Coordination {
1302 pub contract_file: String,
1304 pub contract_token: String,
1306 pub lock_file: String,
1308}
1309
1310#[derive(Deserialize, Default)]
1311#[serde(deny_unknown_fields, default)]
1312struct CoordinationFields {
1313 contract_file: String,
1314 contract_token: String,
1315 lock_file: String,
1316}
1317
1318impl TryFrom<CoordinationFields> for Coordination {
1319 type Error = anyhow::Error;
1320
1321 fn try_from(fields: CoordinationFields) -> Result<Self> {
1322 for (key, name) in [
1323 ("coordination.contract_file", &fields.contract_file),
1324 ("coordination.lock_file", &fields.lock_file),
1325 ] {
1326 if name.trim().is_empty()
1327 || name != name.trim()
1328 || name == "."
1329 || name.contains("..")
1330 || name.contains(['/', '\\', ':', '\0'])
1331 {
1332 bail!(
1333 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1334 );
1335 }
1336 }
1337 let token = &fields.contract_token;
1338 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1339 bail!(
1340 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1341 );
1342 }
1343 Ok(Self {
1344 contract_file: fields.contract_file,
1345 contract_token: fields.contract_token,
1346 lock_file: fields.lock_file,
1347 })
1348 }
1349}
1350
1351#[cfg(test)]
1352pub(crate) fn test_coordination() -> Option<Coordination> {
1353 Some(Coordination {
1354 contract_file: "updater.contract".into(),
1355 contract_token: "test-protocol-v1".into(),
1356 lock_file: "updater.lock".into(),
1357 })
1358}
1359
1360#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1362#[serde(deny_unknown_fields, default)]
1363pub struct Config {
1364 pub coordination: Option<Coordination>,
1366 pub agents: Vec<AgentSpec>,
1368 pub roles: Roles,
1370 pub graph: Graph,
1372 pub blind: Blind,
1374 pub verify: Verify,
1376 pub worktree: Worktree,
1378 pub disk: Disk,
1380 pub merge: Merge,
1382 pub update: Update,
1384 pub prompts: Prompts,
1386 pub notify: Notify,
1388 pub repos: Repos,
1391 pub talk: Talk,
1393 pub daemon: Daemon,
1395 pub release: Release,
1397 pub context_windows: BTreeMap<String, u64>,
1400}
1401
1402const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1412 ("claude-opus-4", 200_000),
1413 ("claude-sonnet-4", 200_000),
1414 ("claude-haiku-4", 200_000),
1415 ("claude-3", 200_000),
1416 ("opus", 200_000),
1417 ("sonnet", 200_000),
1418 ("haiku", 200_000),
1419 ("gpt-5", 400_000),
1420 ("gpt-4.1", 1_000_000),
1421 ("gpt-4o", 128_000),
1422 ("o3", 200_000),
1423 ("o4-mini", 200_000),
1424 ("gemini-2.5", 1_000_000),
1425 ("deepseek", 128_000),
1426];
1427
1428impl Config {
1429 pub fn context_window(&self, model: &str) -> Option<u64> {
1434 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1435 let mut best: Option<(usize, u64)> = None;
1436 for (key, window) in entries {
1437 if key == model {
1438 return Some(window);
1439 }
1440 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1441 best = Some((key.len(), window));
1442 }
1443 }
1444 best.map(|(_, w)| w)
1445 }
1446 lookup(
1447 model,
1448 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1449 )
1450 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1451 }
1452}
1453
1454#[derive(Debug, Clone, Deserialize, Serialize)]
1464#[serde(deny_unknown_fields, default)]
1465pub struct Daemon {
1466 pub max_concurrent_runs: usize,
1487 pub pause_for_interrupts: bool,
1503 pub max_deputies: usize,
1510 pub release_stall_minutes: u64,
1517}
1518
1519impl Default for Daemon {
1520 fn default() -> Self {
1521 Self {
1522 max_concurrent_runs: 1,
1523 pause_for_interrupts: false,
1524 max_deputies: 2,
1525 release_stall_minutes: 60,
1526 }
1527 }
1528}
1529
1530#[derive(Debug, Clone, Deserialize, Serialize)]
1542#[serde(deny_unknown_fields, default)]
1543pub struct Repos {
1544 pub roots: Vec<PathBuf>,
1548 pub auto_clone: bool,
1550 pub clone_command: Option<Vec<String>>,
1554 pub scan_ttl: u64,
1561 pub fetch_interval: u64,
1566}
1567
1568impl Default for Repos {
1569 fn default() -> Self {
1570 Self {
1571 roots: Vec::new(),
1572 auto_clone: false,
1573 clone_command: None,
1574 scan_ttl: 86_400,
1575 fetch_interval: 600,
1576 }
1577 }
1578}
1579
1580#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1596#[serde(deny_unknown_fields, default)]
1597pub struct Prompts {
1598 pub all: String,
1600 pub implement: String,
1602 pub judge: String,
1604 pub review: String,
1606 pub fix: String,
1608}
1609
1610impl Prompts {
1611 pub fn overlay(&self, node: &str) -> Option<String> {
1616 let specific = match node {
1617 "implement" => &self.implement,
1618 "judge" | "vote" | "deliberate" => &self.judge,
1619 "review" => &self.review,
1620 "fix" => &self.fix,
1621 _ => "",
1622 };
1623 let mut parts: Vec<&str> = Vec::new();
1624 for p in [self.all.trim(), specific.trim()] {
1625 if !p.is_empty() {
1626 parts.push(p);
1627 }
1628 }
1629 if parts.is_empty() {
1630 return None;
1631 }
1632 Some(parts.join("\n\n"))
1633 }
1634}
1635
1636#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1643#[serde(deny_unknown_fields, default)]
1644pub struct Notify {
1645 pub command: Vec<String>,
1648}
1649
1650#[derive(Debug, Clone, Deserialize, Serialize)]
1652#[serde(deny_unknown_fields, default)]
1653pub struct Talk {
1654 pub allow_write: bool,
1658 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1660 pub standing_authorization: bool,
1661 pub completion_chat: bool,
1666 pub personas: Vec<PersonaSpec>,
1671 pub operator_name: Option<String>,
1675}
1676
1677pub const OPERATOR_NAME_MAX: usize = 64;
1679
1680impl Default for Talk {
1681 fn default() -> Self {
1682 Self {
1683 allow_write: true,
1684 standing_authorization: false,
1685 completion_chat: true,
1686 personas: Vec::new(),
1687 operator_name: None,
1688 }
1689 }
1690}
1691
1692impl Talk {
1693 pub fn operator_name(&self) -> Option<&str> {
1695 self.operator_name
1696 .as_deref()
1697 .map(str::trim)
1698 .filter(|n| !n.is_empty())
1699 }
1700}
1701
1702#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1704#[serde(deny_unknown_fields)]
1705pub struct PersonaSpec {
1706 pub id: String,
1708 #[serde(default)]
1711 pub name: String,
1712 #[serde(default)]
1715 pub prompt: String,
1716 #[serde(default, skip_serializing_if = "Option::is_none")]
1720 pub icon: Option<String>,
1721}
1722
1723#[derive(Debug, Clone)]
1725pub struct ResolvedRoles {
1726 pub implementers: Vec<AgentSpec>,
1728 pub judges: Vec<AgentSpec>,
1730 pub reviewers: Vec<AgentSpec>,
1732 pub fixer: Option<Vec<AgentSpec>>,
1737 pub conductor: AgentSpec,
1739 pub implementer_roster: Vec<AgentSpec>,
1747 pub judge_roster: Vec<AgentSpec>,
1751 pub reviewer_roster: Vec<AgentSpec>,
1753}
1754
1755fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1762 let mut out = Vec::new();
1763 for (k, v) in table {
1764 if prefix.is_empty() && k == "vars" {
1765 continue;
1766 }
1767 let path = if prefix.is_empty() {
1768 k.clone()
1769 } else {
1770 format!("{prefix}.{k}")
1771 };
1772 match v {
1773 toml::Value::Array(_) => out.push(path),
1774 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1775 _ => {}
1776 }
1777 }
1778 out
1779}
1780
1781#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1783enum ArrayMerge {
1784 Append,
1788 Replace,
1791}
1792
1793fn array_merge_policy(key: &str) -> ArrayMerge {
1832 match key {
1833 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1834 _ => ArrayMerge::Replace,
1835 }
1836}
1837
1838impl Config {
1839 pub fn load(path: &Path) -> Result<Self> {
1842 Self::load_layers(&[path.to_path_buf()])
1843 }
1844
1845 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1855 let mut ctx = teravars::system_context();
1856 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1857 ctx.insert("env", &env);
1858 if let Some(last) = paths.last()
1859 && let Some(dir) = last.parent()
1860 {
1861 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1864 .map(|s| PathBuf::from(s.trim()))
1865 .unwrap_or_else(|_| dir.to_path_buf());
1866 ctx.insert("repo", &dir.to_string_lossy());
1867 ctx.insert(
1868 "repo_name",
1869 &dir.file_name().unwrap_or_default().to_string_lossy(),
1870 );
1871 }
1872 ctx
1873 }
1874
1875 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1883 Self::load_layers_with_machine(paths, Self::machine_layer())
1884 }
1885
1886 fn load_layers_with_machine(paths: &[PathBuf], machine: Option<PathBuf>) -> Result<Self> {
1887 let mut engine = teravars::Engine::default();
1888 let ctx = Self::render_ctx(paths);
1889 if paths.len() > 1 {
1890 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1891 if error.downcast_ref::<ConfigFailure>().is_some() {
1892 error
1893 } else {
1894 let message = error.to_string();
1897 error
1898 .context(ConfigFailure::layers("config-merge", paths))
1899 .context(message)
1900 }
1901 })?;
1902 }
1903 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1904 .map_err(|error| {
1905 let cause = ConfigFailure::render(&error, paths);
1906 anyhow::Error::new(error).context(cause)
1907 })
1908 .with_context(|| {
1909 format!(
1910 "rendering config via teravars: {}",
1911 paths
1912 .iter()
1913 .map(|p| p.display().to_string())
1914 .collect::<Vec<_>>()
1915 .join(", ")
1916 )
1917 })?;
1918 let mut table = merged.config;
1919 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1920 let standing = table
1923 .get_mut("talk")
1924 .and_then(toml::Value::as_table_mut)
1925 .and_then(|talk| talk.remove("standing_authorization"));
1926 let standing = if standing.is_some()
1927 && let Some(machine) = machine.filter(|machine| paths.contains(machine))
1928 {
1929 let machine_paths = [machine];
1930 let mut engine = teravars::Engine::default();
1931 let layer = teravars::load_merged(
1932 &machine_paths,
1933 &mut engine,
1934 &Self::render_ctx(&machine_paths),
1935 )
1936 .context("read machine standing authorization")?;
1937 layer
1938 .config
1939 .get("talk")
1940 .and_then(|talk| talk.get("standing_authorization"))
1941 .map(|value| {
1942 value.as_bool().context(
1943 "[talk] standing_authorization in the machine layer must be a boolean",
1944 )
1945 })
1946 .transpose()?
1947 .unwrap_or(false)
1948 } else {
1949 false
1950 };
1951 table.remove("vars");
1954 let detect_agents = !table.contains_key("agents");
1958 let mut cfg: Self = toml::Value::Table(table)
1959 .try_into()
1960 .context("deserializing magi config")
1961 .context(ConfigFailure::layers("config-deserialize", paths))?;
1962 cfg.talk.standing_authorization = standing;
1963 if !cfg.graph.question_routing {
1964 tracing::warn!(
1965 "[graph] question_routing is retired and ignored; task inquiries always use their chat"
1966 );
1967 }
1968 crate::persona::validate(&cfg.talk.personas)?;
1969 if let Some(own) = cfg.disk.reclaim_free_bytes
1970 && own < cfg.disk.min_free_bytes
1971 {
1972 tracing::warn!(
1973 "[disk] reclaim_free_bytes ({own}) is below min_free_bytes ({}); collection aims at min_free_bytes",
1974 cfg.disk.min_free_bytes
1975 );
1976 }
1977 cfg.worktree.validate()?;
1978 cfg.release.validate()?;
1979 if let Some(name) = cfg.talk.operator_name() {
1980 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1981 bail!(
1982 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1983 );
1984 }
1985 }
1986 if detect_agents {
1987 cfg.agents = Self::autodetected().agents;
1988 }
1989 Ok(cfg)
1990 }
1991
1992 fn normalize_renamed_keys(
2000 paths: &[PathBuf],
2001 engine: &mut teravars::Engine,
2002 ctx: &teravars::Context,
2003 table: &mut toml::map::Map<String, toml::Value>,
2004 ) -> Result<()> {
2005 let both = matches!(
2006 table.get("graph"),
2007 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
2008 );
2009 if !both {
2010 return Ok(());
2011 }
2012 let mut winner: Option<toml::Value> = None;
2013 for path in paths {
2014 let one = teravars::load_merged([path], engine, ctx)
2015 .map_err(|error| {
2016 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
2017 anyhow::Error::new(error).context(cause)
2018 })
2019 .with_context(|| format!("rendering {}", path.display()))?;
2020 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
2021 continue;
2022 };
2023 if g.contains_key("candidates") && g.contains_key("implementers") {
2024 bail!(
2025 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
2026 path.display()
2027 );
2028 }
2029 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
2030 winner = Some(v.clone());
2031 }
2032 }
2033 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
2034 g.remove("candidates");
2035 if let Some(v) = winner {
2036 g.insert("implementers".to_owned(), v);
2037 }
2038 }
2039 Ok(())
2040 }
2041
2042 fn refuse_split_arrays(
2066 paths: &[PathBuf],
2067 engine: &mut teravars::Engine,
2068 ctx: &teravars::Context,
2069 ) -> Result<()> {
2070 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
2071 for path in paths {
2072 let one = teravars::load_merged([path], engine, ctx)
2073 .map_err(|error| {
2074 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
2075 anyhow::Error::new(error).context(cause)
2076 })
2077 .with_context(|| format!("rendering {}", path.display()))?;
2078 for key in array_keys(&one.config, "") {
2079 if array_merge_policy(&key) == ArrayMerge::Append {
2080 continue;
2081 }
2082 if let Some(first) = seen.get(&key) {
2083 bail!(
2084 "`{key}` is an array declared in two config layers:\n \
2085 {}\n {}\nteravars appends arrays when it merges, so \
2086 magi would run the concatenation of both - which is \
2087 not what either file says. Declare `{key}` in exactly \
2088 one of them.",
2089 first.display(),
2090 path.display()
2091 );
2092 }
2093 seen.insert(key, path.clone());
2094 }
2095 }
2096 Ok(())
2097 }
2098
2099 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
2121 let mut engine = teravars::Engine::default();
2122 let ctx = Self::render_ctx(paths);
2123 let mut out = Vec::new();
2124 for path in paths {
2125 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
2126 continue;
2127 };
2128 let mut cur = &one.config;
2129 let mut found = None;
2130 let parts: Vec<&str> = key.split('.').collect();
2131 for (i, part) in parts.iter().enumerate() {
2132 match cur.get(*part) {
2133 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
2134 found = Some(a);
2135 break;
2136 }
2137 Some(toml::Value::Table(t)) => cur = t,
2138 _ => break,
2139 }
2140 }
2141 let Some(values) = found else { continue };
2142 let strings: Vec<String> = values
2143 .iter()
2144 .filter_map(|v| v.as_str().map(str::to_owned))
2145 .collect();
2146 if !strings.is_empty() {
2147 out.push((path.clone(), strings));
2148 }
2149 }
2150 out
2151 }
2152
2153 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
2159 let mut engine = teravars::Engine::default();
2160 let ctx = Self::render_ctx(paths);
2161 paths
2162 .iter()
2163 .map(|path| {
2164 let one = teravars::load_merged([path], &mut engine, &ctx)
2165 .map(|m| m.config)
2166 .with_context(|| format!("rendering {}", path.display()));
2167 (path.clone(), one)
2168 })
2169 .collect()
2170 }
2171
2172 pub fn describe_composed(
2182 paths: &[PathBuf],
2183 commands: &[String],
2184 key: &str,
2185 empty: &str,
2186 ) -> String {
2187 if commands.is_empty() {
2188 return empty.to_owned();
2189 }
2190 let joined = commands.join(" && ");
2191 let provenance = Self::array_provenance(paths, key);
2192 if provenance.len() <= 1 {
2193 return joined;
2194 }
2195 let mut out = joined;
2196 for (path, cmds) in &provenance {
2197 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2198 }
2199 out
2200 }
2201
2202 #[track_caller]
2209 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2210 #[cfg(test)]
2211 crate::web::request_cost::discovery();
2212 tracing::trace!(
2213 caller = %std::panic::Location::caller(),
2214 explicit = explicit.is_some(),
2215 "discovering configuration"
2216 );
2217 if let Some(p) = explicit {
2218 let paths = vec![p.to_path_buf()];
2219 return Ok((Self::load_layers(&paths)?, paths));
2220 }
2221 let paths = Self::layers_checked(repo)?;
2222 if paths.is_empty() {
2223 return Ok((Self::autodetected(), paths));
2224 }
2225 Ok((Self::load_layers(&paths)?, paths))
2226 }
2227
2228 pub async fn discover_fetched(
2231 repo: &Path,
2232 explicit: Option<&Path>,
2233 ) -> Result<(Self, Vec<PathBuf>)> {
2234 if explicit.is_none() && is_git_repo(repo) {
2235 let (remote, cfg_base) = probe_remote_base(repo);
2239 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2240 .await
2241 .with_context(|| ConfigFailure {
2242 stage: "config-base",
2243 target: remote.clone(),
2244 })?;
2245 let out = crate::git::fetch(repo, &remote, &base)
2246 .await
2247 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2248 .with_context(|| ConfigFailure {
2249 stage: "config-fetch",
2250 target: format!("{remote}/{base}"),
2251 })?;
2252 if !out.ok() {
2253 return Err(anyhow::anyhow!(
2254 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2255 out.stderr.lines().next().unwrap_or("").trim()
2256 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2257 }
2258 if cfg_base.is_none() {
2259 crate::git::ensure_remote_head(repo, &remote, &base).await;
2260 }
2261 }
2262 Self::discover(repo, explicit).map_err(|error| {
2263 if error.downcast_ref::<ConfigFailure>().is_some() {
2264 error
2265 } else {
2266 error.context(ConfigFailure {
2267 stage: "config-load",
2268 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2269 })
2270 }
2271 })
2272 }
2273
2274 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2276 let mut paths: Vec<PathBuf> = Self::machine_layer()
2277 .into_iter()
2278 .filter(|p| p.is_file())
2279 .collect();
2280 paths.extend(Self::repo_layers(repo)?);
2281 Ok(paths)
2282 }
2283
2284 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2286 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2287 if let Some(root) = cached {
2288 let relative = path.strip_prefix(root).unwrap_or(path);
2289 let reference = resolve_remote_base(repo)
2290 .map(|(remote, base)| format!("{remote}/{base}"))
2291 .unwrap_or_else(|_| "remote base".to_owned());
2292 format!(
2293 "{} at {reference} (including its includes)",
2294 repo.join(relative).display()
2295 )
2296 } else {
2297 format!("{} (including its includes)", path.display())
2298 }
2299 }
2300
2301 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2304 match inspect_git_repo(repo) {
2305 RepoKind::NotGit => Ok(local_repo_layers(repo)),
2306 RepoKind::Found(dirs) => remote_layers_with_git(repo, Some(dirs)),
2307 RepoKind::Fallback => remote_layers_fallback(repo),
2308 }
2309 }
2310
2311 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2331
2332 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2337 let mut paths = Vec::new();
2338 paths.extend(Self::machine_layer());
2339 paths.push(repo.join(".magi").join("config.toml"));
2340 paths.push(repo.join("magi.toml"));
2341 paths.retain(|p| p.is_file());
2342 paths
2343 }
2344
2345 #[cfg(test)]
2352 pub(crate) fn machine_layer() -> Option<PathBuf> {
2353 std::env::var(Self::CONFIG_DIR_ENV)
2354 .ok()
2355 .filter(|dir| !dir.trim().is_empty())
2356 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2357 }
2358
2359 #[cfg(not(test))]
2361 pub(crate) fn machine_layer() -> Option<PathBuf> {
2362 match std::env::var(Self::CONFIG_DIR_ENV) {
2363 Ok(dir) if dir.trim().is_empty() => None,
2365 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2366 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2367 }
2368 }
2369
2370 pub fn autodetected() -> Self {
2372 let mut cfg = Self::default();
2373 for (kind, id, model) in [
2374 (AgentKind::Claude, "opus", Some("opus")),
2375 (AgentKind::Claude, "sonnet", Some("sonnet")),
2376 (AgentKind::Antigravity, "antigravity", None),
2377 (AgentKind::Opencode, "opencode", None),
2378 (AgentKind::Codex, "codex", None),
2379 (AgentKind::Omp, "omp", None),
2380 ] {
2381 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2382 cfg.agents.push(AgentSpec {
2383 id: id.to_owned(),
2384 kind,
2385 model: model.map(str::to_owned),
2386 command: Vec::new(),
2387 extra_args: Vec::new(),
2388 env: BTreeMap::new(),
2389 prompt_delivery: None,
2390 max_turn_secs: None,
2391 });
2392 }
2393 }
2394 cfg
2395 }
2396
2397 pub fn cache_dir(&self) -> Option<PathBuf> {
2400 self.verify.cache_dir()
2401 }
2402
2403 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2405 self.agents
2406 .iter()
2407 .find(|a| a.id == id)
2408 .with_context(|| format!("no agent with id `{id}` in the roster"))
2409 }
2410
2411 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2418 let mut out = Vec::with_capacity(count);
2419 for i in 0..count {
2420 let spec = if ids.is_empty() {
2421 self.agents[(i + offset) % self.agents.len()].clone()
2422 } else {
2423 self.agent(&ids[i % ids.len()])?.clone()
2424 };
2425 out.push(spec);
2426 }
2427 Ok(out)
2428 }
2429
2430 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2437 if ids.is_empty() {
2438 Ok(self.agents.clone())
2439 } else {
2440 ids.iter().map(|id| self.agent(id).cloned()).collect()
2441 }
2442 }
2443
2444 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2451 if self.agents.is_empty() {
2452 bail!(
2453 "agent roster is empty: no agent CLI found on PATH and no \
2454 [[agents]] in the config. Run `magi init` to write a starter \
2455 magi.toml."
2456 );
2457 }
2458 let pinned = self
2459 .graph
2460 .selected_implementer
2461 .as_ref()
2462 .map(|id| self.agent(id).cloned())
2463 .transpose()?;
2464 Ok(ResolvedRoles {
2465 implementers: match &pinned {
2466 Some(agent) => vec![agent.clone()],
2467 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2468 },
2469 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2470 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2471 fixer: match self.roles.fixer.as_ref() {
2472 Some(choice) => Some(crate::agent::pick_chain(
2475 &self.agents,
2476 Some(choice),
2477 &|_| true,
2478 "fixer",
2479 )?),
2480 None => None,
2481 },
2482 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2487 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2488 Some(ids) if !ids.is_empty() => ids
2491 .iter()
2492 .find_map(|id| self.agent(id).ok())
2493 .cloned()
2494 .with_context(|| {
2495 format!("[roles] conductor names no agent in the roster: {ids:?}")
2496 })?,
2497 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2502 .unwrap_or_else(|_| self.agents[0].clone()),
2503 },
2504 implementer_roster: match pinned {
2505 Some(agent) => vec![agent],
2506 None => self.full_roster(&self.roles.implementers)?,
2507 },
2508 judge_roster: self.full_roster(&self.roles.judges)?,
2509 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2510 })
2511 }
2512
2513 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2535 if self.agents.is_empty() {
2536 bail!(
2537 "agent roster is empty: no agent CLI found on PATH and no \
2538 [[agents]] in the config. Run `magi init` to write a starter \
2539 magi.toml."
2540 );
2541 }
2542 if !self.roles.advisors.is_empty() {
2543 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2544 }
2545 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2546 }
2547
2548 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2552 if self.roles.advisors.is_empty() {
2553 self.full_roster(&self.roles.judges)
2554 } else {
2555 self.full_roster(&self.roles.advisors)
2556 }
2557 }
2558
2559 pub fn shell(&self) -> Vec<String> {
2561 if let Some(s) = &self.verify.shell {
2562 return s.clone();
2563 }
2564 if which("sh") {
2565 vec!["sh".to_owned(), "-c".to_owned()]
2566 } else {
2567 vec!["cmd".to_owned(), "/C".to_owned()]
2568 }
2569 }
2570
2571 pub fn starter_toml() -> String {
2573 let detected = Self::autodetected();
2574 let mut s = String::from(
2575 "# magi — blind multi-agent implementation competition.\n\
2576 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2577 # -> blind judging -> deliberation -> private final vote\n\
2578 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2579 #\n\
2580 # Rendered by teravars: a `[vars]` table, env\n\
2581 # and system lookups, and `include = [...]` all work. Tera\n\
2582 # braces are live everywhere in this file, but comments are\n\
2583 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2584 # may quote `{{ ... }}` freely.\n\
2585 #\n\
2586 # Layers deep-merge in increasing\n\
2587 # precedence, so the roster can live once per machine in\n\
2588 # <config_dir>/magi/config.toml and each repo only states its own\n\
2589 # gate:\n\
2590 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2591 [vars]\n\
2592 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2593 # Single quotes inside the braces: teravars renders the raw file\n\
2594 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2595 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2596 );
2597 if detected.agents.is_empty() {
2598 s.push_str(
2599 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2600 # kind = claude | opencode | antigravity | codex | command\n\
2601 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2602 );
2603 } else {
2604 for a in &detected.agents {
2605 s.push_str("[[agents]]\n");
2606 s.push_str(&format!("id = {:?}\n", a.id));
2607 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2608 if let Some(m) = &a.model {
2609 s.push_str(&format!("model = {m:?}\n"));
2610 }
2611 s.push('\n');
2612 }
2613 }
2614 s.push_str(
2615 "# Leave a role list empty to rotate through the roster.\n\
2616 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2617 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2618 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2619 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2620 [roles]\n\
2621 implementers = []\n\
2622 judges = []\n\
2623 reviewers = []\n\
2624 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2625 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2626 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2627 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2628 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2629 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2630 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2631 [graph]\n\
2632 # Gate GitHub prose; secret redaction is always enabled.\n\
2633 github_text_guard = true\n\
2634 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2635 github_language = \"en\"\n\
2636 implementers = 3\n\
2637 judges = 3\n\
2638 deliberate_rounds = 1\n\
2639 reviewers = 3\n\
2640 review_rounds = 6\n\
2641 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2642 gate_fix_rounds = 1\n\
2643 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2644 rerun_flaky_checks = true\n\
2645 # 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\
2646 rerun_failed_e2e = true\n\
2647 # Port the strengths judges named in the losing candidates onto the\n\
2648 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2649 graft_runner_up = true\n\
2650 max_parallel = 4\n\
2651 language = \"en\"\n\
2652 # One CLI conversation per seat: judges keep their own argument\n\
2653 # across deliberation, the fixer keeps its implementation context.\n\
2654 sessions = true\n\
2655 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2656 # the final gate inherit this value for compatibility.\n\
2657 timeout_review = 1200\n\
2658 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2659 # verification independent if timeout_review changes later.\n\
2660 # timeout_verify = 1200\n\
2661 # Longest a seat waits for the shared build cache before it is\n\
2662 # spawned. Never counted against an agent's own timeout; expiry\n\
2663 # holds the run (resumable) instead of failing the agent.\n\
2664 # timeout_resource_wait = 1800\n\n\
2665 # Standing chat policy and operator name.\n\
2666 # [talk]\n\
2667 # allow_write = true # accept /apply <action> for one turn; false disables direct changes\n\
2668 # standing_authorization = false # machine layer only; bounded chat recovery\n\
2669 # completion_chat = true # report human/issue-filed task completion to its task chat\n\
2670 # operator_name = \"Commander\"\n\n\
2671 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2672 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2673 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2674 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2675 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2676 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2677 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2678 # [[talk.personas]]\n\
2679 # id = \"gendo\"\n\
2680 # name = \"Gendo Ikari\"\n\
2681 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2682 # icon = \"~/pictures/gendo.png\"\n\n\
2683 [verify]\n\
2684 # Run once per review round in the winner's worktree; failures are\n\
2685 # fed back to the fixer.\n\
2686 e2e = []\n\
2687 # Final gate. Every command must exit 0 before a merge.\n\
2688 gate = []\n\
2689 # Mechanical fixers (formatters) run in the winner's worktree before\n\
2690 # e2e and before the gate; whatever they change becomes one commit. A\n\
2691 # failing command only warns - the gate stays the arbiter. Same timeout\n\
2692 # as the gate (timeout_verify). Keep it light and idempotent.\n\
2693 # pre_gate = []\n\n\
2694 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2695 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2696 # before any agent or verify command touches it. `copy` reads from the\n\
2697 # primary checkout and never overwrites; `optional` skips a missing\n\
2698 # source. `run` goes through the shell with the worktree as cwd and\n\
2699 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2700 # the verify timeout). Setup must not edit tracked files, and what it\n\
2701 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2702 # layer only.\n\
2703 # [worktree]\n\
2704 # setup = [\n\
2705 # { copy = \".env.example -> .env\" },\n\
2706 # { copy = \".env.local\", optional = true },\n\
2707 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2708 # ]\n\
2709 # pre_clean = [] # Repeatable cleanup before owned clean -fdx.\n\n\
2710 [merge]\n\
2711 # none | local | pr\n\
2712 mode = \"none\"\n\
2713 # expected (default) | none. Set none only in repository config without CI.\n\
2714 # Ignores all check statuses; reviews and approval still apply.\n\
2715 # ci = \"expected\"\n\
2716 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2717 [update]\n\
2718 # off | notify | install — checked in the background, throttled.\n\
2719 mode = \"notify\"\n\
2720 # interval = \"24h\"\n\n\
2721 # Opt-in: magi web updates and restarts automatically when a newer release is found.\n\
2722 # auto_restart = false\n\
2723 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2724 # Handover drains only short admission transactions; active workers continue\n\
2725 # on their original executable generation while new work uses the new one.\n\
2726 # Standalone magi serve cannot restart.\n\
2727 # Failed tags are skipped until process restart or a different tag.\n\
2728 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2729 [daemon]\n\
2730 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2731 # no new commit and no check changing state before `magi serve`\n\
2732 # notices and asks you. A failed check is rerun once on its own;\n\
2733 # still red after that escalates at once. 0 turns the watcher off.\n\
2734 # release_stall_minutes = 60\n\n\
2735 [release]\n\
2736 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2737 # Actions never run (private, no minutes): the release pull request\n\
2738 # does not wait for CI, you approve the merge in magi, and then\n\
2739 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2740 # runs `commands` from a clean checkout of the merge commit. A\n\
2741 # failure holds the release with a notice; it is never retried blind.\n\
2742 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2743 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2744 # mode = \"actions\"\n\
2745 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2746 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2747 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2748 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2749 # timeout_minutes = 30\n\
2750 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2751 # The first entry is the version of record and must be the file the\n\
2752 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2753 # rewritten to the same version. Paths are relative to the repository\n\
2754 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2755 # is not touched.\n\
2756 # version_files = [\n\
2757 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2758 # { path = \"package.json\", kind = \"json\" },\n\
2759 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2760 # ]\n",
2761 );
2762 s
2763 }
2764}
2765
2766pub fn which(program: &str) -> bool {
2768 find_program(program).is_some()
2769}
2770
2771pub fn find_program(program: &str) -> Option<PathBuf> {
2780 find_program_on(program, &std::env::var_os("PATH")?)
2781}
2782
2783pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2786 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2787 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2788}
2789
2790fn find_program_in(
2791 program: &str,
2792 paths: &std::ffi::OsStr,
2793 pathext: Option<&str>,
2794) -> Option<PathBuf> {
2795 let p = Path::new(program);
2796 if p.components().count() > 1 {
2797 return p.is_file().then(|| p.to_path_buf());
2798 }
2799 std::env::split_paths(paths).find_map(|dir| match pathext {
2800 Some(exts) => {
2801 let bare = dir.join(program);
2802 if p.extension().is_some() && bare.is_file() {
2803 return Some(bare);
2804 }
2805 exts.split(';')
2806 .filter(|e| !e.is_empty())
2807 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2808 .find(|c| c.is_file())
2809 }
2810 None => Some(dir.join(program)).filter(|c| c.is_file()),
2811 })
2812}
2813
2814const REPO_MARKER: &str = ".magi-repo";
2816
2817const CACHE_MANIFEST: &str = ".magi-cache-manifest.json";
2820const CACHE_MANIFEST_VERSION: u32 = 3;
2821const REPO_LAYER_RELS: [&str; 2] = [".magi/config.toml", "magi.toml"];
2822
2823const GIT_OVERRIDE_ENVS: &[&str] = &[
2827 "GIT_DIR",
2828 "GIT_COMMON_DIR",
2829 "GIT_WORK_TREE",
2830 "GIT_OBJECT_DIRECTORY",
2831 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
2832 "GIT_CEILING_DIRECTORIES",
2833 "GIT_DISCOVERY_ACROSS_FILESYSTEM",
2834 "GIT_NAMESPACE",
2835];
2836
2837fn has_git_env_override() -> bool {
2838 GIT_OVERRIDE_ENVS
2839 .iter()
2840 .any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))
2841}
2842
2843#[derive(Debug, Clone)]
2844struct GitDirs {
2845 common_dir: PathBuf,
2846 files_ref_backend: bool,
2847}
2848
2849#[derive(Debug, Clone)]
2850enum RepoKind {
2851 NotGit,
2852 Found(GitDirs),
2853 Fallback,
2854}
2855
2856fn local_repo_layers(repo: &Path) -> Vec<PathBuf> {
2857 [
2858 repo.join(".magi").join("config.toml"),
2859 repo.join("magi.toml"),
2860 ]
2861 .into_iter()
2862 .filter(|p| p.is_file())
2863 .collect()
2864}
2865
2866fn inspect_git_repo(repo: &Path) -> RepoKind {
2867 if has_git_env_override() || !repo.is_dir() {
2868 return RepoKind::Fallback;
2869 }
2870 let start = match repo.canonicalize() {
2871 Ok(p) => p,
2872 Err(_) => {
2873 if repo.is_absolute() {
2874 repo.to_path_buf()
2875 } else {
2876 match std::env::current_dir() {
2877 Ok(cwd) => cwd.join(repo),
2878 Err(_) => return RepoKind::Fallback,
2879 }
2880 }
2881 }
2882 };
2883
2884 for dir in start.ancestors() {
2885 let dot_git = dir.join(".git");
2886 match std::fs::symlink_metadata(&dot_git) {
2887 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2888 if dir.join("HEAD").is_file()
2891 && dir.join("objects").is_dir()
2892 && (dir.join("refs").is_dir() || dir.join("reftable").is_dir())
2893 {
2894 return RepoKind::Fallback;
2895 }
2896 continue;
2897 }
2898 Err(_) => return RepoKind::Fallback,
2899 Ok(meta) => {
2900 if meta.file_type().is_symlink() {
2901 return RepoKind::Fallback;
2902 }
2903 let git_dir = if meta.is_dir() {
2904 if !dot_git.join("HEAD").is_file() {
2905 return RepoKind::Fallback;
2906 }
2907 dot_git
2908 } else if meta.is_file() {
2909 let Ok(raw) = std::fs::read_to_string(&dot_git) else {
2910 return RepoKind::Fallback;
2911 };
2912 let Some(target) = raw
2913 .trim_end_matches(['\r', '\n'])
2914 .strip_prefix("gitdir:")
2915 .map(str::trim)
2916 .filter(|s| !s.is_empty())
2917 else {
2918 return RepoKind::Fallback;
2919 };
2920 let target_path = PathBuf::from(target);
2921 let resolved = if target_path.is_absolute() {
2922 target_path
2923 } else {
2924 dir.join(target_path)
2925 };
2926 if !resolved.is_dir() || !resolved.join("HEAD").is_file() {
2927 return RepoKind::Fallback;
2928 }
2929 resolved
2930 } else {
2931 return RepoKind::Fallback;
2932 };
2933
2934 let commondir_file = git_dir.join("commondir");
2935 let common_dir = match std::fs::symlink_metadata(&commondir_file) {
2936 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2937 git_dir.canonicalize().unwrap_or(git_dir)
2938 }
2939 Ok(m) if m.is_file() => {
2940 let Ok(raw) = std::fs::read_to_string(&commondir_file) else {
2941 return RepoKind::Fallback;
2942 };
2943 let target = raw.trim();
2944 if target.is_empty() {
2945 return RepoKind::Fallback;
2946 }
2947 let target_path = PathBuf::from(target);
2948 let joined = if target_path.is_absolute() {
2949 target_path
2950 } else {
2951 git_dir.join(target_path)
2952 };
2953 let Ok(canonical) = joined.canonicalize() else {
2954 return RepoKind::Fallback;
2955 };
2956 if !canonical.is_dir() {
2957 return RepoKind::Fallback;
2958 }
2959 canonical
2960 }
2961 _ => return RepoKind::Fallback,
2962 };
2963
2964 let files_ref_backend = is_standard_files_ref_backend(&common_dir);
2965 return RepoKind::Found(GitDirs {
2966 common_dir,
2967 files_ref_backend,
2968 });
2969 }
2970 }
2971 }
2972 RepoKind::NotGit
2973}
2974
2975fn is_git_repo(repo: &Path) -> bool {
2976 match inspect_git_repo(repo) {
2977 RepoKind::NotGit => false,
2978 RepoKind::Found(_) => true,
2979 RepoKind::Fallback => is_git_worktree(repo),
2980 }
2981}
2982
2983fn strip_git_config_value(raw: &str) -> String {
2984 let mut out = String::new();
2985 let mut in_quotes = false;
2986 let mut escaped = false;
2987 for ch in raw.chars() {
2988 if escaped {
2989 out.push(ch);
2990 escaped = false;
2991 continue;
2992 }
2993 if in_quotes {
2994 match ch {
2995 '\\' => escaped = true,
2996 '"' => in_quotes = false,
2997 _ => out.push(ch),
2998 }
2999 continue;
3000 }
3001 match ch {
3002 '"' => in_quotes = true,
3003 '#' | ';' => break,
3004 _ => out.push(ch),
3005 }
3006 }
3007 out.trim().to_owned()
3008}
3009
3010fn is_standard_files_ref_backend(common_dir: &Path) -> bool {
3014 if common_dir.join("reftable").exists() || !common_dir.join("refs").is_dir() {
3015 return false;
3016 }
3017 let Ok(config) = std::fs::read_to_string(common_dir.join("config")) else {
3018 return false;
3019 };
3020 let mut section = String::new();
3021 for raw_line in config.lines() {
3022 let line = raw_line.trim();
3023 if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
3024 continue;
3025 }
3026 if line.ends_with('\\') {
3027 return false;
3028 }
3029 if let Some(rest) = line.strip_prefix('[') {
3030 let Some(end) = rest.find(']') else {
3031 return false;
3032 };
3033 let trailing = rest[end + 1..].trim();
3034 if !trailing.is_empty() && !trailing.starts_with('#') && !trailing.starts_with(';') {
3035 return false;
3036 }
3037 let header = &rest[..end];
3038 section = header
3039 .split(|c: char| c.is_ascii_whitespace() || c == '"')
3040 .next()
3041 .unwrap_or("")
3042 .to_ascii_lowercase();
3043 if matches!(section.as_str(), "include" | "includeif") {
3044 return false;
3045 }
3046 continue;
3047 }
3048 let (key, val) = match line.split_once('=') {
3049 Some((k, v)) => (
3050 k.trim().to_ascii_lowercase(),
3051 strip_git_config_value(v).to_ascii_lowercase(),
3052 ),
3053 None => (
3054 strip_git_config_value(line).to_ascii_lowercase(),
3055 "true".to_owned(),
3056 ),
3057 };
3058 match section.as_str() {
3059 "core" if key == "repositoryformatversion" => {
3060 if !matches!(val.as_str(), "0" | "1") {
3061 return false;
3062 }
3063 }
3064 "extensions" => match key.as_str() {
3065 "refstorage" if val == "files" => {}
3066 "objectformat" if val == "sha1" => {}
3067 "worktreeconfig" | "relativeworktrees" | "partialclone" | "promisor"
3068 | "preciousobjects" | "noop" | "manyfiles" => {}
3069 _ => return false,
3070 },
3071 _ => {}
3072 }
3073 }
3074 true
3075}
3076
3077fn is_safe_ref_name(name: &str) -> bool {
3078 if !name.starts_with("refs/")
3079 || name.ends_with('/')
3080 || name.starts_with("refs/bisect/")
3081 || name.starts_with("refs/worktree/")
3082 || name.starts_with("refs/rewritten/")
3083 {
3084 return false;
3085 }
3086 name.split('/').all(|part| {
3087 !part.is_empty()
3088 && part != "."
3089 && part != ".."
3090 && !part.contains('\\')
3091 && !part.bytes().any(|b| b <= 0x20 || b == 0x7f)
3092 })
3093}
3094
3095fn join_rel_path(base: &Path, rel: &str) -> PathBuf {
3096 let mut path = base.to_path_buf();
3097 for part in rel.split('/') {
3098 path.push(part);
3099 }
3100 path
3101}
3102
3103fn is_sha1_hex(s: &str) -> bool {
3104 s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
3105}
3106
3107fn is_hex_oid(s: &str) -> bool {
3108 (s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
3109}
3110
3111enum LooseRef {
3112 Missing,
3113 Oid(String),
3114 Symref(String),
3115 Unknown,
3116}
3117
3118fn read_loose_ref(common_dir: &Path, ref_name: &str) -> LooseRef {
3119 if !is_safe_ref_name(ref_name) {
3120 return LooseRef::Unknown;
3121 }
3122 let path = join_rel_path(common_dir, ref_name);
3123 match std::fs::symlink_metadata(&path) {
3124 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return LooseRef::Missing,
3125 Err(_) => return LooseRef::Unknown,
3126 Ok(meta) if !meta.is_file() => return LooseRef::Unknown,
3127 Ok(_) => {}
3128 }
3129 match std::fs::read_to_string(&path) {
3130 Err(e) if e.kind() == std::io::ErrorKind::NotFound => LooseRef::Missing,
3131 Err(_) => LooseRef::Unknown,
3132 Ok(raw) => {
3133 let trimmed = raw.trim();
3134 if let Some(target) = trimmed.strip_prefix("ref:") {
3135 let target = target.trim();
3136 if is_safe_ref_name(target) {
3137 LooseRef::Symref(target.to_owned())
3138 } else {
3139 LooseRef::Unknown
3140 }
3141 } else if is_sha1_hex(trimmed) {
3142 LooseRef::Oid(trimmed.to_ascii_lowercase())
3143 } else {
3144 LooseRef::Unknown
3145 }
3146 }
3147 }
3148}
3149
3150enum PackedRef {
3151 Missing,
3152 Oid(String),
3153 Unknown,
3154}
3155
3156fn read_packed_ref(common_dir: &Path, ref_name: &str) -> PackedRef {
3157 let raw = match std::fs::read_to_string(common_dir.join("packed-refs")) {
3158 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return PackedRef::Missing,
3159 Err(_) => return PackedRef::Unknown,
3160 Ok(raw) => raw,
3161 };
3162 let mut lines = raw.lines().peekable();
3163 while let Some(line) = lines.next() {
3164 let line = line.trim_end_matches('\r');
3165 if line.is_empty() || line.starts_with('#') || line.starts_with('^') {
3166 continue;
3167 }
3168 let Some((oid, name)) = line.split_once(' ') else {
3169 return PackedRef::Unknown;
3170 };
3171 if name == ref_name {
3172 if !is_sha1_hex(oid) {
3173 return PackedRef::Unknown;
3174 }
3175 if lines
3176 .peek()
3177 .is_some_and(|next| next.trim_end_matches('\r').starts_with('^'))
3178 {
3179 return PackedRef::Unknown;
3181 }
3182 return PackedRef::Oid(oid.to_ascii_lowercase());
3183 }
3184 }
3185 PackedRef::Missing
3186}
3187
3188fn resolve_remote_head_files(common_dir: &Path, remote: &str) -> Option<String> {
3189 let head = format!("refs/remotes/{remote}/HEAD");
3190 match read_loose_ref(common_dir, &head) {
3191 LooseRef::Symref(target) => crate::git::remote_head_branch(remote, &target),
3192 _ => None,
3193 }
3194}
3195
3196fn resolve_ref_oid_files(common_dir: &Path, start_ref: &str) -> Option<String> {
3197 let mut current = start_ref.to_owned();
3198 for _ in 0..8 {
3199 match read_loose_ref(common_dir, ¤t) {
3200 LooseRef::Oid(oid) => return Some(oid),
3201 LooseRef::Symref(next) => current = next,
3202 LooseRef::Missing => {
3203 return match read_packed_ref(common_dir, ¤t) {
3204 PackedRef::Oid(oid) => Some(oid),
3205 PackedRef::Missing | PackedRef::Unknown => None,
3206 };
3207 }
3208 LooseRef::Unknown => return None,
3209 }
3210 }
3211 None
3212}
3213
3214fn repository_git() -> std::process::Command {
3215 #[cfg(test)]
3216 crate::web::request_cost::git();
3217 let mut command = std::process::Command::new("git");
3218 command.arg("--no-replace-objects");
3219 command
3220}
3221
3222fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
3223 use crate::proc::Quiet as _;
3224 let out = repository_git()
3225 .args(args)
3226 .quiet()
3227 .current_dir(repo)
3228 .stdin(std::process::Stdio::null())
3229 .output()
3230 .ok()?;
3231 out.status
3232 .success()
3233 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
3234}
3235
3236fn is_git_worktree(repo: &Path) -> bool {
3239 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
3240}
3241
3242#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3245pub enum OwnerHold {
3246 LandApproval,
3248 HoldContestedMerge,
3250}
3251
3252impl OwnerHold {
3253 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
3255
3256 pub fn key(self) -> &'static str {
3258 match self {
3259 Self::LandApproval => "land_approval",
3260 Self::HoldContestedMerge => "hold_contested_merge",
3261 }
3262 }
3263
3264 pub fn base_value(self, graph: &Graph) -> bool {
3266 match self {
3267 Self::LandApproval => graph.land_approval,
3268 Self::HoldContestedMerge => graph.hold_contested_merge,
3269 }
3270 }
3271}
3272
3273pub async fn branch_owner_holds(
3276 repo: &Path,
3277 head: &str,
3278) -> (Vec<(OwnerHold, String)>, Vec<String>) {
3279 let mut holds = Vec::new();
3280 let mut diagnostics = Vec::new();
3281 if let Err(error) =
3284 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
3285 {
3286 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
3287 return (holds, diagnostics);
3288 }
3289 for file in ["magi.toml", ".magi/config.toml"] {
3290 let object = format!("{head}:{file}");
3291 let text = match crate::git::git(repo, &["show", &object]).await {
3292 Ok(text) => text,
3293 Err(error) => {
3294 let error = format!("{error:#}");
3296 if !error.contains("does not exist in")
3297 && !error.contains("exists on disk, but not in")
3298 {
3299 diagnostics.push(format!(
3300 "cannot read reviewed branch {file} at {head}: {error}"
3301 ));
3302 }
3303 continue;
3304 }
3305 };
3306 let value = match toml::from_str::<toml::Value>(&text) {
3307 Ok(value) => value,
3308 Err(error) => {
3309 diagnostics.push(format!(
3310 "cannot parse reviewed branch {file} at {head}: {error}"
3311 ));
3312 continue;
3313 }
3314 };
3315 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
3316 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
3317 }
3318 for hold in OwnerHold::ALL {
3319 if value
3320 .get("graph")
3321 .and_then(|g| g.get(hold.key()))
3322 .and_then(toml::Value::as_bool)
3323 == Some(true)
3324 {
3325 holds.push((hold, file.to_owned()));
3326 }
3327 }
3328 }
3329 (holds, diagnostics)
3330}
3331
3332#[derive(Deserialize, Default)]
3333struct ProbeMerge {
3334 base: Option<String>,
3335 remote: Option<String>,
3336}
3337
3338#[derive(Deserialize, Default)]
3339struct Probe {
3340 merge: Option<ProbeMerge>,
3341}
3342
3343fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
3349 if !path.is_file() {
3350 return None;
3351 }
3352 let paths = [path.to_path_buf()];
3353 let mut engine = teravars::Engine::default();
3354 let mut ctx = Config::render_ctx(&paths);
3355 ctx.insert("repo", &repo.to_string_lossy());
3358 ctx.insert(
3359 "repo_name",
3360 &repo.file_name().unwrap_or_default().to_string_lossy(),
3361 );
3362 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
3363 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
3364 {
3365 return probe.merge;
3366 }
3367 let text = std::fs::read_to_string(path).ok()?;
3368 toml::from_str::<Probe>(&text).ok()?.merge
3369}
3370
3371fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
3373 let mut remote = None;
3374 let mut base = None;
3375 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
3376 sources.push(repo.join("magi.toml"));
3377 sources.push(repo.join(".magi").join("config.toml"));
3378 for path in sources {
3379 if let Some(m) = probe_merge(&path, repo) {
3380 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
3381 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
3382 }
3383 }
3384 (remote.unwrap_or_else(|| "origin".to_owned()), base)
3385}
3386
3387fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
3389 let (remote, base) = probe_remote_base(repo);
3390 let base = match base {
3391 Some(b) => b,
3392 None => {
3393 let from_files = match inspect_git_repo(repo) {
3394 RepoKind::Found(dirs) if dirs.files_ref_backend => {
3395 resolve_remote_head_files(&dirs.common_dir, &remote)
3396 }
3397 _ => None,
3398 };
3399 match from_files {
3400 Some(b) => b,
3401 None => {
3402 let head = format!("refs/remotes/{remote}/HEAD");
3403 git_out(repo, &["symbolic-ref", "--quiet", &head])
3404 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
3405 .with_context(|| missing_remote_head_msg(&remote))?
3406 }
3407 }
3408 }
3409 };
3410 Ok((remote, base))
3411}
3412
3413fn missing_remote_head_msg(remote: &str) -> String {
3414 format!(
3415 "cannot tell which branch of `{remote}` holds magi.toml: \
3416 set [merge] base, or run `git remote set-head {remote} -a`"
3417 )
3418}
3419
3420fn missing_tracking_ref_msg(remote: &str, base: &str) -> String {
3421 format!(
3422 "`{remote}/{base}` does not exist in this checkout; fetch it \
3423 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
3424 a possibly stale local magi.toml instead"
3425 )
3426}
3427
3428fn fnv_hex(text: &str) -> String {
3429 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
3430 for b in text.bytes() {
3431 hash ^= u64::from(b);
3432 hash = hash.wrapping_mul(0x0100_0000_01b3);
3433 }
3434 format!("{hash:016x}")
3435}
3436
3437fn declares_include(text: &str) -> bool {
3443 match toml::from_str::<toml::Table>(text) {
3444 Ok(table) => {
3445 table.contains_key("include")
3446 || table
3447 .get("teravars")
3448 .and_then(toml::Value::as_table)
3449 .is_some_and(|t| t.contains_key("include"))
3450 }
3451 Err(_) => text.contains("include"),
3452 }
3453}
3454
3455fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
3458 use crate::proc::Quiet as _;
3459 let mut archive = repository_git()
3460 .args(["archive", "--format=tar", sha])
3461 .quiet()
3462 .current_dir(repo)
3463 .stdin(std::process::Stdio::null())
3464 .stdout(std::process::Stdio::piped())
3465 .stderr(std::process::Stdio::null())
3466 .spawn()
3467 .context("running git archive")?;
3468 let tar = std::process::Command::new("tar")
3469 .arg("-x")
3470 .arg("-C")
3471 .arg(dest)
3472 .quiet()
3473 .stdin(archive.stdout.take().context("git archive has no stdout")?)
3474 .output()
3475 .context("running tar")?;
3476 let status = archive.wait().context("waiting for git archive")?;
3477 if !status.success() || !tar.status.success() {
3478 bail!(
3479 "cannot unpack {sha} for the config's includes: {}",
3480 String::from_utf8_lossy(&tar.stderr).trim()
3481 );
3482 }
3483 Ok(())
3484}
3485
3486fn write_extracted(path: &Path, bytes: impl AsRef<[u8]>) -> Result<()> {
3487 use std::io::Write as _;
3488 match std::fs::remove_file(path) {
3489 Ok(()) => {}
3490 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
3491 Err(e) => return Err(e.into()),
3492 }
3493 std::fs::File::create_new(path)?.write_all(bytes.as_ref())?;
3494 Ok(())
3495}
3496
3497#[derive(Debug, Serialize, Deserialize)]
3498struct CacheManifest {
3499 version: u32,
3500 sha: String,
3501 repo: String,
3502 layers: Vec<String>,
3503 extracted_tree: bool,
3504}
3505
3506fn read_cached_layers(dir: &Path, sha: &str, repo: &Path) -> Option<Vec<PathBuf>> {
3507 let raw = std::fs::read(dir.join(CACHE_MANIFEST)).ok()?;
3508 let manifest: CacheManifest = serde_json::from_slice(&raw).ok()?;
3509 if manifest.version != CACHE_MANIFEST_VERSION
3510 || manifest.sha != sha
3511 || manifest.repo != repo.to_string_lossy()
3512 || manifest.layers.len() > REPO_LAYER_RELS.len()
3513 {
3514 return None;
3515 }
3516 let mut out = Vec::with_capacity(manifest.layers.len());
3517 let mut last_idx: Option<usize> = None;
3518 for rel in &manifest.layers {
3519 let idx = REPO_LAYER_RELS.iter().position(|allowed| *allowed == rel)?;
3520 if last_idx.is_some_and(|prev| idx <= prev) {
3521 return None;
3522 }
3523 last_idx = Some(idx);
3524 let file = join_rel_path(dir, rel);
3525 if !file.is_file() || !file.parent().is_some_and(|p| p.join(REPO_MARKER).is_file()) {
3526 return None;
3527 }
3528 out.push(file);
3529 }
3530 Some(out)
3531}
3532
3533enum BatchEntry {
3534 Missing,
3535 Object {
3536 oid: String,
3537 kind: String,
3538 content: Vec<u8>,
3539 },
3540}
3541
3542fn parse_cat_file_batch(mut buf: &[u8], expected: usize) -> Result<Vec<BatchEntry>> {
3543 let mut entries = Vec::with_capacity(expected);
3544 for _ in 0..expected {
3545 let Some(nl) = buf.iter().position(|&b| b == b'\n') else {
3546 bail!("unexpected EOF in git cat-file --batch header");
3547 };
3548 let line = std::str::from_utf8(&buf[..nl])
3549 .context("non-UTF-8 git cat-file --batch header")?
3550 .trim_end_matches('\r');
3551 buf = &buf[nl + 1..];
3552 if line.ends_with(" missing") || line.ends_with(" ambiguous") {
3553 entries.push(BatchEntry::Missing);
3554 continue;
3555 }
3556 let mut parts = line.split_whitespace();
3557 let (Some(oid), Some(kind), Some(size_str), None) =
3558 (parts.next(), parts.next(), parts.next(), parts.next())
3559 else {
3560 bail!("unexpected git cat-file --batch header: {line}");
3561 };
3562 let size: usize = size_str
3563 .parse()
3564 .with_context(|| format!("invalid git cat-file --batch size: {size_str}"))?;
3565 if buf.len() < size + 1 || buf[size] != b'\n' {
3566 bail!("truncated git cat-file --batch body for {oid}");
3567 }
3568 let content = buf[..size].to_vec();
3569 buf = &buf[size + 1..];
3570 entries.push(BatchEntry::Object {
3571 oid: oid.to_owned(),
3572 kind: kind.to_owned(),
3573 content,
3574 });
3575 }
3576 Ok(entries)
3577}
3578
3579fn read_commit_layers_batch(
3582 repo: &Path,
3583 sha: &str,
3584 remote: &str,
3585 base: &str,
3586) -> Result<(String, Vec<(&'static str, String)>)> {
3587 use crate::proc::Quiet as _;
3588 use std::io::Write as _;
3589
3590 let mut child = repository_git()
3591 .args(["cat-file", "--batch"])
3592 .quiet()
3593 .current_dir(repo)
3594 .stdin(std::process::Stdio::piped())
3595 .stdout(std::process::Stdio::piped())
3596 .stderr(std::process::Stdio::piped())
3597 .spawn()
3598 .context("running git cat-file --batch")?;
3599 if let Some(mut stdin) = child.stdin.take() {
3600 let mut query = format!("{sha}^{{commit}}\n");
3601 for rel in REPO_LAYER_RELS {
3602 query.push_str(&format!("{sha}:{rel}\n"));
3603 }
3604 if let Err(e) = stdin.write_all(query.as_bytes())
3605 && e.kind() != std::io::ErrorKind::BrokenPipe
3606 {
3607 return Err(e).context("writing query to git cat-file --batch");
3608 }
3609 }
3610 let out = child
3611 .wait_with_output()
3612 .context("waiting for git cat-file --batch")?;
3613 if !out.status.success() {
3614 bail!(
3615 "cannot read config from {remote}/{base} ({sha}): {}",
3616 String::from_utf8_lossy(&out.stderr).trim()
3617 );
3618 }
3619 let entries = parse_cat_file_batch(&out.stdout, 1 + REPO_LAYER_RELS.len())?;
3620 let mut iter = entries.into_iter();
3621 let commit_sha = match iter.next() {
3622 Some(BatchEntry::Object { oid, kind, .. }) if kind == "commit" && is_hex_oid(&oid) => oid,
3623 _ => bail!("{}", missing_tracking_ref_msg(remote, base)),
3624 };
3625 let present_paths = if iter
3628 .as_slice()
3629 .iter()
3630 .any(|e| matches!(e, BatchEntry::Missing))
3631 {
3632 let tree = git_out(
3633 repo,
3634 &[
3635 "ls-tree",
3636 "--full-tree",
3637 "--name-only",
3638 &commit_sha,
3639 "--",
3640 ".magi/config.toml",
3641 "magi.toml",
3642 ],
3643 )
3644 .context("cannot read repository configuration tree")?;
3645 tree.lines().map(str::to_owned).collect::<Vec<_>>()
3646 } else {
3647 Vec::new()
3648 };
3649 let mut texts = Vec::new();
3650 for (rel, entry) in REPO_LAYER_RELS.into_iter().zip(iter) {
3651 match entry {
3652 BatchEntry::Missing => {
3653 if present_paths.iter().any(|path| path == rel) {
3654 bail!("cannot read {rel} from {remote}/{base} ({commit_sha}): missing object");
3655 }
3656 }
3657 BatchEntry::Object { kind, content, .. } if kind == "blob" => {
3658 texts.push((rel, String::from_utf8_lossy(&content).into_owned()));
3659 }
3660 BatchEntry::Object { kind, .. } => {
3661 bail!(
3662 "cannot read {rel} from {remote}/{base} ({commit_sha}): expected blob, found {kind}"
3663 );
3664 }
3665 }
3666 }
3667 Ok((commit_sha, texts))
3668}
3669
3670fn resolve_common_and_commit_cli(
3671 repo: &Path,
3672 remote: &str,
3673 base: &str,
3674) -> Option<(PathBuf, String)> {
3675 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3676 if !remote.starts_with('-') && !base.starts_with('-') {
3677 let out = git_out(
3678 repo,
3679 &[
3680 "rev-parse",
3681 "--path-format=absolute",
3682 "--git-common-dir",
3683 &spec,
3684 ],
3685 )?;
3686 let mut lines = out.lines().map(str::trim).filter(|l| !l.is_empty());
3687 let common = lines.next()?;
3688 let sha = lines.next()?;
3689 if lines.next().is_none() && is_hex_oid(sha) {
3690 return Some((PathBuf::from(common), sha.to_owned()));
3691 }
3692 }
3693 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3694 .map(|s| s.trim().to_owned())
3695 .filter(|s| is_hex_oid(s))?;
3696 let common = git_out(
3697 repo,
3698 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
3699 )
3700 .map(|s| PathBuf::from(s.trim()))?;
3701 Some((common, sha))
3702}
3703
3704fn resolve_remote_head_and_commit_cli(repo: &Path, remote: &str) -> Result<(String, String)> {
3708 let head = format!("refs/remotes/{remote}/HEAD");
3709 if let Some(out) = git_out(
3710 repo,
3711 &[
3712 "for-each-ref",
3713 "--format=%(refname)%09%(symref)%09%(objecttype)%09%(objectname)%09%(*objecttype)%09%(*objectname)",
3714 &head,
3715 ],
3716 ) {
3717 for line in out.lines() {
3718 let parts: Vec<&str> = line.trim_end_matches('\r').split('\t').collect();
3719 if parts.len() != 6 || parts[0] != head {
3720 continue;
3721 }
3722 let symref = parts[1];
3723 if let Some(base) = crate::git::remote_head_branch(remote, symref) {
3724 if parts[2] == "commit" && is_hex_oid(parts[3]) {
3725 return Ok((base, parts[3].to_owned()));
3726 }
3727 if parts[4] == "commit" && is_hex_oid(parts[5]) {
3728 return Ok((base, parts[5].to_owned()));
3729 }
3730 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3731 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3732 .map(|s| s.trim().to_owned())
3733 .filter(|s| is_hex_oid(s))
3734 .with_context(|| missing_tracking_ref_msg(remote, &base))?;
3735 return Ok((base, sha));
3736 }
3737 }
3738 }
3739 let base = git_out(repo, &["symbolic-ref", "--quiet", &head])
3742 .and_then(|s| crate::git::remote_head_branch(remote, &s))
3743 .with_context(|| missing_remote_head_msg(remote))?;
3744 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3745 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3746 .map(|s| s.trim().to_owned())
3747 .filter(|s| is_hex_oid(s))
3748 .with_context(|| missing_tracking_ref_msg(remote, &base))?;
3749 Ok((base, sha))
3750}
3751
3752fn remote_layers_fallback(repo: &Path) -> Result<Vec<PathBuf>> {
3753 let (remote, cfg_base) = probe_remote_base(repo);
3754 if let Some(base) = cfg_base {
3755 if let Some((common_dir, sha)) = resolve_common_and_commit_cli(repo, &remote, &base) {
3756 return materialize_remote_layers(repo, Some(common_dir), &remote, &base, &sha, true);
3757 }
3758 if !is_git_worktree(repo) {
3759 return Ok(local_repo_layers(repo));
3760 }
3761 bail!("{}", missing_tracking_ref_msg(&remote, &base));
3762 }
3763 if !is_git_worktree(repo) {
3764 return Ok(local_repo_layers(repo));
3765 }
3766 remote_layers_with_git(repo, None)
3767}
3768
3769fn remote_layers_with_git(repo: &Path, git_dirs: Option<GitDirs>) -> Result<Vec<PathBuf>> {
3772 let (remote, cfg_base) = probe_remote_base(repo);
3773
3774 if let Some(dirs) = &git_dirs
3778 && dirs.files_ref_backend
3779 {
3780 let base_from_files = match &cfg_base {
3781 Some(b) => Some(b.clone()),
3782 None => resolve_remote_head_files(&dirs.common_dir, &remote),
3783 };
3784 if let Some(base) = base_from_files {
3785 let tracking = format!("refs/remotes/{remote}/{base}");
3786 if let Some(sha) = resolve_ref_oid_files(&dirs.common_dir, &tracking) {
3787 return materialize_remote_layers(
3788 repo,
3789 Some(dirs.common_dir.clone()),
3790 &remote,
3791 &base,
3792 &sha,
3793 false,
3794 );
3795 }
3796 }
3797 }
3798
3799 let (common_dir, base, sha) = match (git_dirs, cfg_base) {
3803 (Some(dirs), Some(base)) => {
3804 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3805 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3806 .map(|s| s.trim().to_owned())
3807 .filter(|s| is_hex_oid(s))
3808 .with_context(|| missing_tracking_ref_msg(&remote, &base))?;
3809 (Some(dirs.common_dir), base, sha)
3810 }
3811 (Some(dirs), None) => {
3812 let (base, sha) = resolve_remote_head_and_commit_cli(repo, &remote)?;
3813 (Some(dirs.common_dir), base, sha)
3814 }
3815 (None, Some(base)) => {
3816 let (common_dir, sha) = resolve_common_and_commit_cli(repo, &remote, &base)
3817 .with_context(|| missing_tracking_ref_msg(&remote, &base))?;
3818 (Some(common_dir), base, sha)
3819 }
3820 (None, None) => {
3821 let (base, sha) = resolve_remote_head_and_commit_cli(repo, &remote)?;
3822 (None, base, sha)
3823 }
3824 };
3825 materialize_remote_layers(repo, common_dir, &remote, &base, &sha, true)
3826}
3827
3828fn materialize_remote_layers(
3829 repo: &Path,
3830 common_dir: Option<PathBuf>,
3831 remote: &str,
3832 base: &str,
3833 sha: &str,
3834 verified: bool,
3835) -> Result<Vec<PathBuf>> {
3836 let repo_key = repo.to_string_lossy();
3837 let key_for = |commit_sha: &str| {
3838 format!(
3839 "{commit_sha}-{}-v{CACHE_MANIFEST_VERSION}",
3840 fnv_hex(&repo_key)
3841 )
3842 };
3843 let primary_root = common_dir.map(|c| c.join("magi").join("config"));
3844 let fallback_root = dirs::cache_dir().map(|p| p.join("magi").join("config"));
3845 let lookup = |commit_sha: &str| -> Option<Vec<PathBuf>> {
3846 let key = key_for(commit_sha);
3847 if let Some(root) = &primary_root
3848 && let Some(layers) = read_cached_layers(&root.join(&key), commit_sha, repo)
3849 {
3850 return Some(layers);
3851 }
3852 read_cached_layers(&fallback_root.as_ref()?.join(&key), commit_sha, repo)
3853 };
3854 if let Some(layers) = lookup(sha) {
3855 if !verified {
3856 let commit = git_out(
3860 repo,
3861 &[
3862 "rev-parse",
3863 "--verify",
3864 "--quiet",
3865 &format!("{sha}^{{commit}}"),
3866 ],
3867 );
3868 if !commit.is_some_and(|s| s.trim() == sha) {
3869 bail!("{}", missing_tracking_ref_msg(remote, base));
3870 }
3871 }
3872 return Ok(layers);
3873 }
3874
3875 let (commit_sha, texts) = read_commit_layers_batch(repo, sha, remote, base)?;
3876 if commit_sha != sha
3877 && let Some(layers) = lookup(&commit_sha)
3878 {
3879 return Ok(layers);
3880 }
3881
3882 let key = key_for(&commit_sha);
3883 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
3884 let build = |root: &Path| -> Result<Vec<PathBuf>> {
3888 let final_dir = root.join(&key);
3889 if let Some(layers) = read_cached_layers(&final_dir, &commit_sha, repo) {
3890 return Ok(layers);
3891 }
3892 static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3893 let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3894 std::fs::create_dir_all(root)?;
3895 let tmp = root.join(format!(
3896 "{key}.tmp-{}-{}-{seq}",
3897 std::process::id(),
3898 std::time::SystemTime::now()
3899 .duration_since(std::time::UNIX_EPOCH)
3900 .map(|d| d.as_nanos())
3901 .unwrap_or_default()
3902 ));
3903 let filled = (|| -> Result<()> {
3904 std::fs::create_dir_all(&tmp)?;
3905 if wants_tree {
3906 extract_tree(repo, &commit_sha, &tmp)?;
3907 }
3908 for (rel, text) in &texts {
3909 let file = join_rel_path(&tmp, rel);
3910 let parent = file.parent().unwrap_or(&tmp);
3911 std::fs::create_dir_all(parent)?;
3912 write_extracted(&file, text)?;
3913 write_extracted(&parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
3914 }
3915 let manifest = CacheManifest {
3916 version: CACHE_MANIFEST_VERSION,
3917 sha: commit_sha.clone(),
3918 repo: repo.to_string_lossy().into_owned(),
3919 layers: texts.iter().map(|(rel, _)| (*rel).to_owned()).collect(),
3920 extracted_tree: wants_tree,
3921 };
3922 write_extracted(
3923 &tmp.join(CACHE_MANIFEST),
3924 serde_json::to_vec(&manifest).context("serialize config cache manifest")?,
3925 )?;
3926 Ok(())
3927 })();
3928 if let Err(e) = filled {
3929 let _ = std::fs::remove_dir_all(&tmp);
3930 return Err(e);
3931 }
3932 if std::fs::rename(&tmp, &final_dir).is_err() {
3933 let _ = std::fs::remove_dir_all(&tmp);
3938 return read_cached_layers(&final_dir, &commit_sha, repo)
3939 .with_context(|| format!("cannot place {}", final_dir.display()));
3940 }
3941 Ok(texts
3942 .iter()
3943 .map(|(rel, _)| join_rel_path(&final_dir, rel))
3944 .collect())
3945 };
3946 let layers = match primary_root.as_deref().map(&build) {
3947 Some(Ok(layers)) => layers,
3948 _ => {
3949 let root = fallback_root
3950 .as_deref()
3951 .context("no user config cache directory")?;
3952 build(root).with_context(|| format!("extracting config from {remote}/{base}"))?
3953 }
3954 };
3955 Ok(layers)
3956}
3957
3958#[cfg(test)]
3959mod tests {
3960 #[test]
3961 fn standing_authorization_is_only_from_the_named_machine_layer() {
3962 let dir = tempfile::tempdir().unwrap();
3963 let machine = dir.path().join("machine.toml");
3964 let repo = dir.path().join("magi.toml");
3965 std::fs::write(&machine, "[talk]\nstanding_authorization = false\n").unwrap();
3966 std::fs::write(&repo, "[talk]\nstanding_authorization = true\n").unwrap();
3967 let layers = [machine.clone(), repo.clone()];
3968 let load = |paths| Config::load_layers_with_machine(paths, Some(machine.clone())).unwrap();
3969 assert!(!load(&layers).talk.standing_authorization);
3970 assert!(
3971 !load(std::slice::from_ref(&repo))
3972 .talk
3973 .standing_authorization
3974 );
3975 std::fs::write(&machine, "[talk]\nstanding_authorization = true\n").unwrap();
3976 std::fs::write(&repo, "[talk]\nstanding_authorization = false\n").unwrap();
3977 assert!(load(&layers).talk.standing_authorization);
3978 }
3979
3980 #[test]
3981 fn run_records_with_the_retired_editing_network_key_still_load() {
3982 for value in ["enabled", "restricted"] {
3984 let mut graph = serde_json::to_value(Graph::default()).unwrap();
3985 graph["editing_network"] = serde_json::json!(value);
3986 let back: Graph = serde_json::from_value(graph).unwrap();
3987 assert!(
3988 serde_json::to_value(&back)
3989 .unwrap()
3990 .get("editing_network")
3991 .is_none()
3992 );
3993 let from_toml: Graph = toml::from_str(&format!("editing_network = {value:?}")).unwrap();
3994 assert!(
3995 !toml::to_string(&from_toml)
3996 .unwrap()
3997 .contains("editing_network")
3998 );
3999 }
4000 }
4001
4002 #[test]
4003 fn coordination_defaults_off_and_validates_rendered_layer_values() {
4004 let dir = tempfile::tempdir().unwrap();
4005 let machine = dir.path().join("machine.toml");
4006 let repo = dir.path().join("repo.toml");
4007 std::fs::write(&machine, "").unwrap();
4008 assert!(Config::default().coordination.is_none());
4009 assert!(Config::load(&machine).unwrap().coordination.is_none());
4010 std::fs::write(
4011 &machine,
4012 r#"
4013[vars]
4014contract = "updater.contract"
4015[coordination]
4016contract_file = "{{ vars.contract }}"
4017contract_token = "protocol-v1"
4018lock_file = "updater.lock"
4019"#,
4020 )
4021 .unwrap();
4022 let cfg = Config::load(&machine).unwrap();
4023 let policy = cfg.coordination.unwrap();
4024 assert_eq!(policy.contract_file, "updater.contract");
4025 assert_eq!(policy.contract_token, "protocol-v1");
4026 assert_eq!(policy.lock_file, "updater.lock");
4027 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
4028 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
4029 let policy = cfg.coordination.unwrap();
4030 assert_eq!(policy.contract_file, "updater.contract");
4031 assert_eq!(policy.lock_file, "repository.lock");
4032 std::fs::write(
4033 &repo,
4034 r#"
4035[vars]
4036bad = "../escape"
4037[coordination]
4038lock_file = "{{ vars.bad }}"
4039"#,
4040 )
4041 .unwrap();
4042 let error = Config::load_layers(&[machine, repo]).unwrap_err();
4043 assert!(format!("{error:#}").contains("coordination.lock_file"));
4044 }
4045
4046 #[test]
4047 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
4048 let dir = tempfile::tempdir().unwrap();
4049 let path = dir.path().join("config.toml");
4050 let valid = toml::toml! {
4051 [coordination]
4052 contract_file = "updater.contract"
4053 contract_token = "protocol-v1"
4054 lock_file = "updater.lock"
4055 };
4056 for key in ["contract_file", "lock_file"] {
4057 for bad in [
4058 "",
4059 " ",
4060 " file",
4061 "file ",
4062 "\tfile",
4063 "file\t",
4064 ".",
4065 "..",
4066 "file..name",
4067 "../escape",
4068 "a/b",
4069 "a\\b",
4070 "/absolute",
4071 "C:drive",
4072 "C:\\absolute",
4073 "nul\0name",
4074 ] {
4075 let mut table = valid.clone();
4076 table["coordination"][key] = bad.into();
4077 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4078 let error = Config::load(&path).unwrap_err();
4079 assert!(
4080 format!("{error:#}").contains(&format!("coordination.{key}")),
4081 "{bad:?}: {error:#}"
4082 );
4083 }
4084 }
4085 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
4086 let mut table = valid.clone();
4087 table["coordination"]["contract_token"] = bad.into();
4088 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4089 let error = Config::load(&path).unwrap_err();
4090 assert!(
4091 format!("{error:#}").contains("coordination.contract_token"),
4092 "{error:#}"
4093 );
4094 }
4095 for key in ["contract_file", "contract_token", "lock_file"] {
4096 let mut table = valid.clone();
4097 table["coordination"].as_table_mut().unwrap().remove(key);
4098 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4099 let error = Config::load(&path).unwrap_err();
4100 assert!(
4101 format!("{error:#}").contains(&format!("coordination.{key}")),
4102 "{error:#}"
4103 );
4104 }
4105 let mut table = valid;
4106 table["coordination"]
4107 .as_table_mut()
4108 .unwrap()
4109 .insert("typo".into(), "value".into());
4110 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4111 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
4112 }
4113
4114 #[test]
4115 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
4116 let mut cfg = Config::default();
4117 assert_eq!(
4118 cfg.context_window("claude-sonnet-4-5-20250929"),
4119 Some(200_000)
4120 );
4121 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
4122 assert_eq!(cfg.context_window("mystery-model"), None);
4123 cfg.context_windows
4124 .insert("claude-sonnet-4-5".into(), 1_000_000);
4125 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
4126 cfg.context_windows.insert("mystery".into(), 32_768);
4127 assert_eq!(
4129 cfg.context_window("claude-sonnet-4-5-20250929"),
4130 Some(1_000_000)
4131 );
4132 cfg.context_windows
4134 .insert("claude-sonnet-4-5-20250929".into(), 7);
4135 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
4136 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
4137 }
4138
4139 use super::*;
4140
4141 #[test]
4144 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
4145 let dir = tempfile::tempdir().unwrap();
4146 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
4147 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
4148 let paths = dir.path().as_os_str();
4149 assert_eq!(
4150 find_program_in("codex", paths, Some(".EXE;.CMD")),
4151 Some(dir.path().join("codex.cmd"))
4152 );
4153 assert_eq!(
4154 find_program_in("codex", paths, None),
4155 Some(dir.path().join("codex"))
4156 );
4157 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
4158 }
4159
4160 fn spec(id: &str) -> AgentSpec {
4161 AgentSpec {
4162 id: id.to_owned(),
4163 kind: AgentKind::Command,
4164 model: None,
4165 command: vec!["true".to_owned()],
4166 extra_args: Vec::new(),
4167 env: BTreeMap::new(),
4168 prompt_delivery: None,
4169 max_turn_secs: None,
4170 }
4171 }
4172
4173 #[test]
4174 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
4175 let default: Merge = toml::from_str("").unwrap();
4176 assert_eq!(default.ci, MergeCi::Expected);
4177 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
4178 assert_eq!(
4179 config.merge.ci.expectation(),
4180 crate::land::CiExpectation::Absent
4181 );
4182 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
4183 assert!(Config::starter_toml().contains("# ci = \"expected\""));
4184 }
4185
4186 #[test]
4187 fn github_text_guard_defaults_on_and_can_be_disabled() {
4188 let default: Graph = toml::from_str("").unwrap();
4189 assert!(default.github_text_guard);
4190 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
4191 assert!(!disabled.github_text_guard);
4192 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
4193 assert!(!config.graph.github_text_guard);
4194 assert!(Config::starter_toml().contains("github_text_guard = true"));
4195 }
4196
4197 #[test]
4198 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
4199 assert!(Graph::default().rerun_flaky_checks);
4200 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
4201 assert!(!off.rerun_flaky_checks);
4202 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
4203 }
4204
4205 #[test]
4206 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
4207 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
4212 assert_eq!(g.timeout_verify, None);
4213 assert_eq!(g.verify_timeout(), 3600);
4214 }
4215
4216 #[test]
4217 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
4218 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
4223 assert_eq!(g.timeout_review, 45);
4224 assert_eq!(
4225 g.verify_timeout(),
4226 45,
4227 "an omitted legacy value follows review"
4228 );
4229 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
4230 .expect("parse explicit override");
4231 assert_eq!(explicit.verify_timeout(), 1200);
4232 }
4233
4234 #[test]
4235 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
4236 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
4237 assert_eq!(g.implementers, 4);
4238 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
4239 assert_eq!(g.implementers, 5);
4240 }
4241
4242 fn layered(lower: &str, upper: &str) -> Result<Config> {
4243 let dir = tempfile::tempdir().unwrap();
4244 let a = dir.path().join("a.toml");
4245 let b = dir.path().join("b.toml");
4246 std::fs::write(&a, lower).unwrap();
4247 std::fs::write(&b, upper).unwrap();
4248 Config::load_layers(&[a, b])
4249 }
4250
4251 #[test]
4252 fn graph_implementers_higher_layer_wins_across_spellings() {
4253 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
4254 assert_eq!(c.graph.implementers, 5);
4255 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
4256 assert_eq!(c.graph.implementers, 5);
4257 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
4258 assert_eq!(c.graph.implementers, 2);
4259 }
4260
4261 #[test]
4262 fn graph_implementers_both_keys_in_one_layer_is_refused() {
4263 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
4264 .unwrap_err()
4265 .to_string();
4266 assert!(
4267 err.contains("candidates") && err.contains("implementers"),
4268 "{err}"
4269 );
4270 assert!(err.contains("b.toml"), "{err}");
4271 }
4272
4273 #[test]
4274 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
4275 let g: Graph =
4279 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
4280 .expect("an old-shaped [graph] table must still parse");
4281 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
4282 assert!(
4283 !g.e2e_every_round,
4284 "off by default, same as before this field existed"
4285 );
4286 }
4287
4288 #[test]
4289 fn empty_roles_rotate_judges_off_their_own_candidate() {
4290 let cfg = Config {
4293 agents: vec![spec("a"), spec("b"), spec("c")],
4294 graph: Graph {
4295 implementers: 3,
4296 ..Graph::default()
4297 },
4298 ..Config::default()
4299 };
4300 let roles = cfg.resolve_roles().unwrap();
4301 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
4302 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
4303 assert_eq!(impls, ["a", "b", "c"]);
4304 assert_eq!(judges, ["b", "c", "a"]);
4305 for (i, j) in judges.iter().enumerate() {
4306 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
4307 }
4308 }
4309
4310 #[test]
4311 fn single_agent_roster_fills_every_seat() {
4312 let cfg = Config {
4313 agents: vec![spec("solo")],
4314 graph: Graph {
4315 implementers: 3,
4316 ..Graph::default()
4317 },
4318 ..Config::default()
4319 };
4320 let roles = cfg.resolve_roles().unwrap();
4321 assert_eq!(roles.implementers.len(), 3);
4322 assert!(roles.judges.iter().all(|a| a.id == "solo"));
4323 }
4324
4325 #[test]
4326 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
4327 let cfg = Config {
4332 agents: vec![spec("a"), spec("b"), spec("c")],
4333 graph: Graph {
4334 implementers: 1,
4335 ..Graph::default()
4336 },
4337 ..Config::default()
4338 };
4339 let roles = cfg.resolve_roles().unwrap();
4340 assert_eq!(roles.implementers.len(), 1);
4341 let roster: Vec<&str> = roles
4342 .implementer_roster
4343 .iter()
4344 .map(|a| a.id.as_str())
4345 .collect();
4346 assert_eq!(roster, ["a", "b", "c"]);
4347 }
4348
4349 #[test]
4350 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
4351 let cfg = Config {
4352 agents: vec![spec("a"), spec("b"), spec("c")],
4353 roles: Roles {
4354 implementers: vec!["c".to_owned(), "a".to_owned()],
4355 ..Roles::default()
4356 },
4357 graph: Graph {
4358 implementers: 1,
4359 ..Graph::default()
4360 },
4361 ..Config::default()
4362 };
4363 let roles = cfg.resolve_roles().unwrap();
4364 assert_eq!(roles.implementers.len(), 1);
4366 assert_eq!(roles.implementers[0].id, "c");
4367 let roster: Vec<&str> = roles
4368 .implementer_roster
4369 .iter()
4370 .map(|a| a.id.as_str())
4371 .collect();
4372 assert_eq!(roster, ["c", "a"]);
4373 }
4374
4375 #[test]
4376 fn explicit_roles_win() {
4377 let cfg = Config {
4378 agents: vec![spec("a"), spec("b")],
4379 roles: Roles {
4380 implementers: vec!["b".to_owned()],
4381 judges: vec!["a".to_owned()],
4382 reviewers: Vec::new(),
4383 fixer: Some("a".into()),
4384 ..Roles::default()
4385 },
4386 ..Config::default()
4387 };
4388 let roles = cfg.resolve_roles().unwrap();
4389 assert!(roles.implementers.iter().all(|a| a.id == "b"));
4390 assert!(roles.judges.iter().all(|a| a.id == "a"));
4391 let fixer = roles.fixer.unwrap();
4392 assert_eq!(fixer.len(), 1);
4393 assert_eq!(fixer[0].id, "a");
4394 assert_eq!(roles.conductor.id, "a");
4395 }
4396
4397 #[test]
4398 fn fixer_takes_a_string_or_an_ordered_chain() {
4399 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
4400 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
4401 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
4402 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
4403
4404 let resolve = |fixer: Option<AgentChoice>| {
4405 Config {
4406 agents: vec![spec("a"), spec("b"), spec("c")],
4407 roles: Roles {
4408 fixer,
4409 ..Roles::default()
4410 },
4411 ..Config::default()
4412 }
4413 .resolve_roles()
4414 };
4415 let ids = |r: &ResolvedRoles| -> Vec<String> {
4416 r.fixer
4417 .as_ref()
4418 .unwrap()
4419 .iter()
4420 .map(|s| s.id.clone())
4421 .collect()
4422 };
4423 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
4425 assert!(resolve(None).unwrap().fixer.is_none());
4426 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
4428 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
4429 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
4431 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
4432 }
4433
4434 #[test]
4435 fn unknown_agent_id_is_an_error() {
4436 let cfg = Config {
4437 agents: vec![spec("a")],
4438 roles: Roles {
4439 judges: vec!["nope".to_owned()],
4440 ..Roles::default()
4441 },
4442 ..Config::default()
4443 };
4444 assert!(cfg.resolve_roles().is_err());
4445 }
4446
4447 #[test]
4448 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
4449 let mut cfg = Config {
4450 agents: vec![spec("a"), spec("b")],
4451 ..Config::default()
4452 };
4453 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
4454
4455 cfg.roles.conductor = Some("b".into());
4456 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
4457
4458 cfg.roles.conductor = Some("missing".into());
4459 assert!(cfg.resolve_roles().is_err());
4460 }
4461
4462 #[test]
4463 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
4464 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
4465 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
4466 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
4467
4468 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
4469 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
4470 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
4471
4472 for roles in [one, chain] {
4473 let text = toml::to_string(&roles).unwrap();
4474 let back: Roles = toml::from_str(&text).unwrap();
4475 assert_eq!(back.synthesizer, roles.synthesizer);
4476 assert_eq!(back.chatter, roles.chatter);
4477 }
4478 let text = toml::to_string(&Roles {
4479 conductor: Some("x".into()),
4480 ..Roles::default()
4481 })
4482 .unwrap();
4483 assert!(
4484 text.contains("conductor = \"x\""),
4485 "string stays a string: {text}"
4486 );
4487 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
4488 }
4489
4490 #[test]
4491 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
4492 for (text, ids) in [
4493 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
4494 (
4495 r#"dupes_judge = ["first", "second"]"#,
4496 vec!["first", "second"],
4497 ),
4498 ("dupes_judge = []", vec![]),
4499 ] {
4500 let roles: Roles = toml::from_str(text).unwrap();
4501 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
4502 let serialized = toml::to_string(&roles).unwrap();
4503 let back: Roles = toml::from_str(&serialized).unwrap();
4504 assert_eq!(back.dupes_judge, roles.dupes_judge);
4505 assert!(serialized.contains(text));
4506 }
4507 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
4508 assert!(Roles::default().dupes_judge.is_none());
4509 assert!(Config::starter_toml().contains("# dupes_judge ="));
4510
4511 let mut cfg = Config {
4513 agents: vec![spec("a")],
4514 ..Config::default()
4515 };
4516 cfg.roles.dupes_judge = Some("missing".into());
4517 assert!(cfg.resolve_roles().is_ok());
4518 }
4519
4520 #[test]
4521 fn an_empty_choice_counts_as_unset() {
4522 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
4523 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
4524 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
4525 }
4526
4527 #[test]
4528 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
4529 let mut cfg = Config {
4535 agents: vec![spec("a"), spec("b")],
4536 ..Config::default()
4537 };
4538 let want = primary(cfg.roles.synthesizer.as_ref());
4539 assert_eq!(
4540 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
4541 .unwrap()
4542 .id,
4543 "a",
4544 "unset falls back to agent::pick's own default order"
4545 );
4546
4547 cfg.roles.synthesizer = Some("b".into());
4548 let want = primary(cfg.roles.synthesizer.as_ref());
4549 assert_eq!(
4550 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
4551 .unwrap()
4552 .id,
4553 "b",
4554 "the named agent wins over the default order"
4555 );
4556 }
4557
4558 #[test]
4559 fn empty_roster_is_an_error() {
4560 assert!(Config::default().resolve_roles().is_err());
4561 }
4562
4563 #[test]
4564 fn advise_defaults_to_on_with_three_proposals() {
4565 let g = Graph::default();
4566 assert!(g.advise);
4567 assert!(g.graft_runner_up, "graft is on by default");
4568 assert_eq!(g.advisors, 3);
4569 }
4570
4571 #[test]
4572 fn unset_advisors_falls_back_to_the_judge_roster() {
4573 let cfg = Config {
4574 agents: vec![spec("a"), spec("b")],
4575 roles: Roles {
4576 judges: vec!["b".to_owned()],
4577 ..Roles::default()
4578 },
4579 graph: Graph {
4580 advisors: 2,
4581 ..Graph::default()
4582 },
4583 ..Config::default()
4584 };
4585 let advisors = cfg.advisors().expect("advisors resolve");
4586 assert_eq!(advisors.len(), 2);
4587 assert!(
4588 advisors.iter().all(|a| a.id == "b"),
4589 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
4590 );
4591 }
4592
4593 #[test]
4594 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
4595 let cfg = Config {
4596 agents: vec![spec("a"), spec("b")],
4597 roles: Roles {
4598 judges: vec!["b".to_owned()],
4599 advisors: vec!["a".to_owned()],
4600 ..Roles::default()
4601 },
4602 graph: Graph {
4603 advisors: 2,
4604 ..Graph::default()
4605 },
4606 ..Config::default()
4607 };
4608 let advisors = cfg.advisors().expect("advisors resolve");
4609 assert!(advisors.iter().all(|a| a.id == "a"));
4610 }
4611
4612 #[test]
4618 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
4619 let cfg = Config {
4620 agents: vec![spec("a"), spec("b"), spec("c")],
4621 graph: Graph {
4622 advisors: 3,
4623 judges: 3,
4624 ..Graph::default()
4625 },
4626 ..Config::default()
4627 };
4628 let advisors = cfg.advisors().expect("advisors resolve");
4629 let judges = cfg.resolve_roles().expect("roles resolve").judges;
4630 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
4631 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
4632 assert_eq!(
4633 advisor_ids, judge_ids,
4634 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
4635 );
4636 }
4637
4638 #[test]
4639 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
4640 let cfg = Config {
4641 agents: vec![spec("a")],
4642 roles: Roles {
4643 advisors: vec!["nope".to_owned()],
4644 ..Roles::default()
4645 },
4646 graph: Graph {
4647 advisors: 1,
4648 ..Graph::default()
4649 },
4650 ..Config::default()
4651 };
4652 let err = cfg.advisors().expect_err("`nope` is not in the roster");
4653 assert!(format!("{err:#}").contains("nope"));
4654 }
4655
4656 #[test]
4657 fn repos_default_to_no_roots_and_a_day_of_trust() {
4658 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
4659 assert_eq!(Config::default().repos.scan_ttl, 86_400);
4660 assert_eq!(Config::default().repos.fetch_interval, 600);
4661 assert!(!Config::default().repos.auto_clone);
4662 assert!(Config::default().repos.clone_command.is_none());
4663 }
4664
4665 #[test]
4666 fn a_config_file_with_no_repos_table_still_loads() {
4667 let dir = tempfile::tempdir().unwrap();
4668 let path = dir.path().join("magi.toml");
4669 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4670 let cfg = Config::load(&path).expect("must load without [repos]");
4671 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
4672 assert_eq!(cfg.repos.scan_ttl, 86_400);
4673 }
4674
4675 #[test]
4690 fn a_test_build_does_not_read_the_operators_machine_config() {
4691 let repo = tempfile::tempdir().unwrap();
4692 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4693
4694 let layers = Config::layers(repo.path());
4695 assert_eq!(
4696 layers,
4697 vec![repo.path().join("magi.toml")],
4698 "only the fixture's own file may be a layer"
4699 );
4700 if let Some(real) = dirs::config_dir() {
4701 let machine = real.join("magi").join("config.toml");
4702 assert!(
4703 !layers.contains(&machine),
4704 "the operator's {} must not be a layer in a test build",
4705 machine.display()
4706 );
4707 }
4708 }
4709
4710 #[test]
4711 fn auto_upgrade_config_defaults_and_opt_in() {
4712 let default: Update = toml::from_str("").unwrap();
4713 assert!(!default.auto_restart);
4714 assert_eq!(default.mode, UpdateMode::Notify);
4715 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
4716 assert!(enabled.auto_restart);
4717 assert_eq!(enabled.interval.as_deref(), Some("2h"));
4718 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
4719 }
4720
4721 #[test]
4722 fn starter_toml_loads_through_teravars() {
4723 let dir = tempfile::tempdir().unwrap();
4724 let path = dir.path().join("magi.toml");
4725 std::fs::write(&path, Config::starter_toml()).unwrap();
4726 let parsed = Config::load(&path).expect("starter config must load");
4727 assert_eq!(parsed.graph.implementers, 3);
4728 assert_eq!(parsed.merge.mode, MergeMode::None);
4729 assert_eq!(parsed.merge.style, MergeStyle::Merge);
4730 assert!(parsed.graph.sessions);
4731 assert!(parsed.graph.github_text_guard);
4732 assert_eq!(parsed.graph.timeout_review, 1200);
4733 assert_eq!(parsed.graph.verify_timeout(), 1200);
4734 assert_eq!(parsed.update.mode, UpdateMode::Notify);
4735 }
4736
4737 #[test]
4738 fn release_defaults_to_actions_and_the_starter_documents_it() {
4739 let dir = tempfile::tempdir().unwrap();
4740 let path = dir.path().join("magi.toml");
4741 std::fs::write(&path, Config::starter_toml()).unwrap();
4742 let r = Config::load(&path).unwrap().release;
4743 assert_eq!(r.mode, ReleaseMode::Actions);
4744 assert!(!r.is_local());
4745 assert!(r.commands.is_empty());
4746 assert_eq!(r.timeout_minutes, 30);
4747 assert!(Config::starter_toml().contains("# mode = \"actions\""));
4748 }
4749
4750 #[test]
4751 fn release_local_parses_and_unknown_keys_are_refused() {
4752 let dir = tempfile::tempdir().unwrap();
4753 let path = dir.path().join("magi.toml");
4754 std::fs::write(
4755 &path,
4756 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
4757 )
4758 .unwrap();
4759 let r = Config::load(&path).unwrap().release;
4760 assert!(r.is_local());
4761 assert_eq!(r.commands.len(), 2);
4762 assert_eq!(r.timeout_minutes, 5);
4763 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
4764 assert!(Config::load(&path).is_err());
4765 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
4766 assert!(Config::load(&path).is_err());
4767 }
4768
4769 #[test]
4770 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
4771 let dir = tempfile::tempdir().unwrap();
4772 let path = dir.path().join("magi.toml");
4773 std::fs::write(&path, Config::starter_toml()).unwrap();
4774 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
4775 assert!(Config::starter_toml().contains("# pre_gate = []"));
4776 }
4777
4778 #[test]
4779 fn release_version_files_parse_default_empty_and_are_validated() {
4780 let dir = tempfile::tempdir().unwrap();
4781 let path = dir.path().join("magi.toml");
4782 std::fs::write(&path, "").unwrap();
4783 assert!(
4784 Config::load(&path)
4785 .unwrap()
4786 .release
4787 .version_files
4788 .is_empty()
4789 );
4790 std::fs::write(
4791 &path,
4792 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
4793 )
4794 .unwrap();
4795 let files = Config::load(&path).unwrap().release.version_files;
4796 assert_eq!(files.len(), 2);
4797 assert_eq!(files[1].kind, VersionKind::Json);
4798 for bad in [
4799 "{ path = \"package.json\", kind = \"json\" }",
4800 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
4801 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
4802 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
4803 ] {
4804 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
4805 assert!(Config::load(&path).is_err(), "{bad}");
4806 }
4807 assert!(Config::starter_toml().contains("# version_files = ["));
4808 }
4809
4810 #[test]
4811 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
4812 let starter = Config::starter_toml();
4813 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
4814 assert!(starter.contains("verification independent if timeout_review changes later"));
4815 assert!(starter.contains("# timeout_verify = 1200"));
4816 }
4817
4818 #[test]
4819 fn starter_toml_documents_chat_personas() {
4820 let starter = Config::starter_toml();
4821 assert!(starter.contains("# [[talk.personas]]"));
4822 assert!(starter.contains("tone only"));
4823 }
4824
4825 #[test]
4826 fn talk_personas_parse_and_are_validated() {
4827 let dir = tempfile::tempdir().unwrap();
4828 let path = dir.path().join("magi.toml");
4829 std::fs::write(
4830 &path,
4831 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
4832 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
4833 )
4834 .unwrap();
4835 let cfg = Config::load(&path).expect("loads");
4836 assert_eq!(cfg.talk.personas.len(), 2);
4837 let catalog = crate::persona::catalog(&cfg.talk.personas);
4838 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
4839 assert_eq!(
4840 (rei.name.as_str(), rei.prompt.as_str()),
4841 ("Quiet", "Be brief.")
4842 );
4843 assert_eq!(catalog.last().unwrap().id, "gendo");
4844
4845 for (body, needle) in [
4846 (
4847 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
4848 "empty `id`",
4849 ),
4850 (
4851 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
4852 "empty `prompt`",
4853 ),
4854 (
4855 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
4856 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
4857 "more than once",
4858 ),
4859 (
4860 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
4861 "cannot be redefined",
4862 ),
4863 ] {
4864 std::fs::write(&path, body).unwrap();
4865 let err = format!("{:#}", Config::load(&path).unwrap_err());
4866 assert!(err.contains(needle), "{needle}: {err}");
4867 }
4868 }
4869
4870 #[test]
4871 fn talk_operator_name_is_trimmed_and_validated() {
4872 let dir = tempfile::tempdir().unwrap();
4873 let path = dir.path().join("magi.toml");
4874 let load = |body: &str| {
4875 std::fs::write(&path, body).unwrap();
4876 Config::load(&path)
4877 };
4878 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
4879 assert_eq!(ok.talk.operator_name(), Some("Commander"));
4880 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
4881 assert_eq!(blank.talk.operator_name(), None);
4882 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
4883 let long = "x".repeat(65);
4884 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
4885 }
4886
4887 #[test]
4888 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
4889 let dir = tempfile::tempdir().unwrap();
4890 let load = |body: &str| {
4891 let path = dir.path().join("c.toml");
4892 std::fs::write(&path, body).unwrap();
4893 Config::load(&path)
4894 };
4895 let ok = load(
4896 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
4897 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
4898 )
4899 .unwrap();
4900 let c = crate::persona::catalog(&ok.talk.personas);
4901 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
4902 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
4903 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
4904 let oversized = format!(
4905 "data:image/png;base64,{}",
4906 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
4907 );
4908 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
4909 for (id, fields) in [
4910 ("rei", ""),
4911 ("default", ""),
4912 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
4913 ] {
4914 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
4915 let cfg = load(&body).expect("bad icon must not invalidate config");
4916 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
4917 assert_eq!(persona.id, id);
4918 assert!(crate::persona_icon::load(bad).is_err());
4919 }
4920 }
4921 let doc = Config::starter_toml();
4922 assert!(doc.contains("# icon = "));
4923 }
4924
4925 #[test]
4926 fn talk_personas_in_two_layers_are_refused() {
4927 let dir = tempfile::tempdir().unwrap();
4928 let machine = dir.path().join("machine.toml");
4929 let repo = dir.path().join("repo.toml");
4930 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
4931 std::fs::write(&machine, one).unwrap();
4932 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
4933 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
4934 assert!(err.contains("talk.personas"), "{err}");
4935 }
4936
4937 #[test]
4938 fn starter_toml_documents_role_lists_as_backup_order() {
4939 let starter = Config::starter_toml();
4940 assert!(starter.contains("also an ordered backup list"));
4941 assert!(starter.contains("codex then sonnet are spares"));
4942 }
4943
4944 #[test]
4948 fn a_repository_can_declare_a_linear_history_merge_style() {
4949 let dir = tempfile::tempdir().unwrap();
4950 let path = dir.path().join("magi.toml");
4951 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
4952 let parsed = Config::load(&path).expect("config must load");
4953 assert_eq!(parsed.merge.style, MergeStyle::Squash);
4954 }
4955
4956 #[test]
4957 fn later_layers_win_and_vars_render() {
4958 let dir = tempfile::tempdir().unwrap();
4959 let machine = dir.path().join("machine.toml");
4960 let project = dir.path().join("magi.toml");
4961 std::fs::write(
4963 &machine,
4964 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
4965 [graph]\ncandidates = 3\nmax_parallel = 8\n[verify]\nbuild_cache = \"shared\"\n",
4966 )
4967 .unwrap();
4968 std::fs::write(
4971 &project,
4972 "[vars]\ncache = \"/shared\"\n\n\
4973 [graph]\ncandidates = 2\n\n\
4974 [verify]\nbuild_cache = \"isolated\"\n\
4975 gate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
4976 )
4977 .unwrap();
4978
4979 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
4980 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
4981 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
4982 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
4983 assert_eq!(cfg.verify.build_cache, BuildCache::Isolated);
4984 assert_eq!(
4985 cfg.verify.gate,
4986 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
4987 );
4988 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
4990 }
4991
4992 #[test]
4993 fn saved_config_without_a_build_cache_policy_remains_shared() {
4994 let saved: Config = serde_json::from_str(r#"{"verify":{"gate":["cargo test"]}}"#).unwrap();
4995 assert_eq!(saved.verify.build_cache, BuildCache::Shared);
4996 }
4997
4998 #[test]
4999 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
5000 let g = Graph::default();
5004 assert_eq!(g.timeout_talk, 3600);
5005
5006 let dir = tempfile::tempdir().unwrap();
5007 let path = dir.path().join("magi.toml");
5008 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
5009 let cfg = Config::load(&path).expect("must load without timeout_talk set");
5010 assert_eq!(cfg.graph.timeout_talk, 3600);
5011 }
5012
5013 #[test]
5014 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
5015 let dir = tempfile::tempdir().unwrap();
5016 let path = dir.path().join("magi.toml");
5017 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
5018 let cfg = Config::load(&path).expect("must load");
5019 assert_eq!(cfg.graph.timeout_talk, 120);
5020 }
5021
5022 #[test]
5023 fn the_disk_defaults_are_the_measurements_made_up_front() {
5024 let cfg = Config::default();
5025 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
5026 assert!(cfg.disk.auto_fold);
5027 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
5028 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
5029 }
5030
5031 #[test]
5032 fn an_unset_disk_section_is_the_safe_default() {
5033 let dir = tempfile::tempdir().unwrap();
5034 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
5035 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
5036 assert_eq!(cfg.disk, Disk::default());
5037 }
5038
5039 #[test]
5040 fn the_reclaim_threshold_defaults_to_twice_the_floor_and_never_undercuts_it() {
5041 let disk = |min: u64, own: Option<u64>| Disk {
5042 min_free_bytes: min,
5043 reclaim_free_bytes: own,
5044 ..Disk::default()
5045 };
5046 assert_eq!(disk(8, None).reclaim_threshold(), 16);
5047 assert_eq!(Disk::default().reclaim_threshold(), 16 * 1024 * 1024 * 1024);
5048 assert_eq!(disk(8, Some(30)).reclaim_threshold(), 30);
5049 assert_eq!(
5050 disk(8, Some(3)).reclaim_threshold(),
5051 8,
5052 "never below the floor"
5053 );
5054 assert_eq!(disk(8, Some(0)).reclaim_threshold(), 8);
5055 assert_eq!(disk(8, Some(8)).reclaim_threshold(), 8);
5056 assert_eq!(
5057 disk(0, None).reclaim_threshold(),
5058 0,
5059 "gate off: no collection"
5060 );
5061 assert_eq!(
5062 disk(0, Some(0)).reclaim_threshold(),
5063 0,
5064 "explicit 0 resolves like unset: the resolved value decides"
5065 );
5066 assert_eq!(
5067 disk(0, Some(5)).reclaim_threshold(),
5068 5,
5069 "explicit still collects"
5070 );
5071 assert_eq!(disk(u64::MAX, None).reclaim_threshold(), u64::MAX);
5072 }
5073
5074 #[test]
5075 fn reclaim_free_bytes_loads_from_toml_and_older_configs_get_the_default() {
5076 let dir = tempfile::tempdir().unwrap();
5077 let path = dir.path().join("magi.toml");
5078 std::fs::write(&path, "[disk]\nmin_free_bytes = 100\n").unwrap();
5079 let cfg = Config::load(&path).expect("older config loads");
5080 assert_eq!(cfg.disk.reclaim_free_bytes, None);
5081 assert_eq!(cfg.disk.reclaim_threshold(), 200);
5082
5083 std::fs::write(
5084 &path,
5085 "[disk]\nmin_free_bytes = 100\nreclaim_free_bytes = 450\n",
5086 )
5087 .unwrap();
5088 let cfg = Config::load(&path).expect("explicit value loads");
5089 assert_eq!(cfg.disk.reclaim_threshold(), 450);
5090 }
5091
5092 #[test]
5093 fn a_saved_run_config_without_the_field_deserializes_to_the_default() {
5094 let disk = serde_json::to_value(Disk::default()).unwrap();
5097 assert!(disk.get("reclaim_free_bytes").is_none());
5098 let older: Disk = serde_json::from_value(disk).unwrap();
5099 assert_eq!(older, Disk::default());
5100 assert_eq!(older.reclaim_threshold(), 2 * older.min_free_bytes);
5101
5102 let own = Disk {
5103 reclaim_free_bytes: Some(7),
5104 ..Disk::default()
5105 };
5106 let back: Disk = serde_json::from_value(serde_json::to_value(&own).unwrap()).unwrap();
5107 assert_eq!(back.reclaim_free_bytes, Some(7));
5108 }
5109
5110 #[test]
5111 fn env_is_available_to_templates_with_a_default() {
5112 let dir = tempfile::tempdir().unwrap();
5113 let path = dir.path().join("magi.toml");
5114 std::fs::write(
5122 &path,
5123 "[verify]\n\
5124 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
5125 \"populated={{ env | length > 0 }}\"]\n",
5126 )
5127 .unwrap();
5128 let cfg = Config::load(&path).expect("env lookup must render");
5129 assert_eq!(cfg.verify.gate[0], "cache=fallback");
5130 assert_eq!(cfg.verify.gate[1], "populated=true");
5131 }
5132
5133 #[test]
5134 fn a_broken_template_names_the_file() {
5135 let dir = tempfile::tempdir().unwrap();
5136 let path = dir.path().join("magi.toml");
5137 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
5138 let err = Config::load(&path).expect_err("must not silently ignore");
5139 assert!(err.to_string().contains("teravars"), "{err}");
5140 }
5141
5142 #[test]
5143 fn tera_syntax_in_comments_is_inert() {
5144 let dir = tempfile::tempdir().unwrap();
5148 let path = dir.path().join("magi.toml");
5149 std::fs::write(
5150 &path,
5151 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
5152 [graph]\ncandidates = 2\n",
5153 )
5154 .unwrap();
5155 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
5156 assert_eq!(cfg.graph.implementers, 2);
5157 }
5158
5159 #[test]
5160 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
5161 use std::time::Duration;
5162
5163 let mut s: AgentSpec =
5164 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
5165 let budget = Duration::from_millis(1500);
5166 assert_eq!(s.max_turn_secs, None);
5167 assert_eq!(s.turn_timeout(budget), budget);
5168 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
5169 for (cap, expected) in [
5170 (1, Duration::from_secs(1)),
5171 (2, budget),
5172 (0, Duration::ZERO),
5173 ] {
5174 s.max_turn_secs = Some(cap);
5175 let saved = toml::to_string(&s).unwrap();
5176 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
5177 assert_eq!(loaded.max_turn_secs, Some(cap));
5178 assert_eq!(loaded.turn_timeout(budget), expected);
5179 }
5180 }
5181
5182 #[test]
5183 fn opencode_defaults_to_file_delivery() {
5184 let mut s = spec("oc");
5185 s.kind = AgentKind::Opencode;
5186 assert_eq!(s.delivery(), Delivery::File);
5187 s.prompt_delivery = Some(Delivery::Argv);
5188 assert_eq!(s.delivery(), Delivery::Argv);
5189 }
5190 #[test]
5191 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
5192 let g = Graph::default();
5197 assert!(
5198 g.land,
5199 "stopping at an open PR left the watching to a human"
5200 );
5201 assert!(
5202 g.land_approval,
5203 "on-by-default land is only defensible while this is also on"
5204 );
5205 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
5206 assert!(
5207 g.hold_contested_merge,
5208 "a contested hand-off must still reach a human when approvals are off"
5209 );
5210 }
5211 #[test]
5212 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
5213 let dir = tempfile::tempdir().unwrap();
5217 let machine = dir.path().join("machine.toml");
5218 let repo = dir.path().join("magi.toml");
5219 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
5220 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
5221
5222 let err = Config::load_layers(&[machine.clone(), repo.clone()])
5223 .expect_err("two layers naming one array must not merge silently");
5224 assert_eq!(
5225 err.downcast_ref::<ConfigFailure>().unwrap().stage,
5226 "config-merge"
5227 );
5228 let err = err.to_string();
5229 assert!(err.contains("roles.implementers"), "{err}");
5230 assert!(err.contains("machine.toml"), "{err}");
5233 assert!(err.contains("magi.toml"), "{err}");
5234 }
5235
5236 #[test]
5237 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
5238 let dir = tempfile::tempdir().unwrap();
5241 let machine = dir.path().join("machine.toml");
5242 let repo = dir.path().join("magi.toml");
5243 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
5244 std::fs::write(
5245 &repo,
5246 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
5247 [roles]\nimplementers = [\"oc\"]\n",
5248 )
5249 .unwrap();
5250
5251 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
5252 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
5253 assert_eq!(cfg.roles.implementers, ["oc"]);
5254 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
5255 }
5256
5257 #[test]
5258 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
5259 let dir = tempfile::tempdir().unwrap();
5262 let machine = dir.path().join("machine.toml");
5263 let repo = dir.path().join("magi.toml");
5264 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
5265 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5266
5267 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5268 assert_eq!(
5269 cfg.verify.gate,
5270 [
5271 "editorconfig-checker".to_owned(),
5272 "cargo make check".to_owned()
5273 ],
5274 "low-priority (machine) command first, high-priority (repo) command after"
5275 );
5276 }
5277
5278 fn load_one(body: &str) -> Result<Config> {
5279 let dir = tempfile::tempdir().unwrap();
5280 let path = dir.path().join("magi.toml");
5281 std::fs::write(&path, body).unwrap();
5282 Config::load_layers(&[path])
5283 }
5284
5285 #[test]
5286 fn pre_clean_config_is_strict_and_single_layer() {
5287 assert!(Config::default().worktree.pre_clean.is_empty());
5288 let good = load_one("[worktree]\npre_clean = [{run = 'cleanup', timeout_secs = 60}]\n");
5289 assert_eq!(good.unwrap().worktree.pre_clean[0].timeout_secs, Some(60));
5290 for bad in [
5291 "{}",
5292 "{run = ''}",
5293 "{run = ' ', timeout_secs = 2}",
5294 "{run = 'x', timeout_secs = 0}",
5295 "{run = 'x', timeout_secs = -1}",
5296 "{copy = 'cache'}",
5297 "{run = 'x', optional = true}",
5298 "'x'",
5299 ] {
5300 assert!(
5301 load_one(&format!("[worktree]\npre_clean = [{bad}]\n")).is_err(),
5302 "{bad}"
5303 );
5304 }
5305 let dir = tempfile::tempdir().unwrap();
5306 let a = dir.path().join("a.toml");
5307 let b = dir.path().join("b.toml");
5308 for path in [&a, &b] {
5309 std::fs::write(path, "[worktree]\npre_clean = [{run = 'cleanup'}]\n").unwrap();
5310 }
5311 assert!(
5312 Config::load_layers(&[a, b])
5313 .unwrap_err()
5314 .to_string()
5315 .contains("worktree.pre_clean")
5316 );
5317 }
5318
5319 #[test]
5320 fn worktree_setup_defaults_to_empty_and_parses_steps() {
5321 assert!(Config::default().worktree.setup.is_empty());
5322 let cfg = load_one(
5323 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
5324 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
5325 )
5326 .unwrap();
5327 assert_eq!(cfg.worktree.setup.len(), 3);
5328 assert!(cfg.worktree.setup[1].optional);
5329 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
5330 }
5331
5332 #[test]
5333 fn worktree_setup_rejects_malformed_steps() {
5334 for bad in [
5335 "{ copy = \"a\", run = \"b\" }",
5336 "{ optional = true }",
5337 "{ copy = \"a -> ../b\" }",
5338 "{ copy = \"a -> /abs\" }",
5339 "{ copy = \"a -> .git/config\" }",
5340 "{ run = \"b\", optional = true }",
5341 "{ copy = \"a\", timeout_secs = 3 }",
5342 "{ run = \"b\", bogus = 1 }",
5343 ] {
5344 let body = format!("[worktree]\nsetup = [{bad}]\n");
5345 assert!(load_one(&body).is_err(), "{bad}");
5346 }
5347 }
5348
5349 #[test]
5350 fn worktree_setup_in_two_layers_is_refused() {
5351 let dir = tempfile::tempdir().unwrap();
5352 let machine = dir.path().join("machine.toml");
5353 let repo = dir.path().join("magi.toml");
5354 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
5355 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
5356 assert!(Config::load_layers(&[machine, repo]).is_err());
5357 }
5358
5359 #[test]
5360 fn starter_toml_documents_worktree_setup() {
5361 let starter = Config::starter_toml();
5362 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
5363 let body = starter.replace("# [worktree]", "[worktree]");
5365 let mut out = String::new();
5366 let mut live = false;
5367 for line in body.lines() {
5368 if line == "[worktree]" {
5369 live = true;
5370 } else if live && !line.starts_with("# ") {
5371 live = false;
5372 }
5373 out.push_str(&if live {
5374 line.replacen("# ", "", 1)
5375 } else {
5376 line.to_owned()
5377 });
5378 out.push('\n');
5379 }
5380 let cfg = load_one(&out).expect("uncommented example loads");
5381 assert_eq!(cfg.worktree.setup.len(), 3);
5382 }
5383
5384 #[test]
5385 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
5386 let dir = tempfile::tempdir().unwrap();
5387 let machine = dir.path().join("machine.toml");
5388 let repo = dir.path().join("magi.toml");
5389 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
5390 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
5391
5392 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5393 assert_eq!(
5394 cfg.verify.e2e,
5395 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
5396 );
5397 }
5398
5399 #[test]
5400 fn two_layers_declaring_repos_roots_are_both_scanned() {
5401 let dir = tempfile::tempdir().unwrap();
5402 let machine = dir.path().join("machine.toml");
5403 let repo = dir.path().join("magi.toml");
5404 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
5405 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
5406
5407 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5408 assert_eq!(
5409 cfg.repos.roots,
5410 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
5411 );
5412 }
5413
5414 #[test]
5415 fn duplicate_gate_commands_across_layers_both_run() {
5416 let dir = tempfile::tempdir().unwrap();
5419 let machine = dir.path().join("machine.toml");
5420 let repo = dir.path().join("magi.toml");
5421 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
5422 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
5423
5424 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5425 assert_eq!(
5426 cfg.verify.gate,
5427 ["same-command".to_owned(), "same-command".to_owned()]
5428 );
5429 }
5430
5431 #[test]
5432 fn notify_command_is_still_refused_across_two_layers() {
5433 let dir = tempfile::tempdir().unwrap();
5435 let machine = dir.path().join("machine.toml");
5436 let repo = dir.path().join("magi.toml");
5437 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
5438 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
5439
5440 let err = Config::load_layers(&[machine.clone(), repo.clone()])
5441 .expect_err("an argv split across layers must not concatenate");
5442 assert_eq!(
5443 err.downcast_ref::<ConfigFailure>().unwrap().stage,
5444 "config-merge"
5445 );
5446 let err = err.to_string();
5447 assert!(err.contains("notify.command"), "{err}");
5448 assert!(err.contains("machine.toml"), "{err}");
5449 assert!(err.contains("magi.toml"), "{err}");
5450 }
5451
5452 #[test]
5453 fn one_layer_declaring_verify_gate_runs_unchanged() {
5454 let dir = tempfile::tempdir().unwrap();
5457 let path = dir.path().join("magi.toml");
5458 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5459
5460 let cfg = Config::load(&path).expect("single layer must still load");
5461 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
5462 }
5463
5464 #[test]
5465 fn layered_parse_failures_name_the_failing_input() {
5466 let dir = tempfile::tempdir().unwrap();
5467 let a = dir.path().join("a.toml");
5468 let b = dir.path().join("b.toml");
5469 std::fs::write(&a, "[graph").unwrap();
5470 std::fs::write(&b, "[verify").unwrap();
5471 let paths = [a.clone(), b.clone()];
5472 let first = Config::load_layers(&paths).unwrap_err();
5473 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
5474 assert_eq!(first_cause.stage, "config-parse");
5475 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
5476 std::fs::write(&a, "").unwrap();
5477 let second = Config::load_layers(&paths).unwrap_err();
5478 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
5479 assert_eq!(second_cause.stage, "config-parse");
5480 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
5481 assert_ne!(first_cause.target, second_cause.target);
5482 }
5483
5484 #[test]
5485 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
5486 let dir = tempfile::tempdir().unwrap();
5487 let machine = dir.path().join("machine.toml");
5488 let repo = dir.path().join("magi.toml");
5489 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
5490 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5491 let paths = vec![machine.clone(), repo.clone()];
5492
5493 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
5494 let described =
5495 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
5496 assert!(described.contains("editorconfig-checker && cargo make check"));
5497 assert!(
5498 described.contains(&machine.display().to_string()),
5499 "{described}"
5500 );
5501 assert!(
5502 described.contains(&repo.display().to_string()),
5503 "{described}"
5504 );
5505
5506 let single = vec![repo.clone()];
5508 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
5509 let solo_described =
5510 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
5511 assert_eq!(solo_described, "cargo make check");
5512 }
5513
5514 mod remote_layers {
5515 use super::*;
5516
5517 fn git(dir: &Path, args: &[&str]) {
5518 use crate::proc::Quiet as _;
5519 let out = std::process::Command::new("git")
5520 .args(args)
5521 .quiet()
5522 .current_dir(dir)
5523 .output()
5524 .unwrap();
5525 assert!(out.status.success(), "git {args:?}: {out:?}");
5526 }
5527
5528 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
5531 let tmp = tempfile::tempdir().unwrap();
5532 let bare = tmp.path().join("o.git");
5533 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
5534 let repo = tmp.path().join("repo");
5535 std::fs::create_dir_all(&repo).unwrap();
5536 git(&repo, &["init", "-b", "trunk"]);
5537 git(&repo, &["config", "user.name", "t"]);
5538 git(&repo, &["config", "user.email", "t@example.com"]);
5539 std::fs::write(repo.join("magi.toml"), remote).unwrap();
5540 git(&repo, &["add", "-A"]);
5541 git(&repo, &["commit", "-m", "x"]);
5542 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
5543 git(&repo, &["push", "origin", "trunk"]);
5544 git(&repo, &["fetch", "origin"]);
5545 git(&repo, &["remote", "set-head", "origin", "trunk"]);
5546 std::fs::write(repo.join("magi.toml"), disk).unwrap();
5547 (tmp, repo)
5548 }
5549
5550 #[tokio::test]
5551 async fn branch_owner_holds_only_add_literal_true_values() {
5552 for (text, expected) in [
5553 ("[graph]\nland_approval = true\n", true),
5554 ("[graph]\nland_approval = false\n", false),
5555 ("[graph]\nland = true\n", false),
5556 ("[graph\n", false),
5557 ("[graph]\nland_approval = \"yes\"\n", false),
5558 ("[graph]\nland_approval = 1\n", false),
5559 ] {
5560 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
5561 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
5562 let (holds, _) = branch_owner_holds(&repo, &head).await;
5563 assert_eq!(
5564 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
5565 expected
5566 );
5567 assert!(
5568 !holds
5569 .iter()
5570 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
5571 );
5572 for base in [false, true] {
5573 let mut cfg = Config::default();
5574 cfg.graph.land_approval = base;
5575 let mut state = crate::run::RunState::new(
5576 repo.clone(),
5577 "trunk".into(),
5578 head.clone(),
5579 "review".into(),
5580 cfg,
5581 );
5582 state.observe_branch_owner_holds(&head).await;
5583 assert!(
5584 state.branch_owner_holds.is_empty(),
5585 "competition candidates are excluded"
5586 );
5587 state.reviewed_commits = Some(Vec::new());
5588 state.observe_branch_owner_holds(&head).await;
5589 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
5590 }
5591 }
5592 }
5593
5594 #[tokio::test]
5595 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
5596 let (_tmp, repo) = fixture(
5597 "[graph]\nland_approval = true\n",
5598 "[graph]\nland_approval = true\n",
5599 );
5600 git(&repo, &["rm", "magi.toml"]);
5601 std::fs::create_dir(repo.join(".magi")).unwrap();
5602 std::fs::write(
5603 repo.join(".magi/config.toml"),
5604 "[graph]\nhold_contested_merge = true\n",
5605 )
5606 .unwrap();
5607 git(&repo, &["add", "."]);
5608 git(&repo, &["commit", "-m", "nested hold"]);
5609 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
5610 let (holds, _) = branch_owner_holds(&repo, &head).await;
5611 assert_eq!(
5612 holds,
5613 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
5614 );
5615 let (holds, diagnostics) =
5616 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
5617 assert!(holds.is_empty());
5618 assert!(!diagnostics.is_empty());
5619 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
5620 assert!(holds.is_empty());
5621 assert!(!diagnostics.is_empty());
5622 for base in [false, true] {
5623 let mut cfg = Config::default();
5624 cfg.graph.land_approval = base;
5625 let mut state = crate::run::RunState::new(
5626 repo.clone(),
5627 "trunk".into(),
5628 head.clone(),
5629 "review".into(),
5630 cfg,
5631 );
5632 state.reviewed_commits = Some(Vec::new());
5633 state.observe_branch_owner_holds(&head).await;
5634 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
5635 state
5636 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
5637 .await;
5638 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
5639 }
5640 }
5641
5642 #[test]
5643 fn reads_the_remote_blob_not_the_working_tree() {
5644 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5645 let (cfg, _) = Config::discover(&repo, None).unwrap();
5646 assert_eq!(cfg.graph.implementers, 2);
5647 }
5648
5649 #[test]
5650 fn detached_head_still_reads_the_remote() {
5651 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5652 git(&repo, &["checkout", "--detach"]);
5653 let (cfg, _) = Config::discover(&repo, None).unwrap();
5654 assert_eq!(cfg.graph.implementers, 2);
5655 }
5656
5657 #[test]
5658 fn a_missing_ref_is_an_error_not_a_fallback() {
5659 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5660 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5661 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
5662 assert!(err.contains("origin"), "{err}");
5663 }
5664
5665 #[test]
5666 fn merge_base_in_the_checkout_locates_the_ref() {
5667 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
5668 assert!(Config::discover(&repo, None).is_err());
5669 }
5670
5671 #[test]
5672 fn the_magi_dir_layer_is_read_too() {
5673 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5674 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
5675 std::fs::create_dir_all(repo.join(".magi")).unwrap();
5676 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
5677 git(&repo, &["add", "-A"]);
5678 git(&repo, &["commit", "-m", "y"]);
5679 git(&repo, &["push", "origin", "trunk"]);
5680 git(&repo, &["fetch", "origin"]);
5681 let ((cfg, layers), (_, cold_git)) =
5682 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5683 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
5684 assert_eq!(layers.len(), 2);
5685 assert_eq!(cold_git, 1);
5686 let common_cache = repo
5687 .join(".git")
5688 .canonicalize()
5689 .unwrap()
5690 .join("magi")
5691 .join("config");
5692 assert!(
5693 layers.iter().all(|p| p.starts_with(&common_cache)),
5694 "expected .magi/config.toml and magi.toml to cache under common git dir {}, got {layers:?}",
5695 common_cache.display()
5696 );
5697
5698 let ((cfg_warm, warm_layers), (_, warm_git)) =
5699 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5700 assert_eq!((cfg_warm.graph.implementers, cfg_warm.graph.judges), (2, 3));
5701 assert_eq!(warm_layers, layers);
5702 assert_eq!(warm_git, 1);
5703 }
5704
5705 #[test]
5706 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
5707 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
5708 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
5709 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
5710 git(&repo, &["add", "-A"]);
5711 git(&repo, &["commit", "-m", "inc"]);
5712 git(&repo, &["push", "origin", "trunk"]);
5713 git(&repo, &["fetch", "origin"]);
5714 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
5716 let (cfg, _) = Config::discover(&repo, None).unwrap();
5717 assert_eq!(cfg.graph.implementers, 2);
5718 }
5719
5720 #[test]
5721 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
5722 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
5723 let m = t.path().join("machine.toml");
5724 std::fs::write(
5725 &m,
5726 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
5727 )
5728 .unwrap();
5729 let (remote, base) = {
5730 let probe = probe_merge(&m, &repo).unwrap();
5731 (probe.remote, probe.base)
5732 };
5733 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
5734 }
5735
5736 #[test]
5737 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
5738 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5739 let m = t.path().join("machine.toml");
5740 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
5741 let probe = probe_merge(&m, &repo).unwrap();
5742 assert_eq!(probe.base.as_deref(), Some("repo"));
5743 }
5744
5745 #[test]
5746 fn every_include_form_is_recognised() {
5747 assert!(declares_include("include = [\"a.toml\"]\n"));
5748 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
5749 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
5750 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
5751 assert!(!declares_include("[graph]\ncandidates = 2\n"));
5752 }
5753
5754 #[test]
5755 fn an_explicit_config_is_read_as_named() {
5756 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5757 let own = t.path().join("own.toml");
5758 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
5759 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
5760 assert_eq!(cfg.graph.implementers, 4);
5761 }
5762
5763 #[test]
5764 fn discover_fetched_fails_when_the_fetch_does() {
5765 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5766 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
5767 let rt = tokio::runtime::Builder::new_current_thread()
5768 .enable_all()
5769 .build()
5770 .unwrap();
5771 let err = rt
5772 .block_on(Config::discover_fetched(&repo, None))
5773 .unwrap_err();
5774 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
5775 }
5776
5777 #[test]
5778 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
5779 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
5780 let remote = tmp.path().join("o.git");
5781 let offline = tmp.path().join("offline.git");
5782 std::fs::rename(&remote, &offline).unwrap();
5783 let rt = tokio::runtime::Builder::new_current_thread()
5784 .enable_all()
5785 .build()
5786 .unwrap();
5787 let fetch = rt
5788 .block_on(Config::discover_fetched(&repo, None))
5789 .unwrap_err();
5790 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
5791 assert_eq!(fetch_cause.stage, "config-fetch");
5792 assert_eq!(fetch_cause.target, "origin/trunk");
5793
5794 std::fs::rename(&offline, &remote).unwrap();
5795 let parse = rt
5796 .block_on(Config::discover_fetched(&repo, None))
5797 .unwrap_err();
5798 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
5799 assert_eq!(parse_cause.stage, "config-parse");
5800 assert!(parse_cause.target.contains("magi.toml"));
5801 assert!(
5802 !parse_cause.target.contains("/magi/config/"),
5803 "cache commit paths are incidental"
5804 );
5805 assert_ne!(fetch_cause.stage, parse_cause.stage);
5806 }
5807
5808 #[test]
5809 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
5810 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5813 git(&repo, &["remote", "set-head", "origin", "-d"]);
5814 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5815 git(
5816 &repo,
5817 &["config", "remote.origin.followRemoteHEAD", "never"],
5818 );
5819 let rt = tokio::runtime::Builder::new_current_thread()
5820 .enable_all()
5821 .build()
5822 .unwrap();
5823 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
5824 assert_eq!(cfg.graph.implementers, 2);
5825 }
5826
5827 #[test]
5828 fn a_non_git_directory_reads_its_files() {
5829 let dir = tempfile::tempdir().unwrap();
5830 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
5831 let (cfg, (discoveries, git_calls)) =
5832 crate::web::request_cost::measure_sync(|| Config::discover(dir.path(), None));
5833 assert_eq!(cfg.unwrap().0.graph.implementers, 4);
5834 assert_eq!((discoveries, git_calls), (1, 0));
5835 }
5836
5837 fn push_remote_config(bare: &Path, branch: &str, magi_toml: &str) {
5838 let tmp = tempfile::tempdir().unwrap();
5839 let clone = tmp.path().join("push");
5840 git(
5841 tmp.path(),
5842 &["clone", "-b", branch, &bare.to_string_lossy(), "push"],
5843 );
5844 git(&clone, &["config", "user.name", "t"]);
5845 git(&clone, &["config", "user.email", "t@example.com"]);
5846 std::fs::write(clone.join("magi.toml"), magi_toml).unwrap();
5847 git(&clone, &["add", "magi.toml"]);
5848 git(&clone, &["commit", "-m", "update config"]);
5849 git(&clone, &["push", "origin", branch]);
5850 }
5851
5852 #[test]
5853 fn repeated_discovers_stay_within_bounded_git_spawns() {
5854 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5855
5856 let (values, (discoveries, cold_git)) = crate::web::request_cost::measure_sync(|| {
5859 (0..20)
5860 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5861 .collect::<Vec<_>>()
5862 });
5863 assert!(values.iter().all(|&n| n == 2));
5864 assert_eq!(discoveries, 20);
5865 assert_eq!(cold_git, 21);
5866
5867 let (values, (discoveries, warm_git)) = crate::web::request_cost::measure_sync(|| {
5869 (0..20)
5870 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5871 .collect::<Vec<_>>()
5872 });
5873 assert!(values.iter().all(|&n| n == 2));
5874 assert_eq!(discoveries, 20);
5875 assert_eq!(warm_git, 20);
5876 }
5877
5878 #[test]
5879 fn reftable_warm_discover_uses_one_git_process() {
5880 let tmp = tempfile::tempdir().unwrap();
5881 let repo = tmp.path();
5882 git(repo, &["init", "--ref-format=reftable", "-b", "trunk"]);
5883 git(repo, &["config", "user.name", "t"]);
5884 git(repo, &["config", "user.email", "t@example.com"]);
5885 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
5886 git(repo, &["add", "magi.toml"]);
5887 git(repo, &["commit", "-m", "config"]);
5888 git(repo, &["update-ref", "refs/remotes/origin/trunk", "HEAD"]);
5889 git(
5890 repo,
5891 &[
5892 "symbolic-ref",
5893 "refs/remotes/origin/HEAD",
5894 "refs/remotes/origin/trunk",
5895 ],
5896 );
5897 assert_eq!(
5898 Config::discover(repo, None).unwrap().0.graph.implementers,
5899 2
5900 );
5901 let (values, (_, count)) = crate::web::request_cost::measure_sync(|| {
5902 (0..10)
5903 .map(|_| Config::discover(repo, None).unwrap().0.graph.implementers)
5904 .collect::<Vec<_>>()
5905 });
5906 assert_eq!(values, vec![2; 10]);
5907 assert_eq!(count, 10);
5908 }
5909
5910 #[test]
5911 fn zero_layer_repository_caches_empty_manifest() {
5912 let tmp = tempfile::tempdir().unwrap();
5913 let bare = tmp.path().join("o.git");
5914 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
5915 let repo = tmp.path().join("repo");
5916 std::fs::create_dir_all(&repo).unwrap();
5917 git(&repo, &["init", "-b", "trunk"]);
5918 git(&repo, &["config", "user.name", "t"]);
5919 git(&repo, &["config", "user.email", "t@example.com"]);
5920 std::fs::write(repo.join("README.md"), "hello\n").unwrap();
5921 git(&repo, &["add", "-A"]);
5922 git(&repo, &["commit", "-m", "no config"]);
5923 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
5924 git(&repo, &["push", "origin", "trunk"]);
5925 git(&repo, &["fetch", "origin"]);
5926 git(&repo, &["remote", "set-head", "origin", "trunk"]);
5927
5928 let (layers, (_, cold_git)) = crate::web::request_cost::measure_sync(|| {
5929 let mut last = Vec::new();
5930 for _ in 0..20 {
5931 last = Config::discover(&repo, None).unwrap().1;
5932 }
5933 last
5934 });
5935 assert!(layers.is_empty());
5936 assert_eq!(cold_git, 21);
5937
5938 let (layers, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
5939 let mut last = Vec::new();
5940 for _ in 0..20 {
5941 last = Config::discover(&repo, None).unwrap().1;
5942 }
5943 last
5944 });
5945 assert!(layers.is_empty());
5946 assert_eq!(warm_git, 20);
5947 }
5948
5949 #[test]
5950 fn moved_loose_and_packed_refs_are_observed_immediately() {
5951 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5952 let bare = t.path().join("o.git");
5953
5954 assert_eq!(
5956 Config::discover(&repo, None).unwrap().0.graph.implementers,
5957 2
5958 );
5959 let (_, (_, warm_git)) =
5960 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5961 assert_eq!(warm_git, 1);
5962
5963 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 3\n");
5965 git(&repo, &["fetch", "origin"]);
5966 let (cfg, (_, moved_git)) =
5967 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5968 assert_eq!(cfg.graph.implementers, 3);
5969 assert_eq!(moved_git, 2);
5970 let (cfg, (_, warm_after_move)) =
5971 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5972 assert_eq!(cfg.graph.implementers, 3);
5973 assert_eq!(warm_after_move, 1);
5974
5975 git(&repo, &["pack-refs", "--all"]);
5977 let (cfg, (_, packed_warm)) =
5978 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5979 assert_eq!(cfg.graph.implementers, 3);
5980 assert_eq!(packed_warm, 1);
5981
5982 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 4\n");
5984 git(&repo, &["fetch", "origin"]);
5985 git(&repo, &["pack-refs", "--all"]);
5986 let (cfg, (_, packed_move)) =
5987 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5988 assert_eq!(cfg.graph.implementers, 4);
5989 assert_eq!(packed_move, 2);
5990 let (cfg, (_, packed_warm_2)) =
5991 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5992 assert_eq!(cfg.graph.implementers, 4);
5993 assert_eq!(packed_warm_2, 1);
5994
5995 assert!(
5997 std::fs::read_to_string(repo.join("magi.toml"))
5998 .unwrap()
5999 .contains("candidates = 9")
6000 );
6001 }
6002
6003 #[test]
6004 fn linked_worktree_reuses_common_dir_cache_with_one_warm_git_spawn() {
6005 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6006 let bare = t.path().join("o.git");
6007 let wt = t.path().join("linked-wt");
6008 git(
6009 &repo,
6010 &["worktree", "add", "--detach", &wt.to_string_lossy()],
6011 );
6012
6013 let (cfg, (_, cold_git)) =
6014 crate::web::request_cost::measure_sync(|| Config::discover(&wt, None).unwrap().0);
6015 assert_eq!(cfg.graph.implementers, 2);
6016 assert_eq!(cold_git, 2);
6017
6018 let (values, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
6019 (0..10)
6020 .map(|_| Config::discover(&wt, None).unwrap().0.graph.implementers)
6021 .collect::<Vec<_>>()
6022 });
6023 assert!(values.iter().all(|&n| n == 2));
6024 assert_eq!(warm_git, 10);
6025
6026 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 5\n");
6027 git(&wt, &["fetch", "origin"]);
6028 let (cfg, (_, moved_git)) =
6029 crate::web::request_cost::measure_sync(|| Config::discover(&wt, None).unwrap().0);
6030 assert_eq!(cfg.graph.implementers, 5);
6031 assert_eq!(moved_git, 2);
6032 }
6033
6034 #[test]
6035 fn deleted_or_retargeted_refs_never_reuse_stale_cache() {
6036 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6037 let bare = t.path().join("o.git");
6038 assert_eq!(
6039 Config::discover(&repo, None).unwrap().0.graph.implementers,
6040 2
6041 );
6042
6043 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
6045 assert!(Config::discover(&repo, None).is_err());
6046
6047 git(&repo, &["fetch", "origin"]);
6050 git(&repo, &["checkout", "-b", "alt"]);
6051 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 6\n").unwrap();
6052 git(&repo, &["add", "magi.toml"]);
6053 git(&repo, &["commit", "-m", "alt"]);
6054 git(&repo, &["push", "origin", "alt"]);
6055 git(&repo, &["fetch", "origin"]);
6056 let _ = bare;
6057 git(&repo, &["remote", "set-head", "origin", "alt"]);
6058 assert_eq!(
6059 Config::discover(&repo, None).unwrap().0.graph.implementers,
6060 6
6061 );
6062
6063 git(&repo, &["remote", "set-head", "origin", "-d"]);
6065 assert!(Config::discover(&repo, None).is_err());
6066 }
6067
6068 #[test]
6069 fn include_repository_reuses_extracted_tree_with_one_warm_git_spawn() {
6070 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
6071 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
6072 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
6073 git(&repo, &["add", "-A"]);
6074 git(&repo, &["commit", "-m", "inc"]);
6075 git(&repo, &["push", "origin", "trunk"]);
6076 git(&repo, &["fetch", "origin"]);
6077 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
6078
6079 let (cfg, (_, cold_git)) =
6080 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
6081 assert_eq!(cfg.graph.implementers, 2);
6082 assert_eq!(cold_git, 3);
6084
6085 let (values, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
6086 (0..10)
6087 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
6088 .collect::<Vec<_>>()
6089 });
6090 assert!(values.iter().all(|&n| n == 2));
6091 assert_eq!(warm_git, 10);
6092 }
6093
6094 #[test]
6095 fn partial_clone_loads_promised_config_blob() {
6096 let (tmp, source) = fixture("[graph]\ncandidates = 2\n", "");
6097 let bare = tmp.path().join("o.git");
6098 git(&bare, &["config", "uploadpack.allowFilter", "true"]);
6099 let clone = tmp.path().join("partial");
6100 git(
6101 tmp.path(),
6102 &[
6103 "clone",
6104 "--no-local",
6105 "--no-checkout",
6106 "--filter=blob:none",
6107 &bare.to_string_lossy(),
6108 &clone.to_string_lossy(),
6109 ],
6110 );
6111 let oid = git_out(&source, &["rev-parse", "HEAD:magi.toml"]).unwrap();
6112 let missing = repository_git()
6113 .env("GIT_NO_LAZY_FETCH", "1")
6114 .args(["cat-file", "-e", oid.trim()])
6115 .current_dir(&clone)
6116 .output()
6117 .unwrap();
6118 assert!(!missing.status.success(), "fixture must omit the blob");
6119 assert_eq!(
6120 Config::discover(&clone, None).unwrap().0.graph.implementers,
6121 2
6122 );
6123 }
6124
6125 #[test]
6126 fn missing_config_blob_is_not_cached_as_an_absent_layer() {
6127 let (_tmp, repo) = fixture("[graph]\ncandidates = 2\n", "");
6128 let oid = git_out(&repo, &["rev-parse", "HEAD:magi.toml"]).unwrap();
6129 let oid = oid.trim();
6130 let blob = repo.join(".git/objects").join(&oid[..2]).join(&oid[2..]);
6131 let saved = blob.with_extension("saved");
6132 std::fs::rename(&blob, &saved).unwrap();
6133 assert!(Config::discover(&repo, None).is_err());
6134 std::fs::rename(saved, blob).unwrap();
6135 assert_eq!(
6136 Config::discover(&repo, None).unwrap().0.graph.implementers,
6137 2
6138 );
6139 }
6140
6141 #[test]
6142 fn a_cached_config_does_not_hide_a_missing_base_commit() {
6143 let (_tmp, repo) = fixture("[graph]\ncandidates = 2\n", "");
6144 assert_eq!(
6145 Config::discover(&repo, None).unwrap().0.graph.implementers,
6146 2
6147 );
6148 let oid = git_out(&repo, &["rev-parse", "HEAD"]).unwrap();
6149 let oid = oid.trim();
6150 let commit = repo.join(".git/objects").join(&oid[..2]).join(&oid[2..]);
6151 let saved = commit.with_extension("saved");
6152 std::fs::rename(&commit, &saved).unwrap();
6153 assert!(Config::discover(&repo, None).is_err());
6154 std::fs::rename(saved, commit).unwrap();
6155 assert_eq!(
6156 Config::discover(&repo, None).unwrap().0.graph.implementers,
6157 2
6158 );
6159 }
6160
6161 #[test]
6162 fn corrupt_cache_directory_without_manifest_is_not_trusted() {
6163 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6164 let sha = git_out(&repo, &["rev-parse", "refs/remotes/origin/trunk^{commit}"])
6165 .unwrap()
6166 .trim()
6167 .to_owned();
6168 let key = format!(
6169 "{sha}-{}-v{CACHE_MANIFEST_VERSION}",
6170 fnv_hex(&repo.to_string_lossy())
6171 );
6172 let bad_dir = repo.join(".git/magi/config").join(&key);
6173 std::fs::create_dir_all(&bad_dir).unwrap();
6174 std::fs::write(bad_dir.join("magi.toml"), "[graph]\ncandidates = 9\n").unwrap();
6175 std::fs::write(bad_dir.join(REPO_MARKER), repo.to_string_lossy().as_bytes()).unwrap();
6176
6177 let (cfg, _) = Config::discover(&repo, None).unwrap();
6179 assert_eq!(cfg.graph.implementers, 2);
6180 }
6181
6182 #[test]
6183 fn resolve_remote_head_and_commit_cli_uses_one_git_process() {
6184 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6185 let expected = git_out(&repo, &["rev-parse", "refs/remotes/origin/trunk^{commit}"])
6186 .unwrap()
6187 .trim()
6188 .to_owned();
6189 let (resolved, (_, git_calls)) = crate::web::request_cost::measure_sync(|| {
6190 resolve_remote_head_and_commit_cli(&repo, "origin").unwrap()
6191 });
6192 assert_eq!(resolved, ("trunk".to_owned(), expected));
6193 assert_eq!(git_calls, 1);
6194 }
6195
6196 #[test]
6197 fn standard_files_ref_backend_rejects_nonstandard_git_config() {
6198 let tmp = tempfile::tempdir().unwrap();
6199 let common = tmp.path().join("git");
6200 std::fs::create_dir_all(common.join("refs")).unwrap();
6201
6202 let check = |cfg: &str| {
6203 std::fs::write(common.join("config"), cfg).unwrap();
6204 is_standard_files_ref_backend(&common)
6205 };
6206
6207 assert!(check("[core]\n\trepositoryformatversion = 0\n"));
6208 assert!(check(
6209 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tworktreeConfig = true\n\trefStorage = files\n\tobjectFormat = sha1\n"
6210 ));
6211 assert!(!check(
6212 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\trefStorage = reftable\n"
6213 ));
6214 assert!(!check(
6215 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tobjectFormat = sha256\n"
6216 ));
6217 assert!(!check(
6218 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tunknownExt\n"
6219 ));
6220 assert!(!check(
6221 "[core]\n\trepositoryformatversion = 1\n[extensions] refStorage = reftable\n"
6222 ));
6223 assert!(!check(
6224 "[core]\n\trepositoryformatversion = 0\n[include]\n\tpath = extra.cfg\n"
6225 ));
6226 assert!(!check(
6227 "[core]\n\trepositoryformatversion = 0\n\tfoo = bar\\\nbaz\n"
6228 ));
6229 }
6230 }
6231
6232 #[test]
6233 fn github_language_defaults_to_english_and_accepts_japanese() {
6234 let default: Graph = toml::from_str("").unwrap();
6235 assert_eq!(default.github_language, "en");
6236 assert!(default.github_english() && default.language_gate());
6237 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
6238 assert!(!ja.github_english() && !ja.language_gate());
6239 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
6241 assert!(only_ops.language_gate());
6242 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
6243 assert!(!off.language_gate() && off.github_english());
6244 assert!(Config::starter_toml().contains("github_language = \"en\""));
6245 }
6246}