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_manifests(&self) -> Vec<PathBuf> {
851 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
852 crate::cache::extract_manifest_paths(&all)
853 }
854}
855
856#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
858#[serde(deny_unknown_fields, default)]
859pub struct Worktree {
860 pub setup: Vec<SetupStep>,
863 pub pre_clean: Vec<PreCleanStep>,
865}
866
867#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
869#[serde(deny_unknown_fields)]
870pub struct PreCleanStep {
871 pub run: String,
873 pub timeout_secs: Option<u64>,
875}
876
877#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
879#[serde(deny_unknown_fields, default)]
880pub struct SetupStep {
881 pub copy: Option<String>,
884 pub optional: bool,
886 pub run: Option<String>,
888 pub timeout_secs: Option<u64>,
891}
892
893impl Worktree {
894 pub fn validate(&self) -> Result<()> {
896 for (i, step) in self.pre_clean.iter().enumerate() {
897 if step.run.trim().is_empty() || step.timeout_secs == Some(0) {
898 bail!(
899 "[worktree] pre_clean step {} requires a nonempty run and positive timeout",
900 i + 1
901 );
902 }
903 }
904 for (i, step) in self.setup.iter().enumerate() {
905 let n = i + 1;
906 match (&step.copy, &step.run) {
907 (Some(c), None) => {
908 if step.timeout_secs.is_some() {
909 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
910 }
911 crate::worktree_setup::validate_copy(c)
912 .with_context(|| format!("[worktree] setup step {n}"))?;
913 }
914 (None, Some(r)) => {
915 if r.trim().is_empty() {
916 bail!("[worktree] setup step {n}: `run` is empty");
917 }
918 if step.optional {
919 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
920 }
921 }
922 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
923 }
924 }
925 Ok(())
926 }
927}
928
929#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
939#[serde(deny_unknown_fields, default)]
940pub struct Disk {
941 pub min_free_bytes: u64,
950 #[serde(skip_serializing_if = "Option::is_none")]
980 pub reclaim_free_bytes: Option<u64>,
981 pub auto_fold: bool,
987 pub fold_grace_secs: u64,
995 pub cache_limit_bytes: u64,
1007 pub worktree_limit_bytes: u64,
1009 pub worktree_reclaim_bytes: u64,
1013 pub retained_attempt_limit: usize,
1017}
1018
1019impl Disk {
1020 pub fn reclaim_threshold(&self) -> u64 {
1026 let floor = self.min_free_bytes;
1027 self.reclaim_free_bytes
1028 .map_or_else(|| floor.saturating_mul(2), |own| own.max(floor))
1029 }
1030}
1031
1032impl Default for Disk {
1033 fn default() -> Self {
1034 Self {
1035 min_free_bytes: 8 * 1024 * 1024 * 1024,
1036 reclaim_free_bytes: None,
1037 auto_fold: true,
1038 fold_grace_secs: 6 * 60 * 60,
1039 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
1040 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
1041 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
1042 retained_attempt_limit: 8,
1043 }
1044 }
1045}
1046
1047#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1049#[serde(rename_all = "lowercase")]
1050pub enum MergeMode {
1051 None,
1054 Local,
1057 Pr,
1061}
1062
1063#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
1077#[serde(rename_all = "lowercase")]
1078pub enum MergeStyle {
1079 #[default]
1084 Merge,
1085 Squash,
1091 Rebase,
1097}
1098
1099#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1101#[serde(rename_all = "lowercase")]
1102pub enum MergeCi {
1103 #[default]
1105 Expected,
1106 None,
1108}
1109
1110impl MergeCi {
1111 pub fn expectation(self) -> crate::land::CiExpectation {
1113 match self {
1114 Self::Expected => crate::land::CiExpectation::Expected,
1115 Self::None => crate::land::CiExpectation::Absent,
1116 }
1117 }
1118}
1119
1120#[derive(Debug, Clone, Deserialize, Serialize)]
1122#[serde(deny_unknown_fields, default)]
1123pub struct Merge {
1124 pub mode: MergeMode,
1127 pub ci: MergeCi,
1129 pub base: Option<String>,
1131 pub style: MergeStyle,
1134 pub remote: String,
1136 pub release_bump: bool,
1149}
1150
1151impl Default for Merge {
1152 fn default() -> Self {
1153 Self {
1154 mode: MergeMode::None,
1155 ci: MergeCi::Expected,
1156 base: None,
1157 style: MergeStyle::default(),
1158 remote: "origin".to_owned(),
1159 release_bump: true,
1160 }
1161 }
1162}
1163
1164#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1166#[serde(rename_all = "lowercase")]
1167pub enum UpdateMode {
1168 Off,
1170 Notify,
1173 Install,
1175}
1176
1177#[derive(Debug, Clone, Deserialize, Serialize)]
1179#[serde(deny_unknown_fields, default)]
1180pub struct Update {
1181 pub mode: UpdateMode,
1183 pub interval: Option<String>,
1185 pub auto_restart: bool,
1187}
1188
1189impl Default for Update {
1190 fn default() -> Self {
1191 Self {
1192 mode: UpdateMode::Notify,
1193 interval: None,
1194 auto_restart: false,
1195 }
1196 }
1197}
1198
1199#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1201#[serde(rename_all = "lowercase")]
1202pub enum ReleaseMode {
1203 #[default]
1206 Actions,
1207 Local,
1212}
1213
1214#[derive(Debug, Clone, Deserialize, Serialize)]
1216#[serde(deny_unknown_fields, default)]
1217pub struct Release {
1218 pub mode: ReleaseMode,
1221 pub commands: Vec<String>,
1228 pub timeout_minutes: u64,
1230 pub version_files: Vec<VersionFile>,
1238}
1239
1240#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1242#[serde(rename_all = "lowercase")]
1243pub enum VersionKind {
1244 Cargo,
1246 Json,
1248}
1249
1250#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1252#[serde(deny_unknown_fields)]
1253pub struct VersionFile {
1254 pub path: String,
1256 pub kind: VersionKind,
1258}
1259
1260impl Default for Release {
1261 fn default() -> Self {
1262 Self {
1263 mode: ReleaseMode::Actions,
1264 commands: Vec::new(),
1265 timeout_minutes: 30,
1266 version_files: Vec::new(),
1267 }
1268 }
1269}
1270
1271impl Release {
1272 pub fn validate(&self) -> Result<()> {
1274 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1275 }
1276
1277 pub fn is_local(&self) -> bool {
1279 self.mode == ReleaseMode::Local
1280 }
1281}
1282
1283#[derive(Debug, Clone, Deserialize, Serialize)]
1285#[serde(try_from = "CoordinationFields")]
1286pub struct Coordination {
1287 pub contract_file: String,
1289 pub contract_token: String,
1291 pub lock_file: String,
1293}
1294
1295#[derive(Deserialize, Default)]
1296#[serde(deny_unknown_fields, default)]
1297struct CoordinationFields {
1298 contract_file: String,
1299 contract_token: String,
1300 lock_file: String,
1301}
1302
1303impl TryFrom<CoordinationFields> for Coordination {
1304 type Error = anyhow::Error;
1305
1306 fn try_from(fields: CoordinationFields) -> Result<Self> {
1307 for (key, name) in [
1308 ("coordination.contract_file", &fields.contract_file),
1309 ("coordination.lock_file", &fields.lock_file),
1310 ] {
1311 if name.trim().is_empty()
1312 || name != name.trim()
1313 || name == "."
1314 || name.contains("..")
1315 || name.contains(['/', '\\', ':', '\0'])
1316 {
1317 bail!(
1318 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1319 );
1320 }
1321 }
1322 let token = &fields.contract_token;
1323 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1324 bail!(
1325 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1326 );
1327 }
1328 Ok(Self {
1329 contract_file: fields.contract_file,
1330 contract_token: fields.contract_token,
1331 lock_file: fields.lock_file,
1332 })
1333 }
1334}
1335
1336#[cfg(test)]
1337pub(crate) fn test_coordination() -> Option<Coordination> {
1338 Some(Coordination {
1339 contract_file: "updater.contract".into(),
1340 contract_token: "test-protocol-v1".into(),
1341 lock_file: "updater.lock".into(),
1342 })
1343}
1344
1345#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1347#[serde(deny_unknown_fields, default)]
1348pub struct Config {
1349 pub coordination: Option<Coordination>,
1351 pub agents: Vec<AgentSpec>,
1353 pub roles: Roles,
1355 pub graph: Graph,
1357 pub blind: Blind,
1359 pub verify: Verify,
1361 pub worktree: Worktree,
1363 pub disk: Disk,
1365 pub merge: Merge,
1367 pub update: Update,
1369 pub prompts: Prompts,
1371 pub notify: Notify,
1373 pub repos: Repos,
1376 pub talk: Talk,
1378 pub daemon: Daemon,
1380 pub release: Release,
1382 pub context_windows: BTreeMap<String, u64>,
1385}
1386
1387const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1397 ("claude-opus-4", 200_000),
1398 ("claude-sonnet-4", 200_000),
1399 ("claude-haiku-4", 200_000),
1400 ("claude-3", 200_000),
1401 ("opus", 200_000),
1402 ("sonnet", 200_000),
1403 ("haiku", 200_000),
1404 ("gpt-5", 400_000),
1405 ("gpt-4.1", 1_000_000),
1406 ("gpt-4o", 128_000),
1407 ("o3", 200_000),
1408 ("o4-mini", 200_000),
1409 ("gemini-2.5", 1_000_000),
1410 ("deepseek", 128_000),
1411];
1412
1413impl Config {
1414 pub fn context_window(&self, model: &str) -> Option<u64> {
1419 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1420 let mut best: Option<(usize, u64)> = None;
1421 for (key, window) in entries {
1422 if key == model {
1423 return Some(window);
1424 }
1425 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1426 best = Some((key.len(), window));
1427 }
1428 }
1429 best.map(|(_, w)| w)
1430 }
1431 lookup(
1432 model,
1433 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1434 )
1435 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1436 }
1437}
1438
1439#[derive(Debug, Clone, Deserialize, Serialize)]
1449#[serde(deny_unknown_fields, default)]
1450pub struct Daemon {
1451 pub max_concurrent_runs: usize,
1472 pub pause_for_interrupts: bool,
1488 pub max_deputies: usize,
1495 pub release_stall_minutes: u64,
1502}
1503
1504impl Default for Daemon {
1505 fn default() -> Self {
1506 Self {
1507 max_concurrent_runs: 1,
1508 pause_for_interrupts: false,
1509 max_deputies: 2,
1510 release_stall_minutes: 60,
1511 }
1512 }
1513}
1514
1515#[derive(Debug, Clone, Deserialize, Serialize)]
1527#[serde(deny_unknown_fields, default)]
1528pub struct Repos {
1529 pub roots: Vec<PathBuf>,
1533 pub auto_clone: bool,
1535 pub clone_command: Option<Vec<String>>,
1539 pub scan_ttl: u64,
1546 pub fetch_interval: u64,
1551}
1552
1553impl Default for Repos {
1554 fn default() -> Self {
1555 Self {
1556 roots: Vec::new(),
1557 auto_clone: false,
1558 clone_command: None,
1559 scan_ttl: 86_400,
1560 fetch_interval: 600,
1561 }
1562 }
1563}
1564
1565#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1581#[serde(deny_unknown_fields, default)]
1582pub struct Prompts {
1583 pub all: String,
1585 pub implement: String,
1587 pub judge: String,
1589 pub review: String,
1591 pub fix: String,
1593}
1594
1595impl Prompts {
1596 pub fn overlay(&self, node: &str) -> Option<String> {
1601 let specific = match node {
1602 "implement" => &self.implement,
1603 "judge" | "vote" | "deliberate" => &self.judge,
1604 "review" => &self.review,
1605 "fix" => &self.fix,
1606 _ => "",
1607 };
1608 let mut parts: Vec<&str> = Vec::new();
1609 for p in [self.all.trim(), specific.trim()] {
1610 if !p.is_empty() {
1611 parts.push(p);
1612 }
1613 }
1614 if parts.is_empty() {
1615 return None;
1616 }
1617 Some(parts.join("\n\n"))
1618 }
1619}
1620
1621#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1628#[serde(deny_unknown_fields, default)]
1629pub struct Notify {
1630 pub command: Vec<String>,
1633}
1634
1635#[derive(Debug, Clone, Deserialize, Serialize)]
1637#[serde(deny_unknown_fields, default)]
1638pub struct Talk {
1639 pub allow_write: bool,
1648 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1650 pub standing_authorization: bool,
1651 pub completion_chat: bool,
1656 pub personas: Vec<PersonaSpec>,
1661 pub operator_name: Option<String>,
1665}
1666
1667pub const OPERATOR_NAME_MAX: usize = 64;
1669
1670impl Default for Talk {
1671 fn default() -> Self {
1672 Self {
1673 allow_write: false,
1674 standing_authorization: false,
1675 completion_chat: true,
1676 personas: Vec::new(),
1677 operator_name: None,
1678 }
1679 }
1680}
1681
1682impl Talk {
1683 pub fn operator_name(&self) -> Option<&str> {
1685 self.operator_name
1686 .as_deref()
1687 .map(str::trim)
1688 .filter(|n| !n.is_empty())
1689 }
1690}
1691
1692#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1694#[serde(deny_unknown_fields)]
1695pub struct PersonaSpec {
1696 pub id: String,
1698 #[serde(default)]
1701 pub name: String,
1702 #[serde(default)]
1705 pub prompt: String,
1706 #[serde(default, skip_serializing_if = "Option::is_none")]
1710 pub icon: Option<String>,
1711}
1712
1713#[derive(Debug, Clone)]
1715pub struct ResolvedRoles {
1716 pub implementers: Vec<AgentSpec>,
1718 pub judges: Vec<AgentSpec>,
1720 pub reviewers: Vec<AgentSpec>,
1722 pub fixer: Option<Vec<AgentSpec>>,
1727 pub conductor: AgentSpec,
1729 pub implementer_roster: Vec<AgentSpec>,
1737 pub judge_roster: Vec<AgentSpec>,
1741 pub reviewer_roster: Vec<AgentSpec>,
1743}
1744
1745fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1752 let mut out = Vec::new();
1753 for (k, v) in table {
1754 if prefix.is_empty() && k == "vars" {
1755 continue;
1756 }
1757 let path = if prefix.is_empty() {
1758 k.clone()
1759 } else {
1760 format!("{prefix}.{k}")
1761 };
1762 match v {
1763 toml::Value::Array(_) => out.push(path),
1764 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1765 _ => {}
1766 }
1767 }
1768 out
1769}
1770
1771#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1773enum ArrayMerge {
1774 Append,
1778 Replace,
1781}
1782
1783fn array_merge_policy(key: &str) -> ArrayMerge {
1822 match key {
1823 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1824 _ => ArrayMerge::Replace,
1825 }
1826}
1827
1828impl Config {
1829 pub fn load(path: &Path) -> Result<Self> {
1832 Self::load_layers(&[path.to_path_buf()])
1833 }
1834
1835 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1845 let mut ctx = teravars::system_context();
1846 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1847 ctx.insert("env", &env);
1848 if let Some(last) = paths.last()
1849 && let Some(dir) = last.parent()
1850 {
1851 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1854 .map(|s| PathBuf::from(s.trim()))
1855 .unwrap_or_else(|_| dir.to_path_buf());
1856 ctx.insert("repo", &dir.to_string_lossy());
1857 ctx.insert(
1858 "repo_name",
1859 &dir.file_name().unwrap_or_default().to_string_lossy(),
1860 );
1861 }
1862 ctx
1863 }
1864
1865 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1873 Self::load_layers_with_machine(paths, Self::machine_layer())
1874 }
1875
1876 fn load_layers_with_machine(paths: &[PathBuf], machine: Option<PathBuf>) -> Result<Self> {
1877 let mut engine = teravars::Engine::default();
1878 let ctx = Self::render_ctx(paths);
1879 if paths.len() > 1 {
1880 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1881 if error.downcast_ref::<ConfigFailure>().is_some() {
1882 error
1883 } else {
1884 let message = error.to_string();
1887 error
1888 .context(ConfigFailure::layers("config-merge", paths))
1889 .context(message)
1890 }
1891 })?;
1892 }
1893 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1894 .map_err(|error| {
1895 let cause = ConfigFailure::render(&error, paths);
1896 anyhow::Error::new(error).context(cause)
1897 })
1898 .with_context(|| {
1899 format!(
1900 "rendering config via teravars: {}",
1901 paths
1902 .iter()
1903 .map(|p| p.display().to_string())
1904 .collect::<Vec<_>>()
1905 .join(", ")
1906 )
1907 })?;
1908 let mut table = merged.config;
1909 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1910 let standing = table
1913 .get_mut("talk")
1914 .and_then(toml::Value::as_table_mut)
1915 .and_then(|talk| talk.remove("standing_authorization"));
1916 let standing = if standing.is_some()
1917 && let Some(machine) = machine.filter(|machine| paths.contains(machine))
1918 {
1919 let machine_paths = [machine];
1920 let mut engine = teravars::Engine::default();
1921 let layer = teravars::load_merged(
1922 &machine_paths,
1923 &mut engine,
1924 &Self::render_ctx(&machine_paths),
1925 )
1926 .context("read machine standing authorization")?;
1927 layer
1928 .config
1929 .get("talk")
1930 .and_then(|talk| talk.get("standing_authorization"))
1931 .map(|value| {
1932 value.as_bool().context(
1933 "[talk] standing_authorization in the machine layer must be a boolean",
1934 )
1935 })
1936 .transpose()?
1937 .unwrap_or(false)
1938 } else {
1939 false
1940 };
1941 table.remove("vars");
1944 let detect_agents = !table.contains_key("agents");
1948 let mut cfg: Self = toml::Value::Table(table)
1949 .try_into()
1950 .context("deserializing magi config")
1951 .context(ConfigFailure::layers("config-deserialize", paths))?;
1952 cfg.talk.standing_authorization = standing;
1953 if !cfg.graph.question_routing {
1954 tracing::warn!(
1955 "[graph] question_routing is retired and ignored; task inquiries always use their chat"
1956 );
1957 }
1958 crate::persona::validate(&cfg.talk.personas)?;
1959 if let Some(own) = cfg.disk.reclaim_free_bytes
1960 && own < cfg.disk.min_free_bytes
1961 {
1962 tracing::warn!(
1963 "[disk] reclaim_free_bytes ({own}) is below min_free_bytes ({}); collection aims at min_free_bytes",
1964 cfg.disk.min_free_bytes
1965 );
1966 }
1967 cfg.worktree.validate()?;
1968 cfg.release.validate()?;
1969 if let Some(name) = cfg.talk.operator_name() {
1970 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1971 bail!(
1972 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1973 );
1974 }
1975 }
1976 if detect_agents {
1977 cfg.agents = Self::autodetected().agents;
1978 }
1979 Ok(cfg)
1980 }
1981
1982 fn normalize_renamed_keys(
1990 paths: &[PathBuf],
1991 engine: &mut teravars::Engine,
1992 ctx: &teravars::Context,
1993 table: &mut toml::map::Map<String, toml::Value>,
1994 ) -> Result<()> {
1995 let both = matches!(
1996 table.get("graph"),
1997 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1998 );
1999 if !both {
2000 return Ok(());
2001 }
2002 let mut winner: Option<toml::Value> = None;
2003 for path in paths {
2004 let one = teravars::load_merged([path], engine, ctx)
2005 .map_err(|error| {
2006 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
2007 anyhow::Error::new(error).context(cause)
2008 })
2009 .with_context(|| format!("rendering {}", path.display()))?;
2010 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
2011 continue;
2012 };
2013 if g.contains_key("candidates") && g.contains_key("implementers") {
2014 bail!(
2015 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
2016 path.display()
2017 );
2018 }
2019 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
2020 winner = Some(v.clone());
2021 }
2022 }
2023 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
2024 g.remove("candidates");
2025 if let Some(v) = winner {
2026 g.insert("implementers".to_owned(), v);
2027 }
2028 }
2029 Ok(())
2030 }
2031
2032 fn refuse_split_arrays(
2056 paths: &[PathBuf],
2057 engine: &mut teravars::Engine,
2058 ctx: &teravars::Context,
2059 ) -> Result<()> {
2060 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
2061 for path in paths {
2062 let one = teravars::load_merged([path], engine, ctx)
2063 .map_err(|error| {
2064 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
2065 anyhow::Error::new(error).context(cause)
2066 })
2067 .with_context(|| format!("rendering {}", path.display()))?;
2068 for key in array_keys(&one.config, "") {
2069 if array_merge_policy(&key) == ArrayMerge::Append {
2070 continue;
2071 }
2072 if let Some(first) = seen.get(&key) {
2073 bail!(
2074 "`{key}` is an array declared in two config layers:\n \
2075 {}\n {}\nteravars appends arrays when it merges, so \
2076 magi would run the concatenation of both - which is \
2077 not what either file says. Declare `{key}` in exactly \
2078 one of them.",
2079 first.display(),
2080 path.display()
2081 );
2082 }
2083 seen.insert(key, path.clone());
2084 }
2085 }
2086 Ok(())
2087 }
2088
2089 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
2111 let mut engine = teravars::Engine::default();
2112 let ctx = Self::render_ctx(paths);
2113 let mut out = Vec::new();
2114 for path in paths {
2115 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
2116 continue;
2117 };
2118 let mut cur = &one.config;
2119 let mut found = None;
2120 let parts: Vec<&str> = key.split('.').collect();
2121 for (i, part) in parts.iter().enumerate() {
2122 match cur.get(*part) {
2123 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
2124 found = Some(a);
2125 break;
2126 }
2127 Some(toml::Value::Table(t)) => cur = t,
2128 _ => break,
2129 }
2130 }
2131 let Some(values) = found else { continue };
2132 let strings: Vec<String> = values
2133 .iter()
2134 .filter_map(|v| v.as_str().map(str::to_owned))
2135 .collect();
2136 if !strings.is_empty() {
2137 out.push((path.clone(), strings));
2138 }
2139 }
2140 out
2141 }
2142
2143 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
2149 let mut engine = teravars::Engine::default();
2150 let ctx = Self::render_ctx(paths);
2151 paths
2152 .iter()
2153 .map(|path| {
2154 let one = teravars::load_merged([path], &mut engine, &ctx)
2155 .map(|m| m.config)
2156 .with_context(|| format!("rendering {}", path.display()));
2157 (path.clone(), one)
2158 })
2159 .collect()
2160 }
2161
2162 pub fn describe_composed(
2172 paths: &[PathBuf],
2173 commands: &[String],
2174 key: &str,
2175 empty: &str,
2176 ) -> String {
2177 if commands.is_empty() {
2178 return empty.to_owned();
2179 }
2180 let joined = commands.join(" && ");
2181 let provenance = Self::array_provenance(paths, key);
2182 if provenance.len() <= 1 {
2183 return joined;
2184 }
2185 let mut out = joined;
2186 for (path, cmds) in &provenance {
2187 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2188 }
2189 out
2190 }
2191
2192 #[track_caller]
2199 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2200 #[cfg(test)]
2201 crate::web::request_cost::discovery();
2202 tracing::trace!(
2203 caller = %std::panic::Location::caller(),
2204 explicit = explicit.is_some(),
2205 "discovering configuration"
2206 );
2207 if let Some(p) = explicit {
2208 let paths = vec![p.to_path_buf()];
2209 return Ok((Self::load_layers(&paths)?, paths));
2210 }
2211 let paths = Self::layers_checked(repo)?;
2212 if paths.is_empty() {
2213 return Ok((Self::autodetected(), paths));
2214 }
2215 Ok((Self::load_layers(&paths)?, paths))
2216 }
2217
2218 pub async fn discover_fetched(
2221 repo: &Path,
2222 explicit: Option<&Path>,
2223 ) -> Result<(Self, Vec<PathBuf>)> {
2224 if explicit.is_none() && is_git_repo(repo) {
2225 let (remote, cfg_base) = probe_remote_base(repo);
2229 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2230 .await
2231 .with_context(|| ConfigFailure {
2232 stage: "config-base",
2233 target: remote.clone(),
2234 })?;
2235 let out = crate::git::fetch(repo, &remote, &base)
2236 .await
2237 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2238 .with_context(|| ConfigFailure {
2239 stage: "config-fetch",
2240 target: format!("{remote}/{base}"),
2241 })?;
2242 if !out.ok() {
2243 return Err(anyhow::anyhow!(
2244 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2245 out.stderr.lines().next().unwrap_or("").trim()
2246 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2247 }
2248 if cfg_base.is_none() {
2249 crate::git::ensure_remote_head(repo, &remote, &base).await;
2250 }
2251 }
2252 Self::discover(repo, explicit).map_err(|error| {
2253 if error.downcast_ref::<ConfigFailure>().is_some() {
2254 error
2255 } else {
2256 error.context(ConfigFailure {
2257 stage: "config-load",
2258 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2259 })
2260 }
2261 })
2262 }
2263
2264 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2266 let mut paths: Vec<PathBuf> = Self::machine_layer()
2267 .into_iter()
2268 .filter(|p| p.is_file())
2269 .collect();
2270 paths.extend(Self::repo_layers(repo)?);
2271 Ok(paths)
2272 }
2273
2274 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2276 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2277 if let Some(root) = cached {
2278 let relative = path.strip_prefix(root).unwrap_or(path);
2279 let reference = resolve_remote_base(repo)
2280 .map(|(remote, base)| format!("{remote}/{base}"))
2281 .unwrap_or_else(|_| "remote base".to_owned());
2282 format!(
2283 "{} at {reference} (including its includes)",
2284 repo.join(relative).display()
2285 )
2286 } else {
2287 format!("{} (including its includes)", path.display())
2288 }
2289 }
2290
2291 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2294 match inspect_git_repo(repo) {
2295 RepoKind::NotGit => Ok(local_repo_layers(repo)),
2296 RepoKind::Found(dirs) => remote_layers_with_git(repo, Some(dirs)),
2297 RepoKind::Fallback => remote_layers_fallback(repo),
2298 }
2299 }
2300
2301 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2321
2322 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2327 let mut paths = Vec::new();
2328 paths.extend(Self::machine_layer());
2329 paths.push(repo.join(".magi").join("config.toml"));
2330 paths.push(repo.join("magi.toml"));
2331 paths.retain(|p| p.is_file());
2332 paths
2333 }
2334
2335 #[cfg(test)]
2342 pub(crate) fn machine_layer() -> Option<PathBuf> {
2343 std::env::var(Self::CONFIG_DIR_ENV)
2344 .ok()
2345 .filter(|dir| !dir.trim().is_empty())
2346 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2347 }
2348
2349 #[cfg(not(test))]
2351 pub(crate) fn machine_layer() -> Option<PathBuf> {
2352 match std::env::var(Self::CONFIG_DIR_ENV) {
2353 Ok(dir) if dir.trim().is_empty() => None,
2355 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2356 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2357 }
2358 }
2359
2360 pub fn autodetected() -> Self {
2362 let mut cfg = Self::default();
2363 for (kind, id, model) in [
2364 (AgentKind::Claude, "opus", Some("opus")),
2365 (AgentKind::Claude, "sonnet", Some("sonnet")),
2366 (AgentKind::Antigravity, "antigravity", None),
2367 (AgentKind::Opencode, "opencode", None),
2368 (AgentKind::Codex, "codex", None),
2369 (AgentKind::Omp, "omp", None),
2370 ] {
2371 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2372 cfg.agents.push(AgentSpec {
2373 id: id.to_owned(),
2374 kind,
2375 model: model.map(str::to_owned),
2376 command: Vec::new(),
2377 extra_args: Vec::new(),
2378 env: BTreeMap::new(),
2379 prompt_delivery: None,
2380 max_turn_secs: None,
2381 });
2382 }
2383 }
2384 cfg
2385 }
2386
2387 pub fn cache_dir(&self) -> Option<PathBuf> {
2390 self.verify.cache_dir()
2391 }
2392
2393 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2395 self.agents
2396 .iter()
2397 .find(|a| a.id == id)
2398 .with_context(|| format!("no agent with id `{id}` in the roster"))
2399 }
2400
2401 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2408 let mut out = Vec::with_capacity(count);
2409 for i in 0..count {
2410 let spec = if ids.is_empty() {
2411 self.agents[(i + offset) % self.agents.len()].clone()
2412 } else {
2413 self.agent(&ids[i % ids.len()])?.clone()
2414 };
2415 out.push(spec);
2416 }
2417 Ok(out)
2418 }
2419
2420 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2427 if ids.is_empty() {
2428 Ok(self.agents.clone())
2429 } else {
2430 ids.iter().map(|id| self.agent(id).cloned()).collect()
2431 }
2432 }
2433
2434 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2441 if self.agents.is_empty() {
2442 bail!(
2443 "agent roster is empty: no agent CLI found on PATH and no \
2444 [[agents]] in the config. Run `magi init` to write a starter \
2445 magi.toml."
2446 );
2447 }
2448 let pinned = self
2449 .graph
2450 .selected_implementer
2451 .as_ref()
2452 .map(|id| self.agent(id).cloned())
2453 .transpose()?;
2454 Ok(ResolvedRoles {
2455 implementers: match &pinned {
2456 Some(agent) => vec![agent.clone()],
2457 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2458 },
2459 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2460 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2461 fixer: match self.roles.fixer.as_ref() {
2462 Some(choice) => Some(crate::agent::pick_chain(
2465 &self.agents,
2466 Some(choice),
2467 &|_| true,
2468 "fixer",
2469 )?),
2470 None => None,
2471 },
2472 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2477 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2478 Some(ids) if !ids.is_empty() => ids
2481 .iter()
2482 .find_map(|id| self.agent(id).ok())
2483 .cloned()
2484 .with_context(|| {
2485 format!("[roles] conductor names no agent in the roster: {ids:?}")
2486 })?,
2487 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2492 .unwrap_or_else(|_| self.agents[0].clone()),
2493 },
2494 implementer_roster: match pinned {
2495 Some(agent) => vec![agent],
2496 None => self.full_roster(&self.roles.implementers)?,
2497 },
2498 judge_roster: self.full_roster(&self.roles.judges)?,
2499 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2500 })
2501 }
2502
2503 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2525 if self.agents.is_empty() {
2526 bail!(
2527 "agent roster is empty: no agent CLI found on PATH and no \
2528 [[agents]] in the config. Run `magi init` to write a starter \
2529 magi.toml."
2530 );
2531 }
2532 if !self.roles.advisors.is_empty() {
2533 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2534 }
2535 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2536 }
2537
2538 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2542 if self.roles.advisors.is_empty() {
2543 self.full_roster(&self.roles.judges)
2544 } else {
2545 self.full_roster(&self.roles.advisors)
2546 }
2547 }
2548
2549 pub fn shell(&self) -> Vec<String> {
2551 if let Some(s) = &self.verify.shell {
2552 return s.clone();
2553 }
2554 if which("sh") {
2555 vec!["sh".to_owned(), "-c".to_owned()]
2556 } else {
2557 vec!["cmd".to_owned(), "/C".to_owned()]
2558 }
2559 }
2560
2561 pub fn starter_toml() -> String {
2563 let detected = Self::autodetected();
2564 let mut s = String::from(
2565 "# magi — blind multi-agent implementation competition.\n\
2566 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2567 # -> blind judging -> deliberation -> private final vote\n\
2568 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2569 #\n\
2570 # Rendered by teravars: a `[vars]` table, env\n\
2571 # and system lookups, and `include = [...]` all work. Tera\n\
2572 # braces are live everywhere in this file, but comments are\n\
2573 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2574 # may quote `{{ ... }}` freely.\n\
2575 #\n\
2576 # Layers deep-merge in increasing\n\
2577 # precedence, so the roster can live once per machine in\n\
2578 # <config_dir>/magi/config.toml and each repo only states its own\n\
2579 # gate:\n\
2580 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2581 [vars]\n\
2582 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2583 # Single quotes inside the braces: teravars renders the raw file\n\
2584 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2585 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2586 );
2587 if detected.agents.is_empty() {
2588 s.push_str(
2589 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2590 # kind = claude | opencode | antigravity | codex | command\n\
2591 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2592 );
2593 } else {
2594 for a in &detected.agents {
2595 s.push_str("[[agents]]\n");
2596 s.push_str(&format!("id = {:?}\n", a.id));
2597 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2598 if let Some(m) = &a.model {
2599 s.push_str(&format!("model = {m:?}\n"));
2600 }
2601 s.push('\n');
2602 }
2603 }
2604 s.push_str(
2605 "# Leave a role list empty to rotate through the roster.\n\
2606 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2607 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2608 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2609 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2610 [roles]\n\
2611 implementers = []\n\
2612 judges = []\n\
2613 reviewers = []\n\
2614 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2615 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2616 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2617 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2618 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2619 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2620 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2621 [graph]\n\
2622 # Gate GitHub prose; secret redaction is always enabled.\n\
2623 github_text_guard = true\n\
2624 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2625 github_language = \"en\"\n\
2626 implementers = 3\n\
2627 judges = 3\n\
2628 deliberate_rounds = 1\n\
2629 reviewers = 3\n\
2630 review_rounds = 6\n\
2631 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2632 gate_fix_rounds = 1\n\
2633 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2634 rerun_flaky_checks = true\n\
2635 # 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\
2636 rerun_failed_e2e = true\n\
2637 # Port the strengths judges named in the losing candidates onto the\n\
2638 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2639 graft_runner_up = true\n\
2640 max_parallel = 4\n\
2641 language = \"en\"\n\
2642 # One CLI conversation per seat: judges keep their own argument\n\
2643 # across deliberation, the fixer keeps its implementation context.\n\
2644 sessions = true\n\
2645 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2646 # the final gate inherit this value for compatibility.\n\
2647 timeout_review = 1200\n\
2648 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2649 # verification independent if timeout_review changes later.\n\
2650 # timeout_verify = 1200\n\
2651 # Longest a seat waits for the shared build cache before it is\n\
2652 # spawned. Never counted against an agent's own timeout; expiry\n\
2653 # holds the run (resumable) instead of failing the agent.\n\
2654 # timeout_resource_wait = 1800\n\n\
2655 # What the chat calls you (persona address and the Chat's turn label).\n\
2656 # [talk]\n\
2657 # standing_authorization = false # machine layer only; bounded chat recovery\n\
2658 # completion_chat = true # report human/issue-filed task completion to its task chat\n\
2659 # operator_name = \"Commander\"\n\n\
2660 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2661 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2662 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2663 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2664 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2665 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2666 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2667 # [[talk.personas]]\n\
2668 # id = \"gendo\"\n\
2669 # name = \"Gendo Ikari\"\n\
2670 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2671 # icon = \"~/pictures/gendo.png\"\n\n\
2672 [verify]\n\
2673 # Run once per review round in the winner's worktree; failures are\n\
2674 # fed back to the fixer.\n\
2675 e2e = []\n\
2676 # Final gate. Every command must exit 0 before a merge.\n\
2677 gate = []\n\
2678 # Mechanical fixers (formatters) run in the winner's worktree before\n\
2679 # e2e and before the gate; whatever they change becomes one commit. A\n\
2680 # failing command only warns - the gate stays the arbiter. Same timeout\n\
2681 # as the gate (timeout_verify). Keep it light and idempotent.\n\
2682 # pre_gate = []\n\n\
2683 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2684 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2685 # before any agent or verify command touches it. `copy` reads from the\n\
2686 # primary checkout and never overwrites; `optional` skips a missing\n\
2687 # source. `run` goes through the shell with the worktree as cwd and\n\
2688 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2689 # the verify timeout). Setup must not edit tracked files, and what it\n\
2690 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2691 # layer only.\n\
2692 # [worktree]\n\
2693 # setup = [\n\
2694 # { copy = \".env.example -> .env\" },\n\
2695 # { copy = \".env.local\", optional = true },\n\
2696 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2697 # ]\n\
2698 # pre_clean = [] # Repeatable cleanup before owned clean -fdx.\n\n\
2699 [merge]\n\
2700 # none | local | pr\n\
2701 mode = \"none\"\n\
2702 # expected (default) | none. Set none only in repository config without CI.\n\
2703 # Ignores all check statuses; reviews and approval still apply.\n\
2704 # ci = \"expected\"\n\
2705 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2706 [update]\n\
2707 # off | notify | install — checked in the background, throttled.\n\
2708 mode = \"notify\"\n\
2709 # interval = \"24h\"\n\n\
2710 # Opt-in: magi web updates and restarts automatically when a newer release is found.\n\
2711 # auto_restart = false\n\
2712 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2713 # Handover drains only short admission transactions; active workers continue\n\
2714 # on their original executable generation while new work uses the new one.\n\
2715 # Standalone magi serve cannot restart.\n\
2716 # Failed tags are skipped until process restart or a different tag.\n\
2717 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2718 [daemon]\n\
2719 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2720 # no new commit and no check changing state before `magi serve`\n\
2721 # notices and asks you. A failed check is rerun once on its own;\n\
2722 # still red after that escalates at once. 0 turns the watcher off.\n\
2723 # release_stall_minutes = 60\n\n\
2724 [release]\n\
2725 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2726 # Actions never run (private, no minutes): the release pull request\n\
2727 # does not wait for CI, you approve the merge in magi, and then\n\
2728 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2729 # runs `commands` from a clean checkout of the merge commit. A\n\
2730 # failure holds the release with a notice; it is never retried blind.\n\
2731 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2732 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2733 # mode = \"actions\"\n\
2734 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2735 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2736 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2737 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2738 # timeout_minutes = 30\n\
2739 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2740 # The first entry is the version of record and must be the file the\n\
2741 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2742 # rewritten to the same version. Paths are relative to the repository\n\
2743 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2744 # is not touched.\n\
2745 # version_files = [\n\
2746 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2747 # { path = \"package.json\", kind = \"json\" },\n\
2748 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2749 # ]\n",
2750 );
2751 s
2752 }
2753}
2754
2755pub fn which(program: &str) -> bool {
2757 find_program(program).is_some()
2758}
2759
2760pub fn find_program(program: &str) -> Option<PathBuf> {
2769 find_program_on(program, &std::env::var_os("PATH")?)
2770}
2771
2772pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2775 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2776 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2777}
2778
2779fn find_program_in(
2780 program: &str,
2781 paths: &std::ffi::OsStr,
2782 pathext: Option<&str>,
2783) -> Option<PathBuf> {
2784 let p = Path::new(program);
2785 if p.components().count() > 1 {
2786 return p.is_file().then(|| p.to_path_buf());
2787 }
2788 std::env::split_paths(paths).find_map(|dir| match pathext {
2789 Some(exts) => {
2790 let bare = dir.join(program);
2791 if p.extension().is_some() && bare.is_file() {
2792 return Some(bare);
2793 }
2794 exts.split(';')
2795 .filter(|e| !e.is_empty())
2796 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2797 .find(|c| c.is_file())
2798 }
2799 None => Some(dir.join(program)).filter(|c| c.is_file()),
2800 })
2801}
2802
2803const REPO_MARKER: &str = ".magi-repo";
2805
2806const CACHE_MANIFEST: &str = ".magi-cache-manifest.json";
2809const CACHE_MANIFEST_VERSION: u32 = 3;
2810const REPO_LAYER_RELS: [&str; 2] = [".magi/config.toml", "magi.toml"];
2811
2812const GIT_OVERRIDE_ENVS: &[&str] = &[
2816 "GIT_DIR",
2817 "GIT_COMMON_DIR",
2818 "GIT_WORK_TREE",
2819 "GIT_OBJECT_DIRECTORY",
2820 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
2821 "GIT_CEILING_DIRECTORIES",
2822 "GIT_DISCOVERY_ACROSS_FILESYSTEM",
2823 "GIT_NAMESPACE",
2824];
2825
2826fn has_git_env_override() -> bool {
2827 GIT_OVERRIDE_ENVS
2828 .iter()
2829 .any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))
2830}
2831
2832#[derive(Debug, Clone)]
2833struct GitDirs {
2834 common_dir: PathBuf,
2835 files_ref_backend: bool,
2836}
2837
2838#[derive(Debug, Clone)]
2839enum RepoKind {
2840 NotGit,
2841 Found(GitDirs),
2842 Fallback,
2843}
2844
2845fn local_repo_layers(repo: &Path) -> Vec<PathBuf> {
2846 [
2847 repo.join(".magi").join("config.toml"),
2848 repo.join("magi.toml"),
2849 ]
2850 .into_iter()
2851 .filter(|p| p.is_file())
2852 .collect()
2853}
2854
2855fn inspect_git_repo(repo: &Path) -> RepoKind {
2856 if has_git_env_override() || !repo.is_dir() {
2857 return RepoKind::Fallback;
2858 }
2859 let start = match repo.canonicalize() {
2860 Ok(p) => p,
2861 Err(_) => {
2862 if repo.is_absolute() {
2863 repo.to_path_buf()
2864 } else {
2865 match std::env::current_dir() {
2866 Ok(cwd) => cwd.join(repo),
2867 Err(_) => return RepoKind::Fallback,
2868 }
2869 }
2870 }
2871 };
2872
2873 for dir in start.ancestors() {
2874 let dot_git = dir.join(".git");
2875 match std::fs::symlink_metadata(&dot_git) {
2876 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2877 if dir.join("HEAD").is_file()
2880 && dir.join("objects").is_dir()
2881 && (dir.join("refs").is_dir() || dir.join("reftable").is_dir())
2882 {
2883 return RepoKind::Fallback;
2884 }
2885 continue;
2886 }
2887 Err(_) => return RepoKind::Fallback,
2888 Ok(meta) => {
2889 if meta.file_type().is_symlink() {
2890 return RepoKind::Fallback;
2891 }
2892 let git_dir = if meta.is_dir() {
2893 if !dot_git.join("HEAD").is_file() {
2894 return RepoKind::Fallback;
2895 }
2896 dot_git
2897 } else if meta.is_file() {
2898 let Ok(raw) = std::fs::read_to_string(&dot_git) else {
2899 return RepoKind::Fallback;
2900 };
2901 let Some(target) = raw
2902 .trim_end_matches(['\r', '\n'])
2903 .strip_prefix("gitdir:")
2904 .map(str::trim)
2905 .filter(|s| !s.is_empty())
2906 else {
2907 return RepoKind::Fallback;
2908 };
2909 let target_path = PathBuf::from(target);
2910 let resolved = if target_path.is_absolute() {
2911 target_path
2912 } else {
2913 dir.join(target_path)
2914 };
2915 if !resolved.is_dir() || !resolved.join("HEAD").is_file() {
2916 return RepoKind::Fallback;
2917 }
2918 resolved
2919 } else {
2920 return RepoKind::Fallback;
2921 };
2922
2923 let commondir_file = git_dir.join("commondir");
2924 let common_dir = match std::fs::symlink_metadata(&commondir_file) {
2925 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2926 git_dir.canonicalize().unwrap_or(git_dir)
2927 }
2928 Ok(m) if m.is_file() => {
2929 let Ok(raw) = std::fs::read_to_string(&commondir_file) else {
2930 return RepoKind::Fallback;
2931 };
2932 let target = raw.trim();
2933 if target.is_empty() {
2934 return RepoKind::Fallback;
2935 }
2936 let target_path = PathBuf::from(target);
2937 let joined = if target_path.is_absolute() {
2938 target_path
2939 } else {
2940 git_dir.join(target_path)
2941 };
2942 let Ok(canonical) = joined.canonicalize() else {
2943 return RepoKind::Fallback;
2944 };
2945 if !canonical.is_dir() {
2946 return RepoKind::Fallback;
2947 }
2948 canonical
2949 }
2950 _ => return RepoKind::Fallback,
2951 };
2952
2953 let files_ref_backend = is_standard_files_ref_backend(&common_dir);
2954 return RepoKind::Found(GitDirs {
2955 common_dir,
2956 files_ref_backend,
2957 });
2958 }
2959 }
2960 }
2961 RepoKind::NotGit
2962}
2963
2964fn is_git_repo(repo: &Path) -> bool {
2965 match inspect_git_repo(repo) {
2966 RepoKind::NotGit => false,
2967 RepoKind::Found(_) => true,
2968 RepoKind::Fallback => is_git_worktree(repo),
2969 }
2970}
2971
2972fn strip_git_config_value(raw: &str) -> String {
2973 let mut out = String::new();
2974 let mut in_quotes = false;
2975 let mut escaped = false;
2976 for ch in raw.chars() {
2977 if escaped {
2978 out.push(ch);
2979 escaped = false;
2980 continue;
2981 }
2982 if in_quotes {
2983 match ch {
2984 '\\' => escaped = true,
2985 '"' => in_quotes = false,
2986 _ => out.push(ch),
2987 }
2988 continue;
2989 }
2990 match ch {
2991 '"' => in_quotes = true,
2992 '#' | ';' => break,
2993 _ => out.push(ch),
2994 }
2995 }
2996 out.trim().to_owned()
2997}
2998
2999fn is_standard_files_ref_backend(common_dir: &Path) -> bool {
3003 if common_dir.join("reftable").exists() || !common_dir.join("refs").is_dir() {
3004 return false;
3005 }
3006 let Ok(config) = std::fs::read_to_string(common_dir.join("config")) else {
3007 return false;
3008 };
3009 let mut section = String::new();
3010 for raw_line in config.lines() {
3011 let line = raw_line.trim();
3012 if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
3013 continue;
3014 }
3015 if line.ends_with('\\') {
3016 return false;
3017 }
3018 if let Some(rest) = line.strip_prefix('[') {
3019 let Some(end) = rest.find(']') else {
3020 return false;
3021 };
3022 let trailing = rest[end + 1..].trim();
3023 if !trailing.is_empty() && !trailing.starts_with('#') && !trailing.starts_with(';') {
3024 return false;
3025 }
3026 let header = &rest[..end];
3027 section = header
3028 .split(|c: char| c.is_ascii_whitespace() || c == '"')
3029 .next()
3030 .unwrap_or("")
3031 .to_ascii_lowercase();
3032 if matches!(section.as_str(), "include" | "includeif") {
3033 return false;
3034 }
3035 continue;
3036 }
3037 let (key, val) = match line.split_once('=') {
3038 Some((k, v)) => (
3039 k.trim().to_ascii_lowercase(),
3040 strip_git_config_value(v).to_ascii_lowercase(),
3041 ),
3042 None => (
3043 strip_git_config_value(line).to_ascii_lowercase(),
3044 "true".to_owned(),
3045 ),
3046 };
3047 match section.as_str() {
3048 "core" if key == "repositoryformatversion" => {
3049 if !matches!(val.as_str(), "0" | "1") {
3050 return false;
3051 }
3052 }
3053 "extensions" => match key.as_str() {
3054 "refstorage" if val == "files" => {}
3055 "objectformat" if val == "sha1" => {}
3056 "worktreeconfig" | "relativeworktrees" | "partialclone" | "promisor"
3057 | "preciousobjects" | "noop" | "manyfiles" => {}
3058 _ => return false,
3059 },
3060 _ => {}
3061 }
3062 }
3063 true
3064}
3065
3066fn is_safe_ref_name(name: &str) -> bool {
3067 if !name.starts_with("refs/")
3068 || name.ends_with('/')
3069 || name.starts_with("refs/bisect/")
3070 || name.starts_with("refs/worktree/")
3071 || name.starts_with("refs/rewritten/")
3072 {
3073 return false;
3074 }
3075 name.split('/').all(|part| {
3076 !part.is_empty()
3077 && part != "."
3078 && part != ".."
3079 && !part.contains('\\')
3080 && !part.bytes().any(|b| b <= 0x20 || b == 0x7f)
3081 })
3082}
3083
3084fn join_rel_path(base: &Path, rel: &str) -> PathBuf {
3085 let mut path = base.to_path_buf();
3086 for part in rel.split('/') {
3087 path.push(part);
3088 }
3089 path
3090}
3091
3092fn is_sha1_hex(s: &str) -> bool {
3093 s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
3094}
3095
3096fn is_hex_oid(s: &str) -> bool {
3097 (s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
3098}
3099
3100enum LooseRef {
3101 Missing,
3102 Oid(String),
3103 Symref(String),
3104 Unknown,
3105}
3106
3107fn read_loose_ref(common_dir: &Path, ref_name: &str) -> LooseRef {
3108 if !is_safe_ref_name(ref_name) {
3109 return LooseRef::Unknown;
3110 }
3111 let path = join_rel_path(common_dir, ref_name);
3112 match std::fs::symlink_metadata(&path) {
3113 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return LooseRef::Missing,
3114 Err(_) => return LooseRef::Unknown,
3115 Ok(meta) if !meta.is_file() => return LooseRef::Unknown,
3116 Ok(_) => {}
3117 }
3118 match std::fs::read_to_string(&path) {
3119 Err(e) if e.kind() == std::io::ErrorKind::NotFound => LooseRef::Missing,
3120 Err(_) => LooseRef::Unknown,
3121 Ok(raw) => {
3122 let trimmed = raw.trim();
3123 if let Some(target) = trimmed.strip_prefix("ref:") {
3124 let target = target.trim();
3125 if is_safe_ref_name(target) {
3126 LooseRef::Symref(target.to_owned())
3127 } else {
3128 LooseRef::Unknown
3129 }
3130 } else if is_sha1_hex(trimmed) {
3131 LooseRef::Oid(trimmed.to_ascii_lowercase())
3132 } else {
3133 LooseRef::Unknown
3134 }
3135 }
3136 }
3137}
3138
3139enum PackedRef {
3140 Missing,
3141 Oid(String),
3142 Unknown,
3143}
3144
3145fn read_packed_ref(common_dir: &Path, ref_name: &str) -> PackedRef {
3146 let raw = match std::fs::read_to_string(common_dir.join("packed-refs")) {
3147 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return PackedRef::Missing,
3148 Err(_) => return PackedRef::Unknown,
3149 Ok(raw) => raw,
3150 };
3151 let mut lines = raw.lines().peekable();
3152 while let Some(line) = lines.next() {
3153 let line = line.trim_end_matches('\r');
3154 if line.is_empty() || line.starts_with('#') || line.starts_with('^') {
3155 continue;
3156 }
3157 let Some((oid, name)) = line.split_once(' ') else {
3158 return PackedRef::Unknown;
3159 };
3160 if name == ref_name {
3161 if !is_sha1_hex(oid) {
3162 return PackedRef::Unknown;
3163 }
3164 if lines
3165 .peek()
3166 .is_some_and(|next| next.trim_end_matches('\r').starts_with('^'))
3167 {
3168 return PackedRef::Unknown;
3170 }
3171 return PackedRef::Oid(oid.to_ascii_lowercase());
3172 }
3173 }
3174 PackedRef::Missing
3175}
3176
3177fn resolve_remote_head_files(common_dir: &Path, remote: &str) -> Option<String> {
3178 let head = format!("refs/remotes/{remote}/HEAD");
3179 match read_loose_ref(common_dir, &head) {
3180 LooseRef::Symref(target) => crate::git::remote_head_branch(remote, &target),
3181 _ => None,
3182 }
3183}
3184
3185fn resolve_ref_oid_files(common_dir: &Path, start_ref: &str) -> Option<String> {
3186 let mut current = start_ref.to_owned();
3187 for _ in 0..8 {
3188 match read_loose_ref(common_dir, ¤t) {
3189 LooseRef::Oid(oid) => return Some(oid),
3190 LooseRef::Symref(next) => current = next,
3191 LooseRef::Missing => {
3192 return match read_packed_ref(common_dir, ¤t) {
3193 PackedRef::Oid(oid) => Some(oid),
3194 PackedRef::Missing | PackedRef::Unknown => None,
3195 };
3196 }
3197 LooseRef::Unknown => return None,
3198 }
3199 }
3200 None
3201}
3202
3203fn repository_git() -> std::process::Command {
3204 #[cfg(test)]
3205 crate::web::request_cost::git();
3206 let mut command = std::process::Command::new("git");
3207 command.arg("--no-replace-objects");
3208 command
3209}
3210
3211fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
3212 use crate::proc::Quiet as _;
3213 let out = repository_git()
3214 .args(args)
3215 .quiet()
3216 .current_dir(repo)
3217 .stdin(std::process::Stdio::null())
3218 .output()
3219 .ok()?;
3220 out.status
3221 .success()
3222 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
3223}
3224
3225fn is_git_worktree(repo: &Path) -> bool {
3228 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
3229}
3230
3231#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3234pub enum OwnerHold {
3235 LandApproval,
3237 HoldContestedMerge,
3239}
3240
3241impl OwnerHold {
3242 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
3244
3245 pub fn key(self) -> &'static str {
3247 match self {
3248 Self::LandApproval => "land_approval",
3249 Self::HoldContestedMerge => "hold_contested_merge",
3250 }
3251 }
3252
3253 pub fn base_value(self, graph: &Graph) -> bool {
3255 match self {
3256 Self::LandApproval => graph.land_approval,
3257 Self::HoldContestedMerge => graph.hold_contested_merge,
3258 }
3259 }
3260}
3261
3262pub async fn branch_owner_holds(
3265 repo: &Path,
3266 head: &str,
3267) -> (Vec<(OwnerHold, String)>, Vec<String>) {
3268 let mut holds = Vec::new();
3269 let mut diagnostics = Vec::new();
3270 if let Err(error) =
3273 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
3274 {
3275 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
3276 return (holds, diagnostics);
3277 }
3278 for file in ["magi.toml", ".magi/config.toml"] {
3279 let object = format!("{head}:{file}");
3280 let text = match crate::git::git(repo, &["show", &object]).await {
3281 Ok(text) => text,
3282 Err(error) => {
3283 let error = format!("{error:#}");
3285 if !error.contains("does not exist in")
3286 && !error.contains("exists on disk, but not in")
3287 {
3288 diagnostics.push(format!(
3289 "cannot read reviewed branch {file} at {head}: {error}"
3290 ));
3291 }
3292 continue;
3293 }
3294 };
3295 let value = match toml::from_str::<toml::Value>(&text) {
3296 Ok(value) => value,
3297 Err(error) => {
3298 diagnostics.push(format!(
3299 "cannot parse reviewed branch {file} at {head}: {error}"
3300 ));
3301 continue;
3302 }
3303 };
3304 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
3305 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
3306 }
3307 for hold in OwnerHold::ALL {
3308 if value
3309 .get("graph")
3310 .and_then(|g| g.get(hold.key()))
3311 .and_then(toml::Value::as_bool)
3312 == Some(true)
3313 {
3314 holds.push((hold, file.to_owned()));
3315 }
3316 }
3317 }
3318 (holds, diagnostics)
3319}
3320
3321#[derive(Deserialize, Default)]
3322struct ProbeMerge {
3323 base: Option<String>,
3324 remote: Option<String>,
3325}
3326
3327#[derive(Deserialize, Default)]
3328struct Probe {
3329 merge: Option<ProbeMerge>,
3330}
3331
3332fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
3338 if !path.is_file() {
3339 return None;
3340 }
3341 let paths = [path.to_path_buf()];
3342 let mut engine = teravars::Engine::default();
3343 let mut ctx = Config::render_ctx(&paths);
3344 ctx.insert("repo", &repo.to_string_lossy());
3347 ctx.insert(
3348 "repo_name",
3349 &repo.file_name().unwrap_or_default().to_string_lossy(),
3350 );
3351 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
3352 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
3353 {
3354 return probe.merge;
3355 }
3356 let text = std::fs::read_to_string(path).ok()?;
3357 toml::from_str::<Probe>(&text).ok()?.merge
3358}
3359
3360fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
3362 let mut remote = None;
3363 let mut base = None;
3364 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
3365 sources.push(repo.join("magi.toml"));
3366 sources.push(repo.join(".magi").join("config.toml"));
3367 for path in sources {
3368 if let Some(m) = probe_merge(&path, repo) {
3369 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
3370 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
3371 }
3372 }
3373 (remote.unwrap_or_else(|| "origin".to_owned()), base)
3374}
3375
3376fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
3378 let (remote, base) = probe_remote_base(repo);
3379 let base = match base {
3380 Some(b) => b,
3381 None => {
3382 let from_files = match inspect_git_repo(repo) {
3383 RepoKind::Found(dirs) if dirs.files_ref_backend => {
3384 resolve_remote_head_files(&dirs.common_dir, &remote)
3385 }
3386 _ => None,
3387 };
3388 match from_files {
3389 Some(b) => b,
3390 None => {
3391 let head = format!("refs/remotes/{remote}/HEAD");
3392 git_out(repo, &["symbolic-ref", "--quiet", &head])
3393 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
3394 .with_context(|| missing_remote_head_msg(&remote))?
3395 }
3396 }
3397 }
3398 };
3399 Ok((remote, base))
3400}
3401
3402fn missing_remote_head_msg(remote: &str) -> String {
3403 format!(
3404 "cannot tell which branch of `{remote}` holds magi.toml: \
3405 set [merge] base, or run `git remote set-head {remote} -a`"
3406 )
3407}
3408
3409fn missing_tracking_ref_msg(remote: &str, base: &str) -> String {
3410 format!(
3411 "`{remote}/{base}` does not exist in this checkout; fetch it \
3412 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
3413 a possibly stale local magi.toml instead"
3414 )
3415}
3416
3417fn fnv_hex(text: &str) -> String {
3418 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
3419 for b in text.bytes() {
3420 hash ^= u64::from(b);
3421 hash = hash.wrapping_mul(0x0100_0000_01b3);
3422 }
3423 format!("{hash:016x}")
3424}
3425
3426fn declares_include(text: &str) -> bool {
3432 match toml::from_str::<toml::Table>(text) {
3433 Ok(table) => {
3434 table.contains_key("include")
3435 || table
3436 .get("teravars")
3437 .and_then(toml::Value::as_table)
3438 .is_some_and(|t| t.contains_key("include"))
3439 }
3440 Err(_) => text.contains("include"),
3441 }
3442}
3443
3444fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
3447 use crate::proc::Quiet as _;
3448 let mut archive = repository_git()
3449 .args(["archive", "--format=tar", sha])
3450 .quiet()
3451 .current_dir(repo)
3452 .stdin(std::process::Stdio::null())
3453 .stdout(std::process::Stdio::piped())
3454 .stderr(std::process::Stdio::null())
3455 .spawn()
3456 .context("running git archive")?;
3457 let tar = std::process::Command::new("tar")
3458 .arg("-x")
3459 .arg("-C")
3460 .arg(dest)
3461 .quiet()
3462 .stdin(archive.stdout.take().context("git archive has no stdout")?)
3463 .output()
3464 .context("running tar")?;
3465 let status = archive.wait().context("waiting for git archive")?;
3466 if !status.success() || !tar.status.success() {
3467 bail!(
3468 "cannot unpack {sha} for the config's includes: {}",
3469 String::from_utf8_lossy(&tar.stderr).trim()
3470 );
3471 }
3472 Ok(())
3473}
3474
3475fn write_extracted(path: &Path, bytes: impl AsRef<[u8]>) -> Result<()> {
3476 use std::io::Write as _;
3477 match std::fs::remove_file(path) {
3478 Ok(()) => {}
3479 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
3480 Err(e) => return Err(e.into()),
3481 }
3482 std::fs::File::create_new(path)?.write_all(bytes.as_ref())?;
3483 Ok(())
3484}
3485
3486#[derive(Debug, Serialize, Deserialize)]
3487struct CacheManifest {
3488 version: u32,
3489 sha: String,
3490 repo: String,
3491 layers: Vec<String>,
3492 extracted_tree: bool,
3493}
3494
3495fn read_cached_layers(dir: &Path, sha: &str, repo: &Path) -> Option<Vec<PathBuf>> {
3496 let raw = std::fs::read(dir.join(CACHE_MANIFEST)).ok()?;
3497 let manifest: CacheManifest = serde_json::from_slice(&raw).ok()?;
3498 if manifest.version != CACHE_MANIFEST_VERSION
3499 || manifest.sha != sha
3500 || manifest.repo != repo.to_string_lossy()
3501 || manifest.layers.len() > REPO_LAYER_RELS.len()
3502 {
3503 return None;
3504 }
3505 let mut out = Vec::with_capacity(manifest.layers.len());
3506 let mut last_idx: Option<usize> = None;
3507 for rel in &manifest.layers {
3508 let idx = REPO_LAYER_RELS.iter().position(|allowed| *allowed == rel)?;
3509 if last_idx.is_some_and(|prev| idx <= prev) {
3510 return None;
3511 }
3512 last_idx = Some(idx);
3513 let file = join_rel_path(dir, rel);
3514 if !file.is_file() || !file.parent().is_some_and(|p| p.join(REPO_MARKER).is_file()) {
3515 return None;
3516 }
3517 out.push(file);
3518 }
3519 Some(out)
3520}
3521
3522enum BatchEntry {
3523 Missing,
3524 Object {
3525 oid: String,
3526 kind: String,
3527 content: Vec<u8>,
3528 },
3529}
3530
3531fn parse_cat_file_batch(mut buf: &[u8], expected: usize) -> Result<Vec<BatchEntry>> {
3532 let mut entries = Vec::with_capacity(expected);
3533 for _ in 0..expected {
3534 let Some(nl) = buf.iter().position(|&b| b == b'\n') else {
3535 bail!("unexpected EOF in git cat-file --batch header");
3536 };
3537 let line = std::str::from_utf8(&buf[..nl])
3538 .context("non-UTF-8 git cat-file --batch header")?
3539 .trim_end_matches('\r');
3540 buf = &buf[nl + 1..];
3541 if line.ends_with(" missing") || line.ends_with(" ambiguous") {
3542 entries.push(BatchEntry::Missing);
3543 continue;
3544 }
3545 let mut parts = line.split_whitespace();
3546 let (Some(oid), Some(kind), Some(size_str), None) =
3547 (parts.next(), parts.next(), parts.next(), parts.next())
3548 else {
3549 bail!("unexpected git cat-file --batch header: {line}");
3550 };
3551 let size: usize = size_str
3552 .parse()
3553 .with_context(|| format!("invalid git cat-file --batch size: {size_str}"))?;
3554 if buf.len() < size + 1 || buf[size] != b'\n' {
3555 bail!("truncated git cat-file --batch body for {oid}");
3556 }
3557 let content = buf[..size].to_vec();
3558 buf = &buf[size + 1..];
3559 entries.push(BatchEntry::Object {
3560 oid: oid.to_owned(),
3561 kind: kind.to_owned(),
3562 content,
3563 });
3564 }
3565 Ok(entries)
3566}
3567
3568fn read_commit_layers_batch(
3571 repo: &Path,
3572 sha: &str,
3573 remote: &str,
3574 base: &str,
3575) -> Result<(String, Vec<(&'static str, String)>)> {
3576 use crate::proc::Quiet as _;
3577 use std::io::Write as _;
3578
3579 let mut child = repository_git()
3580 .args(["cat-file", "--batch"])
3581 .quiet()
3582 .current_dir(repo)
3583 .stdin(std::process::Stdio::piped())
3584 .stdout(std::process::Stdio::piped())
3585 .stderr(std::process::Stdio::piped())
3586 .spawn()
3587 .context("running git cat-file --batch")?;
3588 if let Some(mut stdin) = child.stdin.take() {
3589 let mut query = format!("{sha}^{{commit}}\n");
3590 for rel in REPO_LAYER_RELS {
3591 query.push_str(&format!("{sha}:{rel}\n"));
3592 }
3593 if let Err(e) = stdin.write_all(query.as_bytes())
3594 && e.kind() != std::io::ErrorKind::BrokenPipe
3595 {
3596 return Err(e).context("writing query to git cat-file --batch");
3597 }
3598 }
3599 let out = child
3600 .wait_with_output()
3601 .context("waiting for git cat-file --batch")?;
3602 if !out.status.success() {
3603 bail!(
3604 "cannot read config from {remote}/{base} ({sha}): {}",
3605 String::from_utf8_lossy(&out.stderr).trim()
3606 );
3607 }
3608 let entries = parse_cat_file_batch(&out.stdout, 1 + REPO_LAYER_RELS.len())?;
3609 let mut iter = entries.into_iter();
3610 let commit_sha = match iter.next() {
3611 Some(BatchEntry::Object { oid, kind, .. }) if kind == "commit" && is_hex_oid(&oid) => oid,
3612 _ => bail!("{}", missing_tracking_ref_msg(remote, base)),
3613 };
3614 let present_paths = if iter
3617 .as_slice()
3618 .iter()
3619 .any(|e| matches!(e, BatchEntry::Missing))
3620 {
3621 let tree = git_out(
3622 repo,
3623 &[
3624 "ls-tree",
3625 "--full-tree",
3626 "--name-only",
3627 &commit_sha,
3628 "--",
3629 ".magi/config.toml",
3630 "magi.toml",
3631 ],
3632 )
3633 .context("cannot read repository configuration tree")?;
3634 tree.lines().map(str::to_owned).collect::<Vec<_>>()
3635 } else {
3636 Vec::new()
3637 };
3638 let mut texts = Vec::new();
3639 for (rel, entry) in REPO_LAYER_RELS.into_iter().zip(iter) {
3640 match entry {
3641 BatchEntry::Missing => {
3642 if present_paths.iter().any(|path| path == rel) {
3643 bail!("cannot read {rel} from {remote}/{base} ({commit_sha}): missing object");
3644 }
3645 }
3646 BatchEntry::Object { kind, content, .. } if kind == "blob" => {
3647 texts.push((rel, String::from_utf8_lossy(&content).into_owned()));
3648 }
3649 BatchEntry::Object { kind, .. } => {
3650 bail!(
3651 "cannot read {rel} from {remote}/{base} ({commit_sha}): expected blob, found {kind}"
3652 );
3653 }
3654 }
3655 }
3656 Ok((commit_sha, texts))
3657}
3658
3659fn resolve_common_and_commit_cli(
3660 repo: &Path,
3661 remote: &str,
3662 base: &str,
3663) -> Option<(PathBuf, String)> {
3664 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3665 if !remote.starts_with('-') && !base.starts_with('-') {
3666 let out = git_out(
3667 repo,
3668 &[
3669 "rev-parse",
3670 "--path-format=absolute",
3671 "--git-common-dir",
3672 &spec,
3673 ],
3674 )?;
3675 let mut lines = out.lines().map(str::trim).filter(|l| !l.is_empty());
3676 let common = lines.next()?;
3677 let sha = lines.next()?;
3678 if lines.next().is_none() && is_hex_oid(sha) {
3679 return Some((PathBuf::from(common), sha.to_owned()));
3680 }
3681 }
3682 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3683 .map(|s| s.trim().to_owned())
3684 .filter(|s| is_hex_oid(s))?;
3685 let common = git_out(
3686 repo,
3687 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
3688 )
3689 .map(|s| PathBuf::from(s.trim()))?;
3690 Some((common, sha))
3691}
3692
3693fn resolve_remote_head_and_commit_cli(repo: &Path, remote: &str) -> Result<(String, String)> {
3697 let head = format!("refs/remotes/{remote}/HEAD");
3698 if let Some(out) = git_out(
3699 repo,
3700 &[
3701 "for-each-ref",
3702 "--format=%(refname)%09%(symref)%09%(objecttype)%09%(objectname)%09%(*objecttype)%09%(*objectname)",
3703 &head,
3704 ],
3705 ) {
3706 for line in out.lines() {
3707 let parts: Vec<&str> = line.trim_end_matches('\r').split('\t').collect();
3708 if parts.len() != 6 || parts[0] != head {
3709 continue;
3710 }
3711 let symref = parts[1];
3712 if let Some(base) = crate::git::remote_head_branch(remote, symref) {
3713 if parts[2] == "commit" && is_hex_oid(parts[3]) {
3714 return Ok((base, parts[3].to_owned()));
3715 }
3716 if parts[4] == "commit" && is_hex_oid(parts[5]) {
3717 return Ok((base, parts[5].to_owned()));
3718 }
3719 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3720 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3721 .map(|s| s.trim().to_owned())
3722 .filter(|s| is_hex_oid(s))
3723 .with_context(|| missing_tracking_ref_msg(remote, &base))?;
3724 return Ok((base, sha));
3725 }
3726 }
3727 }
3728 let base = git_out(repo, &["symbolic-ref", "--quiet", &head])
3731 .and_then(|s| crate::git::remote_head_branch(remote, &s))
3732 .with_context(|| missing_remote_head_msg(remote))?;
3733 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3734 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3735 .map(|s| s.trim().to_owned())
3736 .filter(|s| is_hex_oid(s))
3737 .with_context(|| missing_tracking_ref_msg(remote, &base))?;
3738 Ok((base, sha))
3739}
3740
3741fn remote_layers_fallback(repo: &Path) -> Result<Vec<PathBuf>> {
3742 let (remote, cfg_base) = probe_remote_base(repo);
3743 if let Some(base) = cfg_base {
3744 if let Some((common_dir, sha)) = resolve_common_and_commit_cli(repo, &remote, &base) {
3745 return materialize_remote_layers(repo, Some(common_dir), &remote, &base, &sha, true);
3746 }
3747 if !is_git_worktree(repo) {
3748 return Ok(local_repo_layers(repo));
3749 }
3750 bail!("{}", missing_tracking_ref_msg(&remote, &base));
3751 }
3752 if !is_git_worktree(repo) {
3753 return Ok(local_repo_layers(repo));
3754 }
3755 remote_layers_with_git(repo, None)
3756}
3757
3758fn remote_layers_with_git(repo: &Path, git_dirs: Option<GitDirs>) -> Result<Vec<PathBuf>> {
3761 let (remote, cfg_base) = probe_remote_base(repo);
3762
3763 if let Some(dirs) = &git_dirs
3767 && dirs.files_ref_backend
3768 {
3769 let base_from_files = match &cfg_base {
3770 Some(b) => Some(b.clone()),
3771 None => resolve_remote_head_files(&dirs.common_dir, &remote),
3772 };
3773 if let Some(base) = base_from_files {
3774 let tracking = format!("refs/remotes/{remote}/{base}");
3775 if let Some(sha) = resolve_ref_oid_files(&dirs.common_dir, &tracking) {
3776 return materialize_remote_layers(
3777 repo,
3778 Some(dirs.common_dir.clone()),
3779 &remote,
3780 &base,
3781 &sha,
3782 false,
3783 );
3784 }
3785 }
3786 }
3787
3788 let (common_dir, base, sha) = match (git_dirs, cfg_base) {
3792 (Some(dirs), Some(base)) => {
3793 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3794 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3795 .map(|s| s.trim().to_owned())
3796 .filter(|s| is_hex_oid(s))
3797 .with_context(|| missing_tracking_ref_msg(&remote, &base))?;
3798 (Some(dirs.common_dir), base, sha)
3799 }
3800 (Some(dirs), None) => {
3801 let (base, sha) = resolve_remote_head_and_commit_cli(repo, &remote)?;
3802 (Some(dirs.common_dir), base, sha)
3803 }
3804 (None, Some(base)) => {
3805 let (common_dir, sha) = resolve_common_and_commit_cli(repo, &remote, &base)
3806 .with_context(|| missing_tracking_ref_msg(&remote, &base))?;
3807 (Some(common_dir), base, sha)
3808 }
3809 (None, None) => {
3810 let (base, sha) = resolve_remote_head_and_commit_cli(repo, &remote)?;
3811 (None, base, sha)
3812 }
3813 };
3814 materialize_remote_layers(repo, common_dir, &remote, &base, &sha, true)
3815}
3816
3817fn materialize_remote_layers(
3818 repo: &Path,
3819 common_dir: Option<PathBuf>,
3820 remote: &str,
3821 base: &str,
3822 sha: &str,
3823 verified: bool,
3824) -> Result<Vec<PathBuf>> {
3825 let repo_key = repo.to_string_lossy();
3826 let key_for = |commit_sha: &str| {
3827 format!(
3828 "{commit_sha}-{}-v{CACHE_MANIFEST_VERSION}",
3829 fnv_hex(&repo_key)
3830 )
3831 };
3832 let primary_root = common_dir.map(|c| c.join("magi").join("config"));
3833 let fallback_root = dirs::cache_dir().map(|p| p.join("magi").join("config"));
3834 let lookup = |commit_sha: &str| -> Option<Vec<PathBuf>> {
3835 let key = key_for(commit_sha);
3836 if let Some(root) = &primary_root
3837 && let Some(layers) = read_cached_layers(&root.join(&key), commit_sha, repo)
3838 {
3839 return Some(layers);
3840 }
3841 read_cached_layers(&fallback_root.as_ref()?.join(&key), commit_sha, repo)
3842 };
3843 if let Some(layers) = lookup(sha) {
3844 if !verified {
3845 let commit = git_out(
3849 repo,
3850 &[
3851 "rev-parse",
3852 "--verify",
3853 "--quiet",
3854 &format!("{sha}^{{commit}}"),
3855 ],
3856 );
3857 if !commit.is_some_and(|s| s.trim() == sha) {
3858 bail!("{}", missing_tracking_ref_msg(remote, base));
3859 }
3860 }
3861 return Ok(layers);
3862 }
3863
3864 let (commit_sha, texts) = read_commit_layers_batch(repo, sha, remote, base)?;
3865 if commit_sha != sha
3866 && let Some(layers) = lookup(&commit_sha)
3867 {
3868 return Ok(layers);
3869 }
3870
3871 let key = key_for(&commit_sha);
3872 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
3873 let build = |root: &Path| -> Result<Vec<PathBuf>> {
3877 let final_dir = root.join(&key);
3878 if let Some(layers) = read_cached_layers(&final_dir, &commit_sha, repo) {
3879 return Ok(layers);
3880 }
3881 static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3882 let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3883 std::fs::create_dir_all(root)?;
3884 let tmp = root.join(format!(
3885 "{key}.tmp-{}-{}-{seq}",
3886 std::process::id(),
3887 std::time::SystemTime::now()
3888 .duration_since(std::time::UNIX_EPOCH)
3889 .map(|d| d.as_nanos())
3890 .unwrap_or_default()
3891 ));
3892 let filled = (|| -> Result<()> {
3893 std::fs::create_dir_all(&tmp)?;
3894 if wants_tree {
3895 extract_tree(repo, &commit_sha, &tmp)?;
3896 }
3897 for (rel, text) in &texts {
3898 let file = join_rel_path(&tmp, rel);
3899 let parent = file.parent().unwrap_or(&tmp);
3900 std::fs::create_dir_all(parent)?;
3901 write_extracted(&file, text)?;
3902 write_extracted(&parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
3903 }
3904 let manifest = CacheManifest {
3905 version: CACHE_MANIFEST_VERSION,
3906 sha: commit_sha.clone(),
3907 repo: repo.to_string_lossy().into_owned(),
3908 layers: texts.iter().map(|(rel, _)| (*rel).to_owned()).collect(),
3909 extracted_tree: wants_tree,
3910 };
3911 write_extracted(
3912 &tmp.join(CACHE_MANIFEST),
3913 serde_json::to_vec(&manifest).context("serialize config cache manifest")?,
3914 )?;
3915 Ok(())
3916 })();
3917 if let Err(e) = filled {
3918 let _ = std::fs::remove_dir_all(&tmp);
3919 return Err(e);
3920 }
3921 if std::fs::rename(&tmp, &final_dir).is_err() {
3922 let _ = std::fs::remove_dir_all(&tmp);
3927 return read_cached_layers(&final_dir, &commit_sha, repo)
3928 .with_context(|| format!("cannot place {}", final_dir.display()));
3929 }
3930 Ok(texts
3931 .iter()
3932 .map(|(rel, _)| join_rel_path(&final_dir, rel))
3933 .collect())
3934 };
3935 let layers = match primary_root.as_deref().map(&build) {
3936 Some(Ok(layers)) => layers,
3937 _ => {
3938 let root = fallback_root
3939 .as_deref()
3940 .context("no user config cache directory")?;
3941 build(root).with_context(|| format!("extracting config from {remote}/{base}"))?
3942 }
3943 };
3944 Ok(layers)
3945}
3946
3947#[cfg(test)]
3948mod tests {
3949 #[test]
3950 fn standing_authorization_is_only_from_the_named_machine_layer() {
3951 let dir = tempfile::tempdir().unwrap();
3952 let machine = dir.path().join("machine.toml");
3953 let repo = dir.path().join("magi.toml");
3954 std::fs::write(&machine, "[talk]\nstanding_authorization = false\n").unwrap();
3955 std::fs::write(&repo, "[talk]\nstanding_authorization = true\n").unwrap();
3956 let layers = [machine.clone(), repo.clone()];
3957 let load = |paths| Config::load_layers_with_machine(paths, Some(machine.clone())).unwrap();
3958 assert!(!load(&layers).talk.standing_authorization);
3959 assert!(
3960 !load(std::slice::from_ref(&repo))
3961 .talk
3962 .standing_authorization
3963 );
3964 std::fs::write(&machine, "[talk]\nstanding_authorization = true\n").unwrap();
3965 std::fs::write(&repo, "[talk]\nstanding_authorization = false\n").unwrap();
3966 assert!(load(&layers).talk.standing_authorization);
3967 }
3968
3969 #[test]
3970 fn run_records_with_the_retired_editing_network_key_still_load() {
3971 for value in ["enabled", "restricted"] {
3973 let mut graph = serde_json::to_value(Graph::default()).unwrap();
3974 graph["editing_network"] = serde_json::json!(value);
3975 let back: Graph = serde_json::from_value(graph).unwrap();
3976 assert!(
3977 serde_json::to_value(&back)
3978 .unwrap()
3979 .get("editing_network")
3980 .is_none()
3981 );
3982 let from_toml: Graph = toml::from_str(&format!("editing_network = {value:?}")).unwrap();
3983 assert!(
3984 !toml::to_string(&from_toml)
3985 .unwrap()
3986 .contains("editing_network")
3987 );
3988 }
3989 }
3990
3991 #[test]
3992 fn coordination_defaults_off_and_validates_rendered_layer_values() {
3993 let dir = tempfile::tempdir().unwrap();
3994 let machine = dir.path().join("machine.toml");
3995 let repo = dir.path().join("repo.toml");
3996 std::fs::write(&machine, "").unwrap();
3997 assert!(Config::default().coordination.is_none());
3998 assert!(Config::load(&machine).unwrap().coordination.is_none());
3999 std::fs::write(
4000 &machine,
4001 r#"
4002[vars]
4003contract = "updater.contract"
4004[coordination]
4005contract_file = "{{ vars.contract }}"
4006contract_token = "protocol-v1"
4007lock_file = "updater.lock"
4008"#,
4009 )
4010 .unwrap();
4011 let cfg = Config::load(&machine).unwrap();
4012 let policy = cfg.coordination.unwrap();
4013 assert_eq!(policy.contract_file, "updater.contract");
4014 assert_eq!(policy.contract_token, "protocol-v1");
4015 assert_eq!(policy.lock_file, "updater.lock");
4016 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
4017 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
4018 let policy = cfg.coordination.unwrap();
4019 assert_eq!(policy.contract_file, "updater.contract");
4020 assert_eq!(policy.lock_file, "repository.lock");
4021 std::fs::write(
4022 &repo,
4023 r#"
4024[vars]
4025bad = "../escape"
4026[coordination]
4027lock_file = "{{ vars.bad }}"
4028"#,
4029 )
4030 .unwrap();
4031 let error = Config::load_layers(&[machine, repo]).unwrap_err();
4032 assert!(format!("{error:#}").contains("coordination.lock_file"));
4033 }
4034
4035 #[test]
4036 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
4037 let dir = tempfile::tempdir().unwrap();
4038 let path = dir.path().join("config.toml");
4039 let valid = toml::toml! {
4040 [coordination]
4041 contract_file = "updater.contract"
4042 contract_token = "protocol-v1"
4043 lock_file = "updater.lock"
4044 };
4045 for key in ["contract_file", "lock_file"] {
4046 for bad in [
4047 "",
4048 " ",
4049 " file",
4050 "file ",
4051 "\tfile",
4052 "file\t",
4053 ".",
4054 "..",
4055 "file..name",
4056 "../escape",
4057 "a/b",
4058 "a\\b",
4059 "/absolute",
4060 "C:drive",
4061 "C:\\absolute",
4062 "nul\0name",
4063 ] {
4064 let mut table = valid.clone();
4065 table["coordination"][key] = bad.into();
4066 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4067 let error = Config::load(&path).unwrap_err();
4068 assert!(
4069 format!("{error:#}").contains(&format!("coordination.{key}")),
4070 "{bad:?}: {error:#}"
4071 );
4072 }
4073 }
4074 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
4075 let mut table = valid.clone();
4076 table["coordination"]["contract_token"] = 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("coordination.contract_token"),
4081 "{error:#}"
4082 );
4083 }
4084 for key in ["contract_file", "contract_token", "lock_file"] {
4085 let mut table = valid.clone();
4086 table["coordination"].as_table_mut().unwrap().remove(key);
4087 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4088 let error = Config::load(&path).unwrap_err();
4089 assert!(
4090 format!("{error:#}").contains(&format!("coordination.{key}")),
4091 "{error:#}"
4092 );
4093 }
4094 let mut table = valid;
4095 table["coordination"]
4096 .as_table_mut()
4097 .unwrap()
4098 .insert("typo".into(), "value".into());
4099 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4100 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
4101 }
4102
4103 #[test]
4104 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
4105 let mut cfg = Config::default();
4106 assert_eq!(
4107 cfg.context_window("claude-sonnet-4-5-20250929"),
4108 Some(200_000)
4109 );
4110 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
4111 assert_eq!(cfg.context_window("mystery-model"), None);
4112 cfg.context_windows
4113 .insert("claude-sonnet-4-5".into(), 1_000_000);
4114 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
4115 cfg.context_windows.insert("mystery".into(), 32_768);
4116 assert_eq!(
4118 cfg.context_window("claude-sonnet-4-5-20250929"),
4119 Some(1_000_000)
4120 );
4121 cfg.context_windows
4123 .insert("claude-sonnet-4-5-20250929".into(), 7);
4124 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
4125 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
4126 }
4127
4128 use super::*;
4129
4130 #[test]
4133 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
4134 let dir = tempfile::tempdir().unwrap();
4135 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
4136 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
4137 let paths = dir.path().as_os_str();
4138 assert_eq!(
4139 find_program_in("codex", paths, Some(".EXE;.CMD")),
4140 Some(dir.path().join("codex.cmd"))
4141 );
4142 assert_eq!(
4143 find_program_in("codex", paths, None),
4144 Some(dir.path().join("codex"))
4145 );
4146 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
4147 }
4148
4149 fn spec(id: &str) -> AgentSpec {
4150 AgentSpec {
4151 id: id.to_owned(),
4152 kind: AgentKind::Command,
4153 model: None,
4154 command: vec!["true".to_owned()],
4155 extra_args: Vec::new(),
4156 env: BTreeMap::new(),
4157 prompt_delivery: None,
4158 max_turn_secs: None,
4159 }
4160 }
4161
4162 #[test]
4163 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
4164 let default: Merge = toml::from_str("").unwrap();
4165 assert_eq!(default.ci, MergeCi::Expected);
4166 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
4167 assert_eq!(
4168 config.merge.ci.expectation(),
4169 crate::land::CiExpectation::Absent
4170 );
4171 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
4172 assert!(Config::starter_toml().contains("# ci = \"expected\""));
4173 }
4174
4175 #[test]
4176 fn github_text_guard_defaults_on_and_can_be_disabled() {
4177 let default: Graph = toml::from_str("").unwrap();
4178 assert!(default.github_text_guard);
4179 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
4180 assert!(!disabled.github_text_guard);
4181 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
4182 assert!(!config.graph.github_text_guard);
4183 assert!(Config::starter_toml().contains("github_text_guard = true"));
4184 }
4185
4186 #[test]
4187 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
4188 assert!(Graph::default().rerun_flaky_checks);
4189 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
4190 assert!(!off.rerun_flaky_checks);
4191 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
4192 }
4193
4194 #[test]
4195 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
4196 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
4201 assert_eq!(g.timeout_verify, None);
4202 assert_eq!(g.verify_timeout(), 3600);
4203 }
4204
4205 #[test]
4206 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
4207 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
4212 assert_eq!(g.timeout_review, 45);
4213 assert_eq!(
4214 g.verify_timeout(),
4215 45,
4216 "an omitted legacy value follows review"
4217 );
4218 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
4219 .expect("parse explicit override");
4220 assert_eq!(explicit.verify_timeout(), 1200);
4221 }
4222
4223 #[test]
4224 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
4225 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
4226 assert_eq!(g.implementers, 4);
4227 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
4228 assert_eq!(g.implementers, 5);
4229 }
4230
4231 fn layered(lower: &str, upper: &str) -> Result<Config> {
4232 let dir = tempfile::tempdir().unwrap();
4233 let a = dir.path().join("a.toml");
4234 let b = dir.path().join("b.toml");
4235 std::fs::write(&a, lower).unwrap();
4236 std::fs::write(&b, upper).unwrap();
4237 Config::load_layers(&[a, b])
4238 }
4239
4240 #[test]
4241 fn graph_implementers_higher_layer_wins_across_spellings() {
4242 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
4243 assert_eq!(c.graph.implementers, 5);
4244 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
4245 assert_eq!(c.graph.implementers, 5);
4246 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
4247 assert_eq!(c.graph.implementers, 2);
4248 }
4249
4250 #[test]
4251 fn graph_implementers_both_keys_in_one_layer_is_refused() {
4252 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
4253 .unwrap_err()
4254 .to_string();
4255 assert!(
4256 err.contains("candidates") && err.contains("implementers"),
4257 "{err}"
4258 );
4259 assert!(err.contains("b.toml"), "{err}");
4260 }
4261
4262 #[test]
4263 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
4264 let g: Graph =
4268 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
4269 .expect("an old-shaped [graph] table must still parse");
4270 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
4271 assert!(
4272 !g.e2e_every_round,
4273 "off by default, same as before this field existed"
4274 );
4275 }
4276
4277 #[test]
4278 fn empty_roles_rotate_judges_off_their_own_candidate() {
4279 let cfg = Config {
4282 agents: vec![spec("a"), spec("b"), spec("c")],
4283 graph: Graph {
4284 implementers: 3,
4285 ..Graph::default()
4286 },
4287 ..Config::default()
4288 };
4289 let roles = cfg.resolve_roles().unwrap();
4290 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
4291 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
4292 assert_eq!(impls, ["a", "b", "c"]);
4293 assert_eq!(judges, ["b", "c", "a"]);
4294 for (i, j) in judges.iter().enumerate() {
4295 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
4296 }
4297 }
4298
4299 #[test]
4300 fn single_agent_roster_fills_every_seat() {
4301 let cfg = Config {
4302 agents: vec![spec("solo")],
4303 graph: Graph {
4304 implementers: 3,
4305 ..Graph::default()
4306 },
4307 ..Config::default()
4308 };
4309 let roles = cfg.resolve_roles().unwrap();
4310 assert_eq!(roles.implementers.len(), 3);
4311 assert!(roles.judges.iter().all(|a| a.id == "solo"));
4312 }
4313
4314 #[test]
4315 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
4316 let cfg = Config {
4321 agents: vec![spec("a"), spec("b"), spec("c")],
4322 graph: Graph {
4323 implementers: 1,
4324 ..Graph::default()
4325 },
4326 ..Config::default()
4327 };
4328 let roles = cfg.resolve_roles().unwrap();
4329 assert_eq!(roles.implementers.len(), 1);
4330 let roster: Vec<&str> = roles
4331 .implementer_roster
4332 .iter()
4333 .map(|a| a.id.as_str())
4334 .collect();
4335 assert_eq!(roster, ["a", "b", "c"]);
4336 }
4337
4338 #[test]
4339 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
4340 let cfg = Config {
4341 agents: vec![spec("a"), spec("b"), spec("c")],
4342 roles: Roles {
4343 implementers: vec!["c".to_owned(), "a".to_owned()],
4344 ..Roles::default()
4345 },
4346 graph: Graph {
4347 implementers: 1,
4348 ..Graph::default()
4349 },
4350 ..Config::default()
4351 };
4352 let roles = cfg.resolve_roles().unwrap();
4353 assert_eq!(roles.implementers.len(), 1);
4355 assert_eq!(roles.implementers[0].id, "c");
4356 let roster: Vec<&str> = roles
4357 .implementer_roster
4358 .iter()
4359 .map(|a| a.id.as_str())
4360 .collect();
4361 assert_eq!(roster, ["c", "a"]);
4362 }
4363
4364 #[test]
4365 fn explicit_roles_win() {
4366 let cfg = Config {
4367 agents: vec![spec("a"), spec("b")],
4368 roles: Roles {
4369 implementers: vec!["b".to_owned()],
4370 judges: vec!["a".to_owned()],
4371 reviewers: Vec::new(),
4372 fixer: Some("a".into()),
4373 ..Roles::default()
4374 },
4375 ..Config::default()
4376 };
4377 let roles = cfg.resolve_roles().unwrap();
4378 assert!(roles.implementers.iter().all(|a| a.id == "b"));
4379 assert!(roles.judges.iter().all(|a| a.id == "a"));
4380 let fixer = roles.fixer.unwrap();
4381 assert_eq!(fixer.len(), 1);
4382 assert_eq!(fixer[0].id, "a");
4383 assert_eq!(roles.conductor.id, "a");
4384 }
4385
4386 #[test]
4387 fn fixer_takes_a_string_or_an_ordered_chain() {
4388 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
4389 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
4390 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
4391 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
4392
4393 let resolve = |fixer: Option<AgentChoice>| {
4394 Config {
4395 agents: vec![spec("a"), spec("b"), spec("c")],
4396 roles: Roles {
4397 fixer,
4398 ..Roles::default()
4399 },
4400 ..Config::default()
4401 }
4402 .resolve_roles()
4403 };
4404 let ids = |r: &ResolvedRoles| -> Vec<String> {
4405 r.fixer
4406 .as_ref()
4407 .unwrap()
4408 .iter()
4409 .map(|s| s.id.clone())
4410 .collect()
4411 };
4412 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
4414 assert!(resolve(None).unwrap().fixer.is_none());
4415 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
4417 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
4418 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
4420 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
4421 }
4422
4423 #[test]
4424 fn unknown_agent_id_is_an_error() {
4425 let cfg = Config {
4426 agents: vec![spec("a")],
4427 roles: Roles {
4428 judges: vec!["nope".to_owned()],
4429 ..Roles::default()
4430 },
4431 ..Config::default()
4432 };
4433 assert!(cfg.resolve_roles().is_err());
4434 }
4435
4436 #[test]
4437 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
4438 let mut cfg = Config {
4439 agents: vec![spec("a"), spec("b")],
4440 ..Config::default()
4441 };
4442 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
4443
4444 cfg.roles.conductor = Some("b".into());
4445 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
4446
4447 cfg.roles.conductor = Some("missing".into());
4448 assert!(cfg.resolve_roles().is_err());
4449 }
4450
4451 #[test]
4452 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
4453 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
4454 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
4455 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
4456
4457 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
4458 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
4459 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
4460
4461 for roles in [one, chain] {
4462 let text = toml::to_string(&roles).unwrap();
4463 let back: Roles = toml::from_str(&text).unwrap();
4464 assert_eq!(back.synthesizer, roles.synthesizer);
4465 assert_eq!(back.chatter, roles.chatter);
4466 }
4467 let text = toml::to_string(&Roles {
4468 conductor: Some("x".into()),
4469 ..Roles::default()
4470 })
4471 .unwrap();
4472 assert!(
4473 text.contains("conductor = \"x\""),
4474 "string stays a string: {text}"
4475 );
4476 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
4477 }
4478
4479 #[test]
4480 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
4481 for (text, ids) in [
4482 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
4483 (
4484 r#"dupes_judge = ["first", "second"]"#,
4485 vec!["first", "second"],
4486 ),
4487 ("dupes_judge = []", vec![]),
4488 ] {
4489 let roles: Roles = toml::from_str(text).unwrap();
4490 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
4491 let serialized = toml::to_string(&roles).unwrap();
4492 let back: Roles = toml::from_str(&serialized).unwrap();
4493 assert_eq!(back.dupes_judge, roles.dupes_judge);
4494 assert!(serialized.contains(text));
4495 }
4496 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
4497 assert!(Roles::default().dupes_judge.is_none());
4498 assert!(Config::starter_toml().contains("# dupes_judge ="));
4499
4500 let mut cfg = Config {
4502 agents: vec![spec("a")],
4503 ..Config::default()
4504 };
4505 cfg.roles.dupes_judge = Some("missing".into());
4506 assert!(cfg.resolve_roles().is_ok());
4507 }
4508
4509 #[test]
4510 fn an_empty_choice_counts_as_unset() {
4511 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
4512 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
4513 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
4514 }
4515
4516 #[test]
4517 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
4518 let mut cfg = Config {
4524 agents: vec![spec("a"), spec("b")],
4525 ..Config::default()
4526 };
4527 let want = primary(cfg.roles.synthesizer.as_ref());
4528 assert_eq!(
4529 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
4530 .unwrap()
4531 .id,
4532 "a",
4533 "unset falls back to agent::pick's own default order"
4534 );
4535
4536 cfg.roles.synthesizer = Some("b".into());
4537 let want = primary(cfg.roles.synthesizer.as_ref());
4538 assert_eq!(
4539 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
4540 .unwrap()
4541 .id,
4542 "b",
4543 "the named agent wins over the default order"
4544 );
4545 }
4546
4547 #[test]
4548 fn empty_roster_is_an_error() {
4549 assert!(Config::default().resolve_roles().is_err());
4550 }
4551
4552 #[test]
4553 fn advise_defaults_to_on_with_three_proposals() {
4554 let g = Graph::default();
4555 assert!(g.advise);
4556 assert!(g.graft_runner_up, "graft is on by default");
4557 assert_eq!(g.advisors, 3);
4558 }
4559
4560 #[test]
4561 fn unset_advisors_falls_back_to_the_judge_roster() {
4562 let cfg = Config {
4563 agents: vec![spec("a"), spec("b")],
4564 roles: Roles {
4565 judges: vec!["b".to_owned()],
4566 ..Roles::default()
4567 },
4568 graph: Graph {
4569 advisors: 2,
4570 ..Graph::default()
4571 },
4572 ..Config::default()
4573 };
4574 let advisors = cfg.advisors().expect("advisors resolve");
4575 assert_eq!(advisors.len(), 2);
4576 assert!(
4577 advisors.iter().all(|a| a.id == "b"),
4578 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
4579 );
4580 }
4581
4582 #[test]
4583 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
4584 let cfg = Config {
4585 agents: vec![spec("a"), spec("b")],
4586 roles: Roles {
4587 judges: vec!["b".to_owned()],
4588 advisors: vec!["a".to_owned()],
4589 ..Roles::default()
4590 },
4591 graph: Graph {
4592 advisors: 2,
4593 ..Graph::default()
4594 },
4595 ..Config::default()
4596 };
4597 let advisors = cfg.advisors().expect("advisors resolve");
4598 assert!(advisors.iter().all(|a| a.id == "a"));
4599 }
4600
4601 #[test]
4607 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
4608 let cfg = Config {
4609 agents: vec![spec("a"), spec("b"), spec("c")],
4610 graph: Graph {
4611 advisors: 3,
4612 judges: 3,
4613 ..Graph::default()
4614 },
4615 ..Config::default()
4616 };
4617 let advisors = cfg.advisors().expect("advisors resolve");
4618 let judges = cfg.resolve_roles().expect("roles resolve").judges;
4619 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
4620 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
4621 assert_eq!(
4622 advisor_ids, judge_ids,
4623 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
4624 );
4625 }
4626
4627 #[test]
4628 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
4629 let cfg = Config {
4630 agents: vec![spec("a")],
4631 roles: Roles {
4632 advisors: vec!["nope".to_owned()],
4633 ..Roles::default()
4634 },
4635 graph: Graph {
4636 advisors: 1,
4637 ..Graph::default()
4638 },
4639 ..Config::default()
4640 };
4641 let err = cfg.advisors().expect_err("`nope` is not in the roster");
4642 assert!(format!("{err:#}").contains("nope"));
4643 }
4644
4645 #[test]
4646 fn repos_default_to_no_roots_and_a_day_of_trust() {
4647 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
4648 assert_eq!(Config::default().repos.scan_ttl, 86_400);
4649 assert_eq!(Config::default().repos.fetch_interval, 600);
4650 assert!(!Config::default().repos.auto_clone);
4651 assert!(Config::default().repos.clone_command.is_none());
4652 }
4653
4654 #[test]
4655 fn a_config_file_with_no_repos_table_still_loads() {
4656 let dir = tempfile::tempdir().unwrap();
4657 let path = dir.path().join("magi.toml");
4658 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4659 let cfg = Config::load(&path).expect("must load without [repos]");
4660 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
4661 assert_eq!(cfg.repos.scan_ttl, 86_400);
4662 }
4663
4664 #[test]
4679 fn a_test_build_does_not_read_the_operators_machine_config() {
4680 let repo = tempfile::tempdir().unwrap();
4681 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4682
4683 let layers = Config::layers(repo.path());
4684 assert_eq!(
4685 layers,
4686 vec![repo.path().join("magi.toml")],
4687 "only the fixture's own file may be a layer"
4688 );
4689 if let Some(real) = dirs::config_dir() {
4690 let machine = real.join("magi").join("config.toml");
4691 assert!(
4692 !layers.contains(&machine),
4693 "the operator's {} must not be a layer in a test build",
4694 machine.display()
4695 );
4696 }
4697 }
4698
4699 #[test]
4700 fn auto_upgrade_config_defaults_and_opt_in() {
4701 let default: Update = toml::from_str("").unwrap();
4702 assert!(!default.auto_restart);
4703 assert_eq!(default.mode, UpdateMode::Notify);
4704 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
4705 assert!(enabled.auto_restart);
4706 assert_eq!(enabled.interval.as_deref(), Some("2h"));
4707 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
4708 }
4709
4710 #[test]
4711 fn starter_toml_loads_through_teravars() {
4712 let dir = tempfile::tempdir().unwrap();
4713 let path = dir.path().join("magi.toml");
4714 std::fs::write(&path, Config::starter_toml()).unwrap();
4715 let parsed = Config::load(&path).expect("starter config must load");
4716 assert_eq!(parsed.graph.implementers, 3);
4717 assert_eq!(parsed.merge.mode, MergeMode::None);
4718 assert_eq!(parsed.merge.style, MergeStyle::Merge);
4719 assert!(parsed.graph.sessions);
4720 assert!(parsed.graph.github_text_guard);
4721 assert_eq!(parsed.graph.timeout_review, 1200);
4722 assert_eq!(parsed.graph.verify_timeout(), 1200);
4723 assert_eq!(parsed.update.mode, UpdateMode::Notify);
4724 }
4725
4726 #[test]
4727 fn release_defaults_to_actions_and_the_starter_documents_it() {
4728 let dir = tempfile::tempdir().unwrap();
4729 let path = dir.path().join("magi.toml");
4730 std::fs::write(&path, Config::starter_toml()).unwrap();
4731 let r = Config::load(&path).unwrap().release;
4732 assert_eq!(r.mode, ReleaseMode::Actions);
4733 assert!(!r.is_local());
4734 assert!(r.commands.is_empty());
4735 assert_eq!(r.timeout_minutes, 30);
4736 assert!(Config::starter_toml().contains("# mode = \"actions\""));
4737 }
4738
4739 #[test]
4740 fn release_local_parses_and_unknown_keys_are_refused() {
4741 let dir = tempfile::tempdir().unwrap();
4742 let path = dir.path().join("magi.toml");
4743 std::fs::write(
4744 &path,
4745 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
4746 )
4747 .unwrap();
4748 let r = Config::load(&path).unwrap().release;
4749 assert!(r.is_local());
4750 assert_eq!(r.commands.len(), 2);
4751 assert_eq!(r.timeout_minutes, 5);
4752 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
4753 assert!(Config::load(&path).is_err());
4754 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
4755 assert!(Config::load(&path).is_err());
4756 }
4757
4758 #[test]
4759 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
4760 let dir = tempfile::tempdir().unwrap();
4761 let path = dir.path().join("magi.toml");
4762 std::fs::write(&path, Config::starter_toml()).unwrap();
4763 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
4764 assert!(Config::starter_toml().contains("# pre_gate = []"));
4765 }
4766
4767 #[test]
4768 fn release_version_files_parse_default_empty_and_are_validated() {
4769 let dir = tempfile::tempdir().unwrap();
4770 let path = dir.path().join("magi.toml");
4771 std::fs::write(&path, "").unwrap();
4772 assert!(
4773 Config::load(&path)
4774 .unwrap()
4775 .release
4776 .version_files
4777 .is_empty()
4778 );
4779 std::fs::write(
4780 &path,
4781 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
4782 )
4783 .unwrap();
4784 let files = Config::load(&path).unwrap().release.version_files;
4785 assert_eq!(files.len(), 2);
4786 assert_eq!(files[1].kind, VersionKind::Json);
4787 for bad in [
4788 "{ path = \"package.json\", kind = \"json\" }",
4789 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
4790 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
4791 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
4792 ] {
4793 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
4794 assert!(Config::load(&path).is_err(), "{bad}");
4795 }
4796 assert!(Config::starter_toml().contains("# version_files = ["));
4797 }
4798
4799 #[test]
4800 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
4801 let starter = Config::starter_toml();
4802 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
4803 assert!(starter.contains("verification independent if timeout_review changes later"));
4804 assert!(starter.contains("# timeout_verify = 1200"));
4805 }
4806
4807 #[test]
4808 fn starter_toml_documents_chat_personas() {
4809 let starter = Config::starter_toml();
4810 assert!(starter.contains("# [[talk.personas]]"));
4811 assert!(starter.contains("tone only"));
4812 }
4813
4814 #[test]
4815 fn talk_personas_parse_and_are_validated() {
4816 let dir = tempfile::tempdir().unwrap();
4817 let path = dir.path().join("magi.toml");
4818 std::fs::write(
4819 &path,
4820 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
4821 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
4822 )
4823 .unwrap();
4824 let cfg = Config::load(&path).expect("loads");
4825 assert_eq!(cfg.talk.personas.len(), 2);
4826 let catalog = crate::persona::catalog(&cfg.talk.personas);
4827 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
4828 assert_eq!(
4829 (rei.name.as_str(), rei.prompt.as_str()),
4830 ("Quiet", "Be brief.")
4831 );
4832 assert_eq!(catalog.last().unwrap().id, "gendo");
4833
4834 for (body, needle) in [
4835 (
4836 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
4837 "empty `id`",
4838 ),
4839 (
4840 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
4841 "empty `prompt`",
4842 ),
4843 (
4844 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
4845 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
4846 "more than once",
4847 ),
4848 (
4849 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
4850 "cannot be redefined",
4851 ),
4852 ] {
4853 std::fs::write(&path, body).unwrap();
4854 let err = format!("{:#}", Config::load(&path).unwrap_err());
4855 assert!(err.contains(needle), "{needle}: {err}");
4856 }
4857 }
4858
4859 #[test]
4860 fn talk_operator_name_is_trimmed_and_validated() {
4861 let dir = tempfile::tempdir().unwrap();
4862 let path = dir.path().join("magi.toml");
4863 let load = |body: &str| {
4864 std::fs::write(&path, body).unwrap();
4865 Config::load(&path)
4866 };
4867 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
4868 assert_eq!(ok.talk.operator_name(), Some("Commander"));
4869 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
4870 assert_eq!(blank.talk.operator_name(), None);
4871 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
4872 let long = "x".repeat(65);
4873 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
4874 }
4875
4876 #[test]
4877 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
4878 let dir = tempfile::tempdir().unwrap();
4879 let load = |body: &str| {
4880 let path = dir.path().join("c.toml");
4881 std::fs::write(&path, body).unwrap();
4882 Config::load(&path)
4883 };
4884 let ok = load(
4885 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
4886 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
4887 )
4888 .unwrap();
4889 let c = crate::persona::catalog(&ok.talk.personas);
4890 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
4891 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
4892 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
4893 let oversized = format!(
4894 "data:image/png;base64,{}",
4895 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
4896 );
4897 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
4898 for (id, fields) in [
4899 ("rei", ""),
4900 ("default", ""),
4901 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
4902 ] {
4903 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
4904 let cfg = load(&body).expect("bad icon must not invalidate config");
4905 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
4906 assert_eq!(persona.id, id);
4907 assert!(crate::persona_icon::load(bad).is_err());
4908 }
4909 }
4910 let doc = Config::starter_toml();
4911 assert!(doc.contains("# icon = "));
4912 }
4913
4914 #[test]
4915 fn talk_personas_in_two_layers_are_refused() {
4916 let dir = tempfile::tempdir().unwrap();
4917 let machine = dir.path().join("machine.toml");
4918 let repo = dir.path().join("repo.toml");
4919 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
4920 std::fs::write(&machine, one).unwrap();
4921 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
4922 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
4923 assert!(err.contains("talk.personas"), "{err}");
4924 }
4925
4926 #[test]
4927 fn starter_toml_documents_role_lists_as_backup_order() {
4928 let starter = Config::starter_toml();
4929 assert!(starter.contains("also an ordered backup list"));
4930 assert!(starter.contains("codex then sonnet are spares"));
4931 }
4932
4933 #[test]
4937 fn a_repository_can_declare_a_linear_history_merge_style() {
4938 let dir = tempfile::tempdir().unwrap();
4939 let path = dir.path().join("magi.toml");
4940 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
4941 let parsed = Config::load(&path).expect("config must load");
4942 assert_eq!(parsed.merge.style, MergeStyle::Squash);
4943 }
4944
4945 #[test]
4946 fn later_layers_win_and_vars_render() {
4947 let dir = tempfile::tempdir().unwrap();
4948 let machine = dir.path().join("machine.toml");
4949 let project = dir.path().join("magi.toml");
4950 std::fs::write(
4952 &machine,
4953 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
4954 [graph]\ncandidates = 3\nmax_parallel = 8\n[verify]\nbuild_cache = \"shared\"\n",
4955 )
4956 .unwrap();
4957 std::fs::write(
4960 &project,
4961 "[vars]\ncache = \"/shared\"\n\n\
4962 [graph]\ncandidates = 2\n\n\
4963 [verify]\nbuild_cache = \"isolated\"\n\
4964 gate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
4965 )
4966 .unwrap();
4967
4968 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
4969 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
4970 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
4971 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
4972 assert_eq!(cfg.verify.build_cache, BuildCache::Isolated);
4973 assert_eq!(
4974 cfg.verify.gate,
4975 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
4976 );
4977 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
4979 }
4980
4981 #[test]
4982 fn saved_config_without_a_build_cache_policy_remains_shared() {
4983 let saved: Config = serde_json::from_str(r#"{"verify":{"gate":["cargo test"]}}"#).unwrap();
4984 assert_eq!(saved.verify.build_cache, BuildCache::Shared);
4985 }
4986
4987 #[test]
4988 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
4989 let g = Graph::default();
4993 assert_eq!(g.timeout_talk, 3600);
4994
4995 let dir = tempfile::tempdir().unwrap();
4996 let path = dir.path().join("magi.toml");
4997 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4998 let cfg = Config::load(&path).expect("must load without timeout_talk set");
4999 assert_eq!(cfg.graph.timeout_talk, 3600);
5000 }
5001
5002 #[test]
5003 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
5004 let dir = tempfile::tempdir().unwrap();
5005 let path = dir.path().join("magi.toml");
5006 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
5007 let cfg = Config::load(&path).expect("must load");
5008 assert_eq!(cfg.graph.timeout_talk, 120);
5009 }
5010
5011 #[test]
5012 fn the_disk_defaults_are_the_measurements_made_up_front() {
5013 let cfg = Config::default();
5014 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
5015 assert!(cfg.disk.auto_fold);
5016 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
5017 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
5018 }
5019
5020 #[test]
5021 fn an_unset_disk_section_is_the_safe_default() {
5022 let dir = tempfile::tempdir().unwrap();
5023 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
5024 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
5025 assert_eq!(cfg.disk, Disk::default());
5026 }
5027
5028 #[test]
5029 fn the_reclaim_threshold_defaults_to_twice_the_floor_and_never_undercuts_it() {
5030 let disk = |min: u64, own: Option<u64>| Disk {
5031 min_free_bytes: min,
5032 reclaim_free_bytes: own,
5033 ..Disk::default()
5034 };
5035 assert_eq!(disk(8, None).reclaim_threshold(), 16);
5036 assert_eq!(Disk::default().reclaim_threshold(), 16 * 1024 * 1024 * 1024);
5037 assert_eq!(disk(8, Some(30)).reclaim_threshold(), 30);
5038 assert_eq!(
5039 disk(8, Some(3)).reclaim_threshold(),
5040 8,
5041 "never below the floor"
5042 );
5043 assert_eq!(disk(8, Some(0)).reclaim_threshold(), 8);
5044 assert_eq!(disk(8, Some(8)).reclaim_threshold(), 8);
5045 assert_eq!(
5046 disk(0, None).reclaim_threshold(),
5047 0,
5048 "gate off: no collection"
5049 );
5050 assert_eq!(
5051 disk(0, Some(0)).reclaim_threshold(),
5052 0,
5053 "explicit 0 resolves like unset: the resolved value decides"
5054 );
5055 assert_eq!(
5056 disk(0, Some(5)).reclaim_threshold(),
5057 5,
5058 "explicit still collects"
5059 );
5060 assert_eq!(disk(u64::MAX, None).reclaim_threshold(), u64::MAX);
5061 }
5062
5063 #[test]
5064 fn reclaim_free_bytes_loads_from_toml_and_older_configs_get_the_default() {
5065 let dir = tempfile::tempdir().unwrap();
5066 let path = dir.path().join("magi.toml");
5067 std::fs::write(&path, "[disk]\nmin_free_bytes = 100\n").unwrap();
5068 let cfg = Config::load(&path).expect("older config loads");
5069 assert_eq!(cfg.disk.reclaim_free_bytes, None);
5070 assert_eq!(cfg.disk.reclaim_threshold(), 200);
5071
5072 std::fs::write(
5073 &path,
5074 "[disk]\nmin_free_bytes = 100\nreclaim_free_bytes = 450\n",
5075 )
5076 .unwrap();
5077 let cfg = Config::load(&path).expect("explicit value loads");
5078 assert_eq!(cfg.disk.reclaim_threshold(), 450);
5079 }
5080
5081 #[test]
5082 fn a_saved_run_config_without_the_field_deserializes_to_the_default() {
5083 let disk = serde_json::to_value(Disk::default()).unwrap();
5086 assert!(disk.get("reclaim_free_bytes").is_none());
5087 let older: Disk = serde_json::from_value(disk).unwrap();
5088 assert_eq!(older, Disk::default());
5089 assert_eq!(older.reclaim_threshold(), 2 * older.min_free_bytes);
5090
5091 let own = Disk {
5092 reclaim_free_bytes: Some(7),
5093 ..Disk::default()
5094 };
5095 let back: Disk = serde_json::from_value(serde_json::to_value(&own).unwrap()).unwrap();
5096 assert_eq!(back.reclaim_free_bytes, Some(7));
5097 }
5098
5099 #[test]
5100 fn env_is_available_to_templates_with_a_default() {
5101 let dir = tempfile::tempdir().unwrap();
5102 let path = dir.path().join("magi.toml");
5103 std::fs::write(
5111 &path,
5112 "[verify]\n\
5113 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
5114 \"populated={{ env | length > 0 }}\"]\n",
5115 )
5116 .unwrap();
5117 let cfg = Config::load(&path).expect("env lookup must render");
5118 assert_eq!(cfg.verify.gate[0], "cache=fallback");
5119 assert_eq!(cfg.verify.gate[1], "populated=true");
5120 }
5121
5122 #[test]
5123 fn a_broken_template_names_the_file() {
5124 let dir = tempfile::tempdir().unwrap();
5125 let path = dir.path().join("magi.toml");
5126 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
5127 let err = Config::load(&path).expect_err("must not silently ignore");
5128 assert!(err.to_string().contains("teravars"), "{err}");
5129 }
5130
5131 #[test]
5132 fn tera_syntax_in_comments_is_inert() {
5133 let dir = tempfile::tempdir().unwrap();
5137 let path = dir.path().join("magi.toml");
5138 std::fs::write(
5139 &path,
5140 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
5141 [graph]\ncandidates = 2\n",
5142 )
5143 .unwrap();
5144 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
5145 assert_eq!(cfg.graph.implementers, 2);
5146 }
5147
5148 #[test]
5149 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
5150 use std::time::Duration;
5151
5152 let mut s: AgentSpec =
5153 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
5154 let budget = Duration::from_millis(1500);
5155 assert_eq!(s.max_turn_secs, None);
5156 assert_eq!(s.turn_timeout(budget), budget);
5157 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
5158 for (cap, expected) in [
5159 (1, Duration::from_secs(1)),
5160 (2, budget),
5161 (0, Duration::ZERO),
5162 ] {
5163 s.max_turn_secs = Some(cap);
5164 let saved = toml::to_string(&s).unwrap();
5165 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
5166 assert_eq!(loaded.max_turn_secs, Some(cap));
5167 assert_eq!(loaded.turn_timeout(budget), expected);
5168 }
5169 }
5170
5171 #[test]
5172 fn opencode_defaults_to_file_delivery() {
5173 let mut s = spec("oc");
5174 s.kind = AgentKind::Opencode;
5175 assert_eq!(s.delivery(), Delivery::File);
5176 s.prompt_delivery = Some(Delivery::Argv);
5177 assert_eq!(s.delivery(), Delivery::Argv);
5178 }
5179 #[test]
5180 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
5181 let g = Graph::default();
5186 assert!(
5187 g.land,
5188 "stopping at an open PR left the watching to a human"
5189 );
5190 assert!(
5191 g.land_approval,
5192 "on-by-default land is only defensible while this is also on"
5193 );
5194 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
5195 assert!(
5196 g.hold_contested_merge,
5197 "a contested hand-off must still reach a human when approvals are off"
5198 );
5199 }
5200 #[test]
5201 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
5202 let dir = tempfile::tempdir().unwrap();
5206 let machine = dir.path().join("machine.toml");
5207 let repo = dir.path().join("magi.toml");
5208 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
5209 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
5210
5211 let err = Config::load_layers(&[machine.clone(), repo.clone()])
5212 .expect_err("two layers naming one array must not merge silently");
5213 assert_eq!(
5214 err.downcast_ref::<ConfigFailure>().unwrap().stage,
5215 "config-merge"
5216 );
5217 let err = err.to_string();
5218 assert!(err.contains("roles.implementers"), "{err}");
5219 assert!(err.contains("machine.toml"), "{err}");
5222 assert!(err.contains("magi.toml"), "{err}");
5223 }
5224
5225 #[test]
5226 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
5227 let dir = tempfile::tempdir().unwrap();
5230 let machine = dir.path().join("machine.toml");
5231 let repo = dir.path().join("magi.toml");
5232 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
5233 std::fs::write(
5234 &repo,
5235 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
5236 [roles]\nimplementers = [\"oc\"]\n",
5237 )
5238 .unwrap();
5239
5240 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
5241 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
5242 assert_eq!(cfg.roles.implementers, ["oc"]);
5243 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
5244 }
5245
5246 #[test]
5247 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
5248 let dir = tempfile::tempdir().unwrap();
5251 let machine = dir.path().join("machine.toml");
5252 let repo = dir.path().join("magi.toml");
5253 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
5254 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5255
5256 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5257 assert_eq!(
5258 cfg.verify.gate,
5259 [
5260 "editorconfig-checker".to_owned(),
5261 "cargo make check".to_owned()
5262 ],
5263 "low-priority (machine) command first, high-priority (repo) command after"
5264 );
5265 }
5266
5267 fn load_one(body: &str) -> Result<Config> {
5268 let dir = tempfile::tempdir().unwrap();
5269 let path = dir.path().join("magi.toml");
5270 std::fs::write(&path, body).unwrap();
5271 Config::load_layers(&[path])
5272 }
5273
5274 #[test]
5275 fn pre_clean_config_is_strict_and_single_layer() {
5276 assert!(Config::default().worktree.pre_clean.is_empty());
5277 let good = load_one("[worktree]\npre_clean = [{run = 'cleanup', timeout_secs = 60}]\n");
5278 assert_eq!(good.unwrap().worktree.pre_clean[0].timeout_secs, Some(60));
5279 for bad in [
5280 "{}",
5281 "{run = ''}",
5282 "{run = ' ', timeout_secs = 2}",
5283 "{run = 'x', timeout_secs = 0}",
5284 "{run = 'x', timeout_secs = -1}",
5285 "{copy = 'cache'}",
5286 "{run = 'x', optional = true}",
5287 "'x'",
5288 ] {
5289 assert!(
5290 load_one(&format!("[worktree]\npre_clean = [{bad}]\n")).is_err(),
5291 "{bad}"
5292 );
5293 }
5294 let dir = tempfile::tempdir().unwrap();
5295 let a = dir.path().join("a.toml");
5296 let b = dir.path().join("b.toml");
5297 for path in [&a, &b] {
5298 std::fs::write(path, "[worktree]\npre_clean = [{run = 'cleanup'}]\n").unwrap();
5299 }
5300 assert!(
5301 Config::load_layers(&[a, b])
5302 .unwrap_err()
5303 .to_string()
5304 .contains("worktree.pre_clean")
5305 );
5306 }
5307
5308 #[test]
5309 fn worktree_setup_defaults_to_empty_and_parses_steps() {
5310 assert!(Config::default().worktree.setup.is_empty());
5311 let cfg = load_one(
5312 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
5313 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
5314 )
5315 .unwrap();
5316 assert_eq!(cfg.worktree.setup.len(), 3);
5317 assert!(cfg.worktree.setup[1].optional);
5318 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
5319 }
5320
5321 #[test]
5322 fn worktree_setup_rejects_malformed_steps() {
5323 for bad in [
5324 "{ copy = \"a\", run = \"b\" }",
5325 "{ optional = true }",
5326 "{ copy = \"a -> ../b\" }",
5327 "{ copy = \"a -> /abs\" }",
5328 "{ copy = \"a -> .git/config\" }",
5329 "{ run = \"b\", optional = true }",
5330 "{ copy = \"a\", timeout_secs = 3 }",
5331 "{ run = \"b\", bogus = 1 }",
5332 ] {
5333 let body = format!("[worktree]\nsetup = [{bad}]\n");
5334 assert!(load_one(&body).is_err(), "{bad}");
5335 }
5336 }
5337
5338 #[test]
5339 fn worktree_setup_in_two_layers_is_refused() {
5340 let dir = tempfile::tempdir().unwrap();
5341 let machine = dir.path().join("machine.toml");
5342 let repo = dir.path().join("magi.toml");
5343 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
5344 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
5345 assert!(Config::load_layers(&[machine, repo]).is_err());
5346 }
5347
5348 #[test]
5349 fn starter_toml_documents_worktree_setup() {
5350 let starter = Config::starter_toml();
5351 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
5352 let body = starter.replace("# [worktree]", "[worktree]");
5354 let mut out = String::new();
5355 let mut live = false;
5356 for line in body.lines() {
5357 if line == "[worktree]" {
5358 live = true;
5359 } else if live && !line.starts_with("# ") {
5360 live = false;
5361 }
5362 out.push_str(&if live {
5363 line.replacen("# ", "", 1)
5364 } else {
5365 line.to_owned()
5366 });
5367 out.push('\n');
5368 }
5369 let cfg = load_one(&out).expect("uncommented example loads");
5370 assert_eq!(cfg.worktree.setup.len(), 3);
5371 }
5372
5373 #[test]
5374 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
5375 let dir = tempfile::tempdir().unwrap();
5376 let machine = dir.path().join("machine.toml");
5377 let repo = dir.path().join("magi.toml");
5378 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
5379 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
5380
5381 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5382 assert_eq!(
5383 cfg.verify.e2e,
5384 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
5385 );
5386 }
5387
5388 #[test]
5389 fn two_layers_declaring_repos_roots_are_both_scanned() {
5390 let dir = tempfile::tempdir().unwrap();
5391 let machine = dir.path().join("machine.toml");
5392 let repo = dir.path().join("magi.toml");
5393 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
5394 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
5395
5396 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5397 assert_eq!(
5398 cfg.repos.roots,
5399 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
5400 );
5401 }
5402
5403 #[test]
5404 fn duplicate_gate_commands_across_layers_both_run() {
5405 let dir = tempfile::tempdir().unwrap();
5408 let machine = dir.path().join("machine.toml");
5409 let repo = dir.path().join("magi.toml");
5410 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
5411 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
5412
5413 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5414 assert_eq!(
5415 cfg.verify.gate,
5416 ["same-command".to_owned(), "same-command".to_owned()]
5417 );
5418 }
5419
5420 #[test]
5421 fn notify_command_is_still_refused_across_two_layers() {
5422 let dir = tempfile::tempdir().unwrap();
5424 let machine = dir.path().join("machine.toml");
5425 let repo = dir.path().join("magi.toml");
5426 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
5427 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
5428
5429 let err = Config::load_layers(&[machine.clone(), repo.clone()])
5430 .expect_err("an argv split across layers must not concatenate");
5431 assert_eq!(
5432 err.downcast_ref::<ConfigFailure>().unwrap().stage,
5433 "config-merge"
5434 );
5435 let err = err.to_string();
5436 assert!(err.contains("notify.command"), "{err}");
5437 assert!(err.contains("machine.toml"), "{err}");
5438 assert!(err.contains("magi.toml"), "{err}");
5439 }
5440
5441 #[test]
5442 fn one_layer_declaring_verify_gate_runs_unchanged() {
5443 let dir = tempfile::tempdir().unwrap();
5446 let path = dir.path().join("magi.toml");
5447 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5448
5449 let cfg = Config::load(&path).expect("single layer must still load");
5450 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
5451 }
5452
5453 #[test]
5454 fn layered_parse_failures_name_the_failing_input() {
5455 let dir = tempfile::tempdir().unwrap();
5456 let a = dir.path().join("a.toml");
5457 let b = dir.path().join("b.toml");
5458 std::fs::write(&a, "[graph").unwrap();
5459 std::fs::write(&b, "[verify").unwrap();
5460 let paths = [a.clone(), b.clone()];
5461 let first = Config::load_layers(&paths).unwrap_err();
5462 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
5463 assert_eq!(first_cause.stage, "config-parse");
5464 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
5465 std::fs::write(&a, "").unwrap();
5466 let second = Config::load_layers(&paths).unwrap_err();
5467 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
5468 assert_eq!(second_cause.stage, "config-parse");
5469 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
5470 assert_ne!(first_cause.target, second_cause.target);
5471 }
5472
5473 #[test]
5474 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
5475 let dir = tempfile::tempdir().unwrap();
5476 let machine = dir.path().join("machine.toml");
5477 let repo = dir.path().join("magi.toml");
5478 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
5479 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5480 let paths = vec![machine.clone(), repo.clone()];
5481
5482 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
5483 let described =
5484 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
5485 assert!(described.contains("editorconfig-checker && cargo make check"));
5486 assert!(
5487 described.contains(&machine.display().to_string()),
5488 "{described}"
5489 );
5490 assert!(
5491 described.contains(&repo.display().to_string()),
5492 "{described}"
5493 );
5494
5495 let single = vec![repo.clone()];
5497 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
5498 let solo_described =
5499 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
5500 assert_eq!(solo_described, "cargo make check");
5501 }
5502
5503 mod remote_layers {
5504 use super::*;
5505
5506 fn git(dir: &Path, args: &[&str]) {
5507 use crate::proc::Quiet as _;
5508 let out = std::process::Command::new("git")
5509 .args(args)
5510 .quiet()
5511 .current_dir(dir)
5512 .output()
5513 .unwrap();
5514 assert!(out.status.success(), "git {args:?}: {out:?}");
5515 }
5516
5517 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
5520 let tmp = tempfile::tempdir().unwrap();
5521 let bare = tmp.path().join("o.git");
5522 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
5523 let repo = tmp.path().join("repo");
5524 std::fs::create_dir_all(&repo).unwrap();
5525 git(&repo, &["init", "-b", "trunk"]);
5526 git(&repo, &["config", "user.name", "t"]);
5527 git(&repo, &["config", "user.email", "t@example.com"]);
5528 std::fs::write(repo.join("magi.toml"), remote).unwrap();
5529 git(&repo, &["add", "-A"]);
5530 git(&repo, &["commit", "-m", "x"]);
5531 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
5532 git(&repo, &["push", "origin", "trunk"]);
5533 git(&repo, &["fetch", "origin"]);
5534 git(&repo, &["remote", "set-head", "origin", "trunk"]);
5535 std::fs::write(repo.join("magi.toml"), disk).unwrap();
5536 (tmp, repo)
5537 }
5538
5539 #[tokio::test]
5540 async fn branch_owner_holds_only_add_literal_true_values() {
5541 for (text, expected) in [
5542 ("[graph]\nland_approval = true\n", true),
5543 ("[graph]\nland_approval = false\n", false),
5544 ("[graph]\nland = true\n", false),
5545 ("[graph\n", false),
5546 ("[graph]\nland_approval = \"yes\"\n", false),
5547 ("[graph]\nland_approval = 1\n", false),
5548 ] {
5549 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
5550 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
5551 let (holds, _) = branch_owner_holds(&repo, &head).await;
5552 assert_eq!(
5553 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
5554 expected
5555 );
5556 assert!(
5557 !holds
5558 .iter()
5559 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
5560 );
5561 for base in [false, true] {
5562 let mut cfg = Config::default();
5563 cfg.graph.land_approval = base;
5564 let mut state = crate::run::RunState::new(
5565 repo.clone(),
5566 "trunk".into(),
5567 head.clone(),
5568 "review".into(),
5569 cfg,
5570 );
5571 state.observe_branch_owner_holds(&head).await;
5572 assert!(
5573 state.branch_owner_holds.is_empty(),
5574 "competition candidates are excluded"
5575 );
5576 state.reviewed_commits = Some(Vec::new());
5577 state.observe_branch_owner_holds(&head).await;
5578 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
5579 }
5580 }
5581 }
5582
5583 #[tokio::test]
5584 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
5585 let (_tmp, repo) = fixture(
5586 "[graph]\nland_approval = true\n",
5587 "[graph]\nland_approval = true\n",
5588 );
5589 git(&repo, &["rm", "magi.toml"]);
5590 std::fs::create_dir(repo.join(".magi")).unwrap();
5591 std::fs::write(
5592 repo.join(".magi/config.toml"),
5593 "[graph]\nhold_contested_merge = true\n",
5594 )
5595 .unwrap();
5596 git(&repo, &["add", "."]);
5597 git(&repo, &["commit", "-m", "nested hold"]);
5598 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
5599 let (holds, _) = branch_owner_holds(&repo, &head).await;
5600 assert_eq!(
5601 holds,
5602 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
5603 );
5604 let (holds, diagnostics) =
5605 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
5606 assert!(holds.is_empty());
5607 assert!(!diagnostics.is_empty());
5608 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
5609 assert!(holds.is_empty());
5610 assert!(!diagnostics.is_empty());
5611 for base in [false, true] {
5612 let mut cfg = Config::default();
5613 cfg.graph.land_approval = base;
5614 let mut state = crate::run::RunState::new(
5615 repo.clone(),
5616 "trunk".into(),
5617 head.clone(),
5618 "review".into(),
5619 cfg,
5620 );
5621 state.reviewed_commits = Some(Vec::new());
5622 state.observe_branch_owner_holds(&head).await;
5623 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
5624 state
5625 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
5626 .await;
5627 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
5628 }
5629 }
5630
5631 #[test]
5632 fn reads_the_remote_blob_not_the_working_tree() {
5633 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5634 let (cfg, _) = Config::discover(&repo, None).unwrap();
5635 assert_eq!(cfg.graph.implementers, 2);
5636 }
5637
5638 #[test]
5639 fn detached_head_still_reads_the_remote() {
5640 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5641 git(&repo, &["checkout", "--detach"]);
5642 let (cfg, _) = Config::discover(&repo, None).unwrap();
5643 assert_eq!(cfg.graph.implementers, 2);
5644 }
5645
5646 #[test]
5647 fn a_missing_ref_is_an_error_not_a_fallback() {
5648 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5649 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5650 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
5651 assert!(err.contains("origin"), "{err}");
5652 }
5653
5654 #[test]
5655 fn merge_base_in_the_checkout_locates_the_ref() {
5656 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
5657 assert!(Config::discover(&repo, None).is_err());
5658 }
5659
5660 #[test]
5661 fn the_magi_dir_layer_is_read_too() {
5662 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5663 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
5664 std::fs::create_dir_all(repo.join(".magi")).unwrap();
5665 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
5666 git(&repo, &["add", "-A"]);
5667 git(&repo, &["commit", "-m", "y"]);
5668 git(&repo, &["push", "origin", "trunk"]);
5669 git(&repo, &["fetch", "origin"]);
5670 let ((cfg, layers), (_, cold_git)) =
5671 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5672 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
5673 assert_eq!(layers.len(), 2);
5674 assert_eq!(cold_git, 1);
5675 let common_cache = repo
5676 .join(".git")
5677 .canonicalize()
5678 .unwrap()
5679 .join("magi")
5680 .join("config");
5681 assert!(
5682 layers.iter().all(|p| p.starts_with(&common_cache)),
5683 "expected .magi/config.toml and magi.toml to cache under common git dir {}, got {layers:?}",
5684 common_cache.display()
5685 );
5686
5687 let ((cfg_warm, warm_layers), (_, warm_git)) =
5688 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5689 assert_eq!((cfg_warm.graph.implementers, cfg_warm.graph.judges), (2, 3));
5690 assert_eq!(warm_layers, layers);
5691 assert_eq!(warm_git, 1);
5692 }
5693
5694 #[test]
5695 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
5696 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
5697 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
5698 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
5699 git(&repo, &["add", "-A"]);
5700 git(&repo, &["commit", "-m", "inc"]);
5701 git(&repo, &["push", "origin", "trunk"]);
5702 git(&repo, &["fetch", "origin"]);
5703 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
5705 let (cfg, _) = Config::discover(&repo, None).unwrap();
5706 assert_eq!(cfg.graph.implementers, 2);
5707 }
5708
5709 #[test]
5710 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
5711 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
5712 let m = t.path().join("machine.toml");
5713 std::fs::write(
5714 &m,
5715 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
5716 )
5717 .unwrap();
5718 let (remote, base) = {
5719 let probe = probe_merge(&m, &repo).unwrap();
5720 (probe.remote, probe.base)
5721 };
5722 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
5723 }
5724
5725 #[test]
5726 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
5727 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5728 let m = t.path().join("machine.toml");
5729 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
5730 let probe = probe_merge(&m, &repo).unwrap();
5731 assert_eq!(probe.base.as_deref(), Some("repo"));
5732 }
5733
5734 #[test]
5735 fn every_include_form_is_recognised() {
5736 assert!(declares_include("include = [\"a.toml\"]\n"));
5737 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
5738 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
5739 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
5740 assert!(!declares_include("[graph]\ncandidates = 2\n"));
5741 }
5742
5743 #[test]
5744 fn an_explicit_config_is_read_as_named() {
5745 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5746 let own = t.path().join("own.toml");
5747 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
5748 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
5749 assert_eq!(cfg.graph.implementers, 4);
5750 }
5751
5752 #[test]
5753 fn discover_fetched_fails_when_the_fetch_does() {
5754 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5755 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
5756 let rt = tokio::runtime::Builder::new_current_thread()
5757 .enable_all()
5758 .build()
5759 .unwrap();
5760 let err = rt
5761 .block_on(Config::discover_fetched(&repo, None))
5762 .unwrap_err();
5763 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
5764 }
5765
5766 #[test]
5767 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
5768 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
5769 let remote = tmp.path().join("o.git");
5770 let offline = tmp.path().join("offline.git");
5771 std::fs::rename(&remote, &offline).unwrap();
5772 let rt = tokio::runtime::Builder::new_current_thread()
5773 .enable_all()
5774 .build()
5775 .unwrap();
5776 let fetch = rt
5777 .block_on(Config::discover_fetched(&repo, None))
5778 .unwrap_err();
5779 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
5780 assert_eq!(fetch_cause.stage, "config-fetch");
5781 assert_eq!(fetch_cause.target, "origin/trunk");
5782
5783 std::fs::rename(&offline, &remote).unwrap();
5784 let parse = rt
5785 .block_on(Config::discover_fetched(&repo, None))
5786 .unwrap_err();
5787 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
5788 assert_eq!(parse_cause.stage, "config-parse");
5789 assert!(parse_cause.target.contains("magi.toml"));
5790 assert!(
5791 !parse_cause.target.contains("/magi/config/"),
5792 "cache commit paths are incidental"
5793 );
5794 assert_ne!(fetch_cause.stage, parse_cause.stage);
5795 }
5796
5797 #[test]
5798 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
5799 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5802 git(&repo, &["remote", "set-head", "origin", "-d"]);
5803 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5804 git(
5805 &repo,
5806 &["config", "remote.origin.followRemoteHEAD", "never"],
5807 );
5808 let rt = tokio::runtime::Builder::new_current_thread()
5809 .enable_all()
5810 .build()
5811 .unwrap();
5812 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
5813 assert_eq!(cfg.graph.implementers, 2);
5814 }
5815
5816 #[test]
5817 fn a_non_git_directory_reads_its_files() {
5818 let dir = tempfile::tempdir().unwrap();
5819 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
5820 let (cfg, (discoveries, git_calls)) =
5821 crate::web::request_cost::measure_sync(|| Config::discover(dir.path(), None));
5822 assert_eq!(cfg.unwrap().0.graph.implementers, 4);
5823 assert_eq!((discoveries, git_calls), (1, 0));
5824 }
5825
5826 fn push_remote_config(bare: &Path, branch: &str, magi_toml: &str) {
5827 let tmp = tempfile::tempdir().unwrap();
5828 let clone = tmp.path().join("push");
5829 git(
5830 tmp.path(),
5831 &["clone", "-b", branch, &bare.to_string_lossy(), "push"],
5832 );
5833 git(&clone, &["config", "user.name", "t"]);
5834 git(&clone, &["config", "user.email", "t@example.com"]);
5835 std::fs::write(clone.join("magi.toml"), magi_toml).unwrap();
5836 git(&clone, &["add", "magi.toml"]);
5837 git(&clone, &["commit", "-m", "update config"]);
5838 git(&clone, &["push", "origin", branch]);
5839 }
5840
5841 #[test]
5842 fn repeated_discovers_stay_within_bounded_git_spawns() {
5843 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5844
5845 let (values, (discoveries, cold_git)) = crate::web::request_cost::measure_sync(|| {
5848 (0..20)
5849 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5850 .collect::<Vec<_>>()
5851 });
5852 assert!(values.iter().all(|&n| n == 2));
5853 assert_eq!(discoveries, 20);
5854 assert_eq!(cold_git, 21);
5855
5856 let (values, (discoveries, warm_git)) = crate::web::request_cost::measure_sync(|| {
5858 (0..20)
5859 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5860 .collect::<Vec<_>>()
5861 });
5862 assert!(values.iter().all(|&n| n == 2));
5863 assert_eq!(discoveries, 20);
5864 assert_eq!(warm_git, 20);
5865 }
5866
5867 #[test]
5868 fn reftable_warm_discover_uses_one_git_process() {
5869 let tmp = tempfile::tempdir().unwrap();
5870 let repo = tmp.path();
5871 git(repo, &["init", "--ref-format=reftable", "-b", "trunk"]);
5872 git(repo, &["config", "user.name", "t"]);
5873 git(repo, &["config", "user.email", "t@example.com"]);
5874 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
5875 git(repo, &["add", "magi.toml"]);
5876 git(repo, &["commit", "-m", "config"]);
5877 git(repo, &["update-ref", "refs/remotes/origin/trunk", "HEAD"]);
5878 git(
5879 repo,
5880 &[
5881 "symbolic-ref",
5882 "refs/remotes/origin/HEAD",
5883 "refs/remotes/origin/trunk",
5884 ],
5885 );
5886 assert_eq!(
5887 Config::discover(repo, None).unwrap().0.graph.implementers,
5888 2
5889 );
5890 let (values, (_, count)) = crate::web::request_cost::measure_sync(|| {
5891 (0..10)
5892 .map(|_| Config::discover(repo, None).unwrap().0.graph.implementers)
5893 .collect::<Vec<_>>()
5894 });
5895 assert_eq!(values, vec![2; 10]);
5896 assert_eq!(count, 10);
5897 }
5898
5899 #[test]
5900 fn zero_layer_repository_caches_empty_manifest() {
5901 let tmp = tempfile::tempdir().unwrap();
5902 let bare = tmp.path().join("o.git");
5903 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
5904 let repo = tmp.path().join("repo");
5905 std::fs::create_dir_all(&repo).unwrap();
5906 git(&repo, &["init", "-b", "trunk"]);
5907 git(&repo, &["config", "user.name", "t"]);
5908 git(&repo, &["config", "user.email", "t@example.com"]);
5909 std::fs::write(repo.join("README.md"), "hello\n").unwrap();
5910 git(&repo, &["add", "-A"]);
5911 git(&repo, &["commit", "-m", "no config"]);
5912 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
5913 git(&repo, &["push", "origin", "trunk"]);
5914 git(&repo, &["fetch", "origin"]);
5915 git(&repo, &["remote", "set-head", "origin", "trunk"]);
5916
5917 let (layers, (_, cold_git)) = crate::web::request_cost::measure_sync(|| {
5918 let mut last = Vec::new();
5919 for _ in 0..20 {
5920 last = Config::discover(&repo, None).unwrap().1;
5921 }
5922 last
5923 });
5924 assert!(layers.is_empty());
5925 assert_eq!(cold_git, 21);
5926
5927 let (layers, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
5928 let mut last = Vec::new();
5929 for _ in 0..20 {
5930 last = Config::discover(&repo, None).unwrap().1;
5931 }
5932 last
5933 });
5934 assert!(layers.is_empty());
5935 assert_eq!(warm_git, 20);
5936 }
5937
5938 #[test]
5939 fn moved_loose_and_packed_refs_are_observed_immediately() {
5940 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5941 let bare = t.path().join("o.git");
5942
5943 assert_eq!(
5945 Config::discover(&repo, None).unwrap().0.graph.implementers,
5946 2
5947 );
5948 let (_, (_, warm_git)) =
5949 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5950 assert_eq!(warm_git, 1);
5951
5952 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 3\n");
5954 git(&repo, &["fetch", "origin"]);
5955 let (cfg, (_, moved_git)) =
5956 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5957 assert_eq!(cfg.graph.implementers, 3);
5958 assert_eq!(moved_git, 2);
5959 let (cfg, (_, warm_after_move)) =
5960 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5961 assert_eq!(cfg.graph.implementers, 3);
5962 assert_eq!(warm_after_move, 1);
5963
5964 git(&repo, &["pack-refs", "--all"]);
5966 let (cfg, (_, packed_warm)) =
5967 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5968 assert_eq!(cfg.graph.implementers, 3);
5969 assert_eq!(packed_warm, 1);
5970
5971 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 4\n");
5973 git(&repo, &["fetch", "origin"]);
5974 git(&repo, &["pack-refs", "--all"]);
5975 let (cfg, (_, packed_move)) =
5976 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5977 assert_eq!(cfg.graph.implementers, 4);
5978 assert_eq!(packed_move, 2);
5979 let (cfg, (_, packed_warm_2)) =
5980 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5981 assert_eq!(cfg.graph.implementers, 4);
5982 assert_eq!(packed_warm_2, 1);
5983
5984 assert!(
5986 std::fs::read_to_string(repo.join("magi.toml"))
5987 .unwrap()
5988 .contains("candidates = 9")
5989 );
5990 }
5991
5992 #[test]
5993 fn linked_worktree_reuses_common_dir_cache_with_one_warm_git_spawn() {
5994 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5995 let bare = t.path().join("o.git");
5996 let wt = t.path().join("linked-wt");
5997 git(
5998 &repo,
5999 &["worktree", "add", "--detach", &wt.to_string_lossy()],
6000 );
6001
6002 let (cfg, (_, cold_git)) =
6003 crate::web::request_cost::measure_sync(|| Config::discover(&wt, None).unwrap().0);
6004 assert_eq!(cfg.graph.implementers, 2);
6005 assert_eq!(cold_git, 2);
6006
6007 let (values, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
6008 (0..10)
6009 .map(|_| Config::discover(&wt, None).unwrap().0.graph.implementers)
6010 .collect::<Vec<_>>()
6011 });
6012 assert!(values.iter().all(|&n| n == 2));
6013 assert_eq!(warm_git, 10);
6014
6015 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 5\n");
6016 git(&wt, &["fetch", "origin"]);
6017 let (cfg, (_, moved_git)) =
6018 crate::web::request_cost::measure_sync(|| Config::discover(&wt, None).unwrap().0);
6019 assert_eq!(cfg.graph.implementers, 5);
6020 assert_eq!(moved_git, 2);
6021 }
6022
6023 #[test]
6024 fn deleted_or_retargeted_refs_never_reuse_stale_cache() {
6025 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6026 let bare = t.path().join("o.git");
6027 assert_eq!(
6028 Config::discover(&repo, None).unwrap().0.graph.implementers,
6029 2
6030 );
6031
6032 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
6034 assert!(Config::discover(&repo, None).is_err());
6035
6036 git(&repo, &["fetch", "origin"]);
6039 git(&repo, &["checkout", "-b", "alt"]);
6040 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 6\n").unwrap();
6041 git(&repo, &["add", "magi.toml"]);
6042 git(&repo, &["commit", "-m", "alt"]);
6043 git(&repo, &["push", "origin", "alt"]);
6044 git(&repo, &["fetch", "origin"]);
6045 let _ = bare;
6046 git(&repo, &["remote", "set-head", "origin", "alt"]);
6047 assert_eq!(
6048 Config::discover(&repo, None).unwrap().0.graph.implementers,
6049 6
6050 );
6051
6052 git(&repo, &["remote", "set-head", "origin", "-d"]);
6054 assert!(Config::discover(&repo, None).is_err());
6055 }
6056
6057 #[test]
6058 fn include_repository_reuses_extracted_tree_with_one_warm_git_spawn() {
6059 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
6060 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
6061 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
6062 git(&repo, &["add", "-A"]);
6063 git(&repo, &["commit", "-m", "inc"]);
6064 git(&repo, &["push", "origin", "trunk"]);
6065 git(&repo, &["fetch", "origin"]);
6066 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
6067
6068 let (cfg, (_, cold_git)) =
6069 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
6070 assert_eq!(cfg.graph.implementers, 2);
6071 assert_eq!(cold_git, 3);
6073
6074 let (values, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
6075 (0..10)
6076 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
6077 .collect::<Vec<_>>()
6078 });
6079 assert!(values.iter().all(|&n| n == 2));
6080 assert_eq!(warm_git, 10);
6081 }
6082
6083 #[test]
6084 fn partial_clone_loads_promised_config_blob() {
6085 let (tmp, source) = fixture("[graph]\ncandidates = 2\n", "");
6086 let bare = tmp.path().join("o.git");
6087 git(&bare, &["config", "uploadpack.allowFilter", "true"]);
6088 let clone = tmp.path().join("partial");
6089 git(
6090 tmp.path(),
6091 &[
6092 "clone",
6093 "--no-local",
6094 "--no-checkout",
6095 "--filter=blob:none",
6096 &bare.to_string_lossy(),
6097 &clone.to_string_lossy(),
6098 ],
6099 );
6100 let oid = git_out(&source, &["rev-parse", "HEAD:magi.toml"]).unwrap();
6101 let missing = repository_git()
6102 .env("GIT_NO_LAZY_FETCH", "1")
6103 .args(["cat-file", "-e", oid.trim()])
6104 .current_dir(&clone)
6105 .output()
6106 .unwrap();
6107 assert!(!missing.status.success(), "fixture must omit the blob");
6108 assert_eq!(
6109 Config::discover(&clone, None).unwrap().0.graph.implementers,
6110 2
6111 );
6112 }
6113
6114 #[test]
6115 fn missing_config_blob_is_not_cached_as_an_absent_layer() {
6116 let (_tmp, repo) = fixture("[graph]\ncandidates = 2\n", "");
6117 let oid = git_out(&repo, &["rev-parse", "HEAD:magi.toml"]).unwrap();
6118 let oid = oid.trim();
6119 let blob = repo.join(".git/objects").join(&oid[..2]).join(&oid[2..]);
6120 let saved = blob.with_extension("saved");
6121 std::fs::rename(&blob, &saved).unwrap();
6122 assert!(Config::discover(&repo, None).is_err());
6123 std::fs::rename(saved, blob).unwrap();
6124 assert_eq!(
6125 Config::discover(&repo, None).unwrap().0.graph.implementers,
6126 2
6127 );
6128 }
6129
6130 #[test]
6131 fn a_cached_config_does_not_hide_a_missing_base_commit() {
6132 let (_tmp, repo) = fixture("[graph]\ncandidates = 2\n", "");
6133 assert_eq!(
6134 Config::discover(&repo, None).unwrap().0.graph.implementers,
6135 2
6136 );
6137 let oid = git_out(&repo, &["rev-parse", "HEAD"]).unwrap();
6138 let oid = oid.trim();
6139 let commit = repo.join(".git/objects").join(&oid[..2]).join(&oid[2..]);
6140 let saved = commit.with_extension("saved");
6141 std::fs::rename(&commit, &saved).unwrap();
6142 assert!(Config::discover(&repo, None).is_err());
6143 std::fs::rename(saved, commit).unwrap();
6144 assert_eq!(
6145 Config::discover(&repo, None).unwrap().0.graph.implementers,
6146 2
6147 );
6148 }
6149
6150 #[test]
6151 fn corrupt_cache_directory_without_manifest_is_not_trusted() {
6152 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6153 let sha = git_out(&repo, &["rev-parse", "refs/remotes/origin/trunk^{commit}"])
6154 .unwrap()
6155 .trim()
6156 .to_owned();
6157 let key = format!(
6158 "{sha}-{}-v{CACHE_MANIFEST_VERSION}",
6159 fnv_hex(&repo.to_string_lossy())
6160 );
6161 let bad_dir = repo.join(".git/magi/config").join(&key);
6162 std::fs::create_dir_all(&bad_dir).unwrap();
6163 std::fs::write(bad_dir.join("magi.toml"), "[graph]\ncandidates = 9\n").unwrap();
6164 std::fs::write(bad_dir.join(REPO_MARKER), repo.to_string_lossy().as_bytes()).unwrap();
6165
6166 let (cfg, _) = Config::discover(&repo, None).unwrap();
6168 assert_eq!(cfg.graph.implementers, 2);
6169 }
6170
6171 #[test]
6172 fn resolve_remote_head_and_commit_cli_uses_one_git_process() {
6173 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6174 let expected = git_out(&repo, &["rev-parse", "refs/remotes/origin/trunk^{commit}"])
6175 .unwrap()
6176 .trim()
6177 .to_owned();
6178 let (resolved, (_, git_calls)) = crate::web::request_cost::measure_sync(|| {
6179 resolve_remote_head_and_commit_cli(&repo, "origin").unwrap()
6180 });
6181 assert_eq!(resolved, ("trunk".to_owned(), expected));
6182 assert_eq!(git_calls, 1);
6183 }
6184
6185 #[test]
6186 fn standard_files_ref_backend_rejects_nonstandard_git_config() {
6187 let tmp = tempfile::tempdir().unwrap();
6188 let common = tmp.path().join("git");
6189 std::fs::create_dir_all(common.join("refs")).unwrap();
6190
6191 let check = |cfg: &str| {
6192 std::fs::write(common.join("config"), cfg).unwrap();
6193 is_standard_files_ref_backend(&common)
6194 };
6195
6196 assert!(check("[core]\n\trepositoryformatversion = 0\n"));
6197 assert!(check(
6198 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tworktreeConfig = true\n\trefStorage = files\n\tobjectFormat = sha1\n"
6199 ));
6200 assert!(!check(
6201 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\trefStorage = reftable\n"
6202 ));
6203 assert!(!check(
6204 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tobjectFormat = sha256\n"
6205 ));
6206 assert!(!check(
6207 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tunknownExt\n"
6208 ));
6209 assert!(!check(
6210 "[core]\n\trepositoryformatversion = 1\n[extensions] refStorage = reftable\n"
6211 ));
6212 assert!(!check(
6213 "[core]\n\trepositoryformatversion = 0\n[include]\n\tpath = extra.cfg\n"
6214 ));
6215 assert!(!check(
6216 "[core]\n\trepositoryformatversion = 0\n\tfoo = bar\\\nbaz\n"
6217 ));
6218 }
6219 }
6220
6221 #[test]
6222 fn github_language_defaults_to_english_and_accepts_japanese() {
6223 let default: Graph = toml::from_str("").unwrap();
6224 assert_eq!(default.github_language, "en");
6225 assert!(default.github_english() && default.language_gate());
6226 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
6227 assert!(!ja.github_english() && !ja.language_gate());
6228 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
6230 assert!(only_ops.language_gate());
6231 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
6232 assert!(!off.language_gate() && off.github_english());
6233 assert!(Config::starter_toml().contains("github_language = \"en\""));
6234 }
6235}