1use std::collections::BTreeMap;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9
10use crate::plan::is_valid_id;
11use crate::store::write_text_atomically;
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct Config {
15 pub run: RunSettings,
16 pub policy: PolicySettings,
17 pub roles: Roles,
18 pub lanes: BTreeMap<String, Lane>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct RunSettings {
23 pub max_attempts: u32,
24 pub idle_timeout: Duration,
25 pub job_timeout: Duration,
26}
27
28#[derive(Debug, Clone, PartialEq)]
29pub struct PolicySettings {
30 pub min_remaining: f64,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Roles {
36 pub planner: Vec<String>,
37 pub reviewer: Vec<String>,
38 pub worker: Vec<String>,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum HarnessKind {
43 Claude,
44 Agy,
45 Codex,
46 Fake,
48}
49
50impl HarnessKind {
51 pub fn name(self) -> &'static str {
53 match self {
54 HarnessKind::Claude => "claude",
55 HarnessKind::Agy => "agy",
56 HarnessKind::Codex => "codex",
57 HarnessKind::Fake => "fake",
58 }
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
64#[serde(rename_all = "snake_case")]
65pub enum Mode {
66 Off,
67 Handover,
69 Direct,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
73#[serde(rename_all = "snake_case")]
74pub enum CodexProvider {
75 Deepseek,
76 Openai,
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
80#[serde(rename_all = "snake_case")]
81pub enum Effort {
82 Low,
83 Medium,
84 High,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Lane {
89 pub harness: HarnessKind,
90 pub bin: String,
92 pub provider: Option<CodexProvider>,
94 pub model: Option<String>,
96 pub effort: Effort,
97 pub mode: Mode,
98 pub quota_group: Option<String>,
99 pub accept_vendor_terms_risk: bool,
100 pub script: Option<PathBuf>,
102}
103
104impl Lane {
105 pub fn is_manual(&self) -> bool {
107 self.mode == Mode::Handover
108 }
109
110 pub fn is_off(&self) -> bool {
111 self.mode == Mode::Off
112 }
113}
114
115pub const EXAMPLE: &str = r#"[run]
117max_attempts = 5
118idle_timeout = "5m"
119job_timeout = "30m"
120
121[policy]
122min_remaining = 0.05
123
124[roles]
125planner = ["plan"]
126worker = ["gemini", "deepseek"]
127reviewer = ["review"]
128
129[lanes.plan]
130harness = "claude"
131model = "opus"
132effort = "medium"
133
134[lanes.review]
135harness = "claude"
136model = "sonnet"
137effort = "low"
138
139[lanes.deepseek]
140harness = "codex"
141model = "deepseek-flash"
142
143[lanes.gemini]
144harness = "agy"
145mode = "handover"
146model = "gemini-4-hydrogen-medium"
147quota_group = "Gemini Models"
148# accept_vendor_terms_risk = true # required for mode = "direct"
149"#;
150
151#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
152pub enum ConfigError {
153 #[error("no configuration file at {}; create one (an example follows)", .0.display())]
154 Missing(PathBuf),
155 #[error("cannot read {}: {message}", path.display())]
156 Unreadable { path: PathBuf, message: String },
157 #[error("cannot write {}: {message}", path.display())]
158 Unwritable { path: PathBuf, message: String },
159 #[error("the configuration is not valid TOML of the expected shape: {0}")]
160 Syntax(String),
161 #[error("{key}: {problem}")]
162 Invalid { key: String, problem: String },
163}
164
165fn invalid(key: impl Into<String>, problem: impl Into<String>) -> ConfigError {
166 ConfigError::Invalid {
167 key: key.into(),
168 problem: problem.into(),
169 }
170}
171
172pub fn default_path(xdg_config_home: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
175 let base = match (xdg_config_home.filter(|v| !v.is_empty()), home) {
176 (Some(xdg), _) => PathBuf::from(xdg),
177 (None, Some(home)) if !home.is_empty() => Path::new(home).join(".config"),
178 _ => return None,
179 };
180 Some(base.join("onerig").join("config.toml"))
181}
182
183pub fn load(path: &Path, allow_fake: bool) -> Result<Config, ConfigError> {
184 let text = std::fs::read_to_string(path).map_err(|e| match e.kind() {
185 std::io::ErrorKind::NotFound => ConfigError::Missing(path.to_path_buf()),
186 _ => ConfigError::Unreadable {
187 path: path.to_path_buf(),
188 message: e.to_string(),
189 },
190 })?;
191 parse(&text, allow_fake)
192}
193
194pub fn parse_duration(text: &str) -> Option<Duration> {
196 let seconds_per_unit = match text.chars().last()? {
197 's' => 1,
198 'm' => 60,
199 'h' => 3600,
200 _ => return None,
201 };
202 let number = &text[..text.len() - 1];
204 if !number.bytes().all(|b| b.is_ascii_digit()) {
205 return None;
206 }
207 let value: u64 = number.parse().ok()?;
208 value.checked_mul(seconds_per_unit).map(Duration::from_secs)
209}
210
211pub fn parse(text: &str, allow_fake: bool) -> Result<Config, ConfigError> {
212 let raw: RawConfig = toml::from_str(text).map_err(|e| ConfigError::Syntax(e.to_string()))?;
213 let run = run_settings(&raw.run)?;
214 let policy = policy_settings(&raw.policy)?;
215 let lanes = raw
216 .lanes
217 .iter()
218 .map(|(name, lane)| Ok((name.clone(), lane_from(name, lane, allow_fake)?)))
219 .collect::<Result<BTreeMap<_, _>, ConfigError>>()?;
220 let roles = roles_from(&raw.roles, &lanes)?;
221 Ok(Config {
222 run,
223 policy,
224 roles,
225 lanes,
226 })
227}
228
229#[derive(Deserialize)]
230#[serde(deny_unknown_fields)]
231struct RawConfig {
232 #[serde(default)]
233 run: RawRun,
234 #[serde(default)]
235 policy: RawPolicy,
236 roles: RawRoles,
237 lanes: BTreeMap<String, RawLane>,
238}
239
240#[derive(Deserialize, Default)]
241#[serde(deny_unknown_fields)]
242struct RawRun {
243 max_attempts: Option<i64>,
244 idle_timeout: Option<String>,
245 job_timeout: Option<String>,
246}
247
248#[derive(Deserialize, Default)]
249#[serde(deny_unknown_fields)]
250struct RawPolicy {
251 min_remaining: Option<f64>,
252}
253
254#[derive(Deserialize)]
255#[serde(deny_unknown_fields)]
256struct RawRoles {
257 planner: Vec<String>,
258 reviewer: Vec<String>,
259 worker: Vec<String>,
260}
261
262#[derive(Deserialize)]
263#[serde(deny_unknown_fields)]
264struct RawLane {
265 harness: String,
266 bin: Option<String>,
267 provider: Option<String>,
268 model: Option<String>,
269 effort: Option<String>,
270 mode: Option<String>,
271 quota_group: Option<String>,
272 accept_vendor_terms_risk: Option<bool>,
273 script: Option<PathBuf>,
274}
275
276fn run_settings(raw: &RawRun) -> Result<RunSettings, ConfigError> {
277 let max_attempts = raw.max_attempts.unwrap_or(5);
278 if !(1..=20).contains(&max_attempts) {
279 return Err(invalid("run.max_attempts", "use a number from 1 to 20"));
280 }
281 Ok(RunSettings {
282 max_attempts: max_attempts as u32,
283 idle_timeout: duration_setting("run.idle_timeout", raw.idle_timeout.as_deref(), 300)?,
284 job_timeout: duration_setting("run.job_timeout", raw.job_timeout.as_deref(), 1800)?,
285 })
286}
287
288fn duration_setting(
289 key: &str,
290 text: Option<&str>,
291 default_secs: u64,
292) -> Result<Duration, ConfigError> {
293 let Some(text) = text else {
294 return Ok(Duration::from_secs(default_secs));
295 };
296 match parse_duration(text) {
297 Some(duration) if duration >= Duration::from_secs(1) => Ok(duration),
298 Some(_) => Err(invalid(key, "use at least 1s")),
299 None => Err(invalid(
300 key,
301 "use a whole number followed by s, m or h, for example \"5m\"",
302 )),
303 }
304}
305
306fn policy_settings(raw: &RawPolicy) -> Result<PolicySettings, ConfigError> {
307 let min_remaining = raw.min_remaining.unwrap_or(0.05);
308 if !(0.0..=1.0).contains(&min_remaining) {
309 return Err(invalid("policy.min_remaining", "use a number from 0 to 1"));
310 }
311 Ok(PolicySettings { min_remaining })
312}
313
314fn lane_from(name: &str, raw: &RawLane, allow_fake: bool) -> Result<Lane, ConfigError> {
315 if !is_valid_id(name) {
316 return Err(invalid(
317 format!("lanes.{name}"),
318 "a lane name uses lowercase letters, digits, '-' and '_', at most 32 characters",
319 ));
320 }
321 let harness = harness_kind(name, &raw.harness, allow_fake)?;
322 check_keys_apply(name, raw, harness)?;
323 let mode = mode_of(name, raw, harness)?;
324 check_direct_agy(name, raw, harness, mode)?;
325 build_lane(name, raw, harness, mode)
326}
327
328fn build_lane(
329 name: &str,
330 raw: &RawLane,
331 harness: HarnessKind,
332 mode: Mode,
333) -> Result<Lane, ConfigError> {
334 Ok(Lane {
335 harness,
336 bin: raw
337 .bin
338 .clone()
339 .unwrap_or_else(|| harness.name().to_string()),
340 provider: provider_of(name, raw, harness)?,
341 model: required(
342 name,
343 "model",
344 raw.model.clone(),
345 harness != HarnessKind::Fake,
346 )?,
347 effort: effort_of(name, raw)?,
348 mode,
349 quota_group: raw.quota_group.clone(),
350 accept_vendor_terms_risk: raw.accept_vendor_terms_risk.unwrap_or(false),
351 script: required(
352 name,
353 "script",
354 raw.script.clone(),
355 harness == HarnessKind::Fake,
356 )?,
357 })
358}
359
360fn harness_kind(name: &str, text: &str, allow_fake: bool) -> Result<HarnessKind, ConfigError> {
361 let key = format!("lanes.{name}.harness");
362 match text {
363 "claude" => Ok(HarnessKind::Claude),
364 "agy" => Ok(HarnessKind::Agy),
365 "codex" => Ok(HarnessKind::Codex),
366 "fake" if allow_fake => Ok(HarnessKind::Fake),
367 "fake" => Err(invalid(
368 key,
369 "fake lanes are for tests and need ONERIG_TEST to be set",
370 )),
371 _ => Err(invalid(key, "use claude, agy or codex")),
372 }
373}
374
375fn check_keys_apply(name: &str, raw: &RawLane, harness: HarnessKind) -> Result<(), ConfigError> {
376 use HarnessKind::{Agy, Claude, Codex, Fake};
377 let rules: [(&str, bool, &[HarnessKind]); 7] = [
378 ("provider", raw.provider.is_some(), &[Codex]),
379 ("model", raw.model.is_some(), &[Claude, Agy, Codex]),
380 ("effort", raw.effort.is_some(), &[Claude]),
381 ("mode", raw.mode.is_some(), &[Agy]),
382 ("quota_group", raw.quota_group.is_some(), &[Agy]),
383 (
384 "accept_vendor_terms_risk",
385 raw.accept_vendor_terms_risk.is_some(),
386 &[Agy],
387 ),
388 ("script", raw.script.is_some(), &[Fake]),
389 ];
390 match rules
391 .iter()
392 .find(|(_, set, allowed)| *set && !allowed.contains(&harness))
393 {
394 Some((key, _, _)) => Err(invalid(
395 format!("lanes.{name}.{key}"),
396 format!("does not apply to a {} lane", harness.name()),
397 )),
398 None => Ok(()),
399 }
400}
401
402fn provider_of(
403 name: &str,
404 raw: &RawLane,
405 harness: HarnessKind,
406) -> Result<Option<CodexProvider>, ConfigError> {
407 if harness != HarnessKind::Codex {
408 return Ok(None);
409 }
410 match raw.provider.as_deref().unwrap_or("deepseek") {
411 "deepseek" => Ok(Some(CodexProvider::Deepseek)),
412 "openai" => Ok(Some(CodexProvider::Openai)),
413 _ => Err(invalid(
414 format!("lanes.{name}.provider"),
415 "use deepseek or openai",
416 )),
417 }
418}
419
420fn required<T>(
421 name: &str,
422 key: &str,
423 value: Option<T>,
424 needed: bool,
425) -> Result<Option<T>, ConfigError> {
426 match (needed, value) {
427 (true, None) => Err(invalid(format!("lanes.{name}.{key}"), "is required")),
428 (_, value) => Ok(value),
429 }
430}
431
432fn mode_of(name: &str, raw: &RawLane, harness: HarnessKind) -> Result<Mode, ConfigError> {
433 if harness != HarnessKind::Agy {
434 return Ok(Mode::Direct);
435 }
436 match raw.mode.as_deref().unwrap_or("handover") {
437 "off" => Ok(Mode::Off),
438 "handover" => Ok(Mode::Handover),
439 "direct" => Ok(Mode::Direct),
440 _ => Err(invalid(
441 format!("lanes.{name}.mode"),
442 "use off, handover or direct",
443 )),
444 }
445}
446
447fn check_direct_agy(
448 name: &str,
449 raw: &RawLane,
450 harness: HarnessKind,
451 mode: Mode,
452) -> Result<(), ConfigError> {
453 if harness != HarnessKind::Agy || mode != Mode::Direct {
454 return Ok(());
455 }
456 if raw.accept_vendor_terms_risk != Some(true) {
457 return Err(invalid(
458 format!("lanes.{name}.accept_vendor_terms_risk"),
459 "mode = \"direct\" lets onerig drive agy on your Google sign-in, which Google's \
460 Antigravity terms treat as a breach that can suspend the account; set this to true \
461 to accept that risk",
462 ));
463 }
464 required(name, "quota_group", raw.quota_group.as_ref(), true).map(|_| ())
465}
466
467fn effort_of(name: &str, raw: &RawLane) -> Result<Effort, ConfigError> {
468 match raw.effort.as_deref().unwrap_or("medium") {
469 "low" => Ok(Effort::Low),
470 "medium" => Ok(Effort::Medium),
471 "high" => Ok(Effort::High),
472 _ => Err(invalid(
473 format!("lanes.{name}.effort"),
474 "use low, medium or high",
475 )),
476 }
477}
478
479fn roles_from(raw: &RawRoles, lanes: &BTreeMap<String, Lane>) -> Result<Roles, ConfigError> {
480 Ok(Roles {
481 planner: auto_role_lanes("roles.planner", &raw.planner, lanes)?,
482 reviewer: auto_role_lanes("roles.reviewer", &raw.reviewer, lanes)?,
483 worker: worker_lanes(&raw.worker, lanes)?,
484 })
485}
486
487fn existing<'a>(
488 key: &str,
489 name: &str,
490 lanes: &'a BTreeMap<String, Lane>,
491) -> Result<&'a Lane, ConfigError> {
492 lanes
493 .get(name)
494 .ok_or_else(|| invalid(key, format!("there is no lane named {name}")))
495}
496
497fn distinct_lanes(
498 key: &str,
499 names: &[String],
500 lanes: &BTreeMap<String, Lane>,
501) -> Result<(), ConfigError> {
502 if names.is_empty() {
503 return Err(invalid(key, "name at least one lane"));
504 }
505 for (index, name) in names.iter().enumerate() {
506 if names[..index].contains(name) {
507 return Err(invalid(key, format!("lane {name} is named twice")));
508 }
509 let _ = existing(key, name, lanes)?;
510 }
511 Ok(())
512}
513
514fn auto_role_lanes(
515 key: &str,
516 names: &[String],
517 lanes: &BTreeMap<String, Lane>,
518) -> Result<Vec<String>, ConfigError> {
519 distinct_lanes(key, names, lanes)?;
520 for name in names {
521 let lane = &lanes[name];
522 if lane.is_off() || lane.is_manual() {
523 return Err(invalid(
524 key,
525 format!(
526 "lane {name} is manual or off; planner and reviewer lanes must run automatically"
527 ),
528 ));
529 }
530 }
531 Ok(names.to_vec())
532}
533
534fn worker_lanes(
535 names: &[String],
536 lanes: &BTreeMap<String, Lane>,
537) -> Result<Vec<String>, ConfigError> {
538 const KEY: &str = "roles.worker";
539 distinct_lanes(KEY, names, lanes)?;
540 if names.iter().all(|name| lanes[name].is_off()) {
541 return Err(invalid(KEY, "at least one worker lane must not be off"));
542 }
543 Ok(names.to_vec())
544}
545
546pub fn to_toml(config: &Config) -> String {
548 let out = OutConfig {
549 run: OutRun {
550 max_attempts: config.run.max_attempts,
551 idle_timeout: format_duration(config.run.idle_timeout),
552 job_timeout: format_duration(config.run.job_timeout),
553 },
554 policy: OutPolicy {
555 min_remaining: config.policy.min_remaining,
556 },
557 roles: OutRoles {
558 planner: &config.roles.planner,
559 reviewer: &config.roles.reviewer,
560 worker: &config.roles.worker,
561 },
562 lanes: config
563 .lanes
564 .iter()
565 .map(|(name, lane)| (name.clone(), out_lane(lane)))
566 .collect(),
567 };
568 toml::to_string_pretty(&out).unwrap_or_default()
569}
570
571pub fn save(path: &Path, config: &Config) -> Result<(), ConfigError> {
573 let err = |e: std::io::Error| ConfigError::Unwritable {
574 path: path.to_path_buf(),
575 message: e.to_string(),
576 };
577 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
578 std::fs::create_dir_all(parent).map_err(err)?;
579 }
580 write_text_atomically(path, &to_toml(config)).map_err(err)
581}
582
583#[derive(Serialize)]
584struct OutConfig<'a> {
585 run: OutRun,
586 policy: OutPolicy,
587 roles: OutRoles<'a>,
588 lanes: BTreeMap<String, OutLane<'a>>,
589}
590
591#[derive(Serialize)]
592struct OutRun {
593 max_attempts: u32,
594 idle_timeout: String,
595 job_timeout: String,
596}
597
598#[derive(Serialize)]
599struct OutPolicy {
600 min_remaining: f64,
601}
602
603#[derive(Serialize)]
604struct OutRoles<'a> {
605 planner: &'a [String],
606 reviewer: &'a [String],
607 worker: &'a [String],
608}
609
610#[derive(Serialize)]
611struct OutLane<'a> {
612 harness: &'static str,
613 #[serde(skip_serializing_if = "Option::is_none")]
614 bin: Option<&'a str>,
615 #[serde(skip_serializing_if = "Option::is_none")]
616 provider: Option<CodexProvider>,
617 #[serde(skip_serializing_if = "Option::is_none")]
618 model: Option<&'a str>,
619 #[serde(skip_serializing_if = "Option::is_none")]
620 effort: Option<Effort>,
621 #[serde(skip_serializing_if = "Option::is_none")]
622 mode: Option<Mode>,
623 #[serde(skip_serializing_if = "Option::is_none")]
624 quota_group: Option<&'a str>,
625 #[serde(skip_serializing_if = "Option::is_none")]
626 accept_vendor_terms_risk: Option<bool>,
627 #[serde(skip_serializing_if = "Option::is_none")]
628 script: Option<String>,
629}
630
631fn out_lane(lane: &Lane) -> OutLane<'_> {
632 let custom_bin = (lane.bin != lane.harness.name()).then_some(lane.bin.as_str());
633 let is = |kind| lane.harness == kind;
634 OutLane {
635 harness: lane.harness.name(),
636 bin: custom_bin,
637 provider: lane.provider.filter(|_| is(HarnessKind::Codex)),
638 model: (!is(HarnessKind::Fake))
639 .then_some(lane.model.as_deref())
640 .flatten(),
641 effort: is(HarnessKind::Claude).then_some(lane.effort),
642 mode: is(HarnessKind::Agy).then_some(lane.mode),
643 quota_group: is(HarnessKind::Agy)
644 .then_some(lane.quota_group.as_deref())
645 .flatten(),
646 accept_vendor_terms_risk: (is(HarnessKind::Agy) && lane.accept_vendor_terms_risk)
647 .then_some(true),
648 script: is(HarnessKind::Fake)
649 .then(|| lane.script.as_ref().map(|p| p.display().to_string()))
650 .flatten(),
651 }
652}
653
654fn format_duration(duration: Duration) -> String {
655 let secs = duration.as_secs();
656 if secs >= 3600 && secs.is_multiple_of(3600) {
657 format!("{}h", secs / 3600)
658 } else if secs >= 60 && secs.is_multiple_of(60) {
659 format!("{}m", secs / 60)
660 } else {
661 format!("{secs}s")
662 }
663}
664
665#[cfg(test)]
666mod tests {
667 use super::*;
668
669 const BASE: &str = r#"
670[roles]
671planner = ["plan"]
672reviewer = ["review"]
673worker = ["deepseek"]
674
675[lanes.plan]
676harness = "claude"
677model = "sonnet"
678
679[lanes.review]
680harness = "claude"
681model = "sonnet"
682
683[lanes.deepseek]
684harness = "codex"
685model = "deepseek-flash"
686"#;
687
688 const GEMINI: &str = "\n[lanes.gemini]\nharness = \"agy\"\nmodel = \"m\"\n";
689
690 fn with(extra: &str) -> String {
692 format!("{BASE}{extra}\n")
693 }
694
695 fn with_gemini(extra: &str) -> String {
696 with(&format!("{GEMINI}{extra}")).replace(
697 r#"worker = ["deepseek"]"#,
698 r#"worker = ["deepseek", "gemini"]"#,
699 )
700 }
701
702 fn invalid_key(text: &str) -> String {
703 match parse(text, false) {
704 Err(ConfigError::Invalid { key, .. }) => key,
705 other => panic!("expected an invalid key, got {other:?}"),
706 }
707 }
708
709 #[test]
710 fn the_example_is_valid_and_keeps_agy_manual() {
711 let config = parse(EXAMPLE, false).unwrap();
712
713 assert_eq!(config.roles.worker, ["gemini", "deepseek"]);
714 assert_eq!(config.lanes["plan"].model.as_deref(), Some("opus"));
715 assert_eq!(config.lanes["gemini"].mode, Mode::Handover);
716 assert!(config.lanes["gemini"].is_manual());
717 assert_eq!(config.lanes["deepseek"].mode, Mode::Direct);
718 assert_eq!(
719 config.lanes["deepseek"].provider,
720 Some(CodexProvider::Deepseek)
721 );
722 assert_eq!(config.lanes["review"].effort, Effort::Low);
723 }
724
725 #[test]
726 fn missing_settings_take_their_defaults() {
727 let config = parse(BASE, false).unwrap();
728
729 assert_eq!(config.run.max_attempts, 5);
730 assert_eq!(config.run.idle_timeout, Duration::from_secs(300));
731 assert_eq!(config.run.job_timeout, Duration::from_secs(1800));
732 assert_eq!(config.policy.min_remaining, 0.05);
733 assert_eq!(config.lanes["deepseek"].bin, "codex");
734 assert_eq!(config.lanes["plan"].effort, Effort::Medium);
735 assert_eq!(config.roles.planner, ["plan"]);
736 }
737
738 #[test]
739 fn an_unknown_key_or_a_wrong_type_is_a_syntax_error_naming_it() {
740 let unknown = parse(&with("\n[run]\nmax_attempt = 3"), false);
741 let wrong_type = parse(&with("\n[run]\nmax_attempts = \"3\""), false);
742
743 assert!(matches!(&unknown, Err(ConfigError::Syntax(m)) if m.contains("max_attempt")));
744 assert!(matches!(wrong_type, Err(ConfigError::Syntax(_))));
745 }
746
747 #[test]
748 fn max_attempts_must_be_from_1_to_20() {
749 assert_eq!(
750 invalid_key(&with("\n[run]\nmax_attempts = 0")),
751 "run.max_attempts"
752 );
753 assert_eq!(
754 invalid_key(&with("\n[run]\nmax_attempts = 21")),
755 "run.max_attempts"
756 );
757 assert_eq!(
758 parse(&with("\n[run]\nmax_attempts = 20"), false)
759 .unwrap()
760 .run
761 .max_attempts,
762 20
763 );
764 }
765
766 #[test]
767 fn durations_need_a_unit_and_at_least_one_second() {
768 for bad in ["\"5\"", "\"5d\"", "\"m\"", "\"0s\"", "\"-1s\""] {
769 assert_eq!(
770 invalid_key(&with(&format!("\n[run]\nidle_timeout = {bad}"))),
771 "run.idle_timeout",
772 "{bad}"
773 );
774 }
775 let config = parse(
776 &with("\n[run]\nidle_timeout = \"1s\"\njob_timeout = \"2h\""),
777 false,
778 )
779 .unwrap();
780 assert_eq!(config.run.idle_timeout, Duration::from_secs(1));
781 assert_eq!(config.run.job_timeout, Duration::from_secs(7200));
782 }
783
784 #[test]
785 fn parse_duration_reads_seconds_minutes_and_hours_only() {
786 assert_eq!(parse_duration("45s"), Some(Duration::from_secs(45)));
787 assert_eq!(parse_duration("5m"), Some(Duration::from_secs(300)));
788 assert_eq!(parse_duration("1h"), Some(Duration::from_secs(3600)));
789 for bad in ["", "s", "5", "5x", " 5m", "5.5m", "+5m", "é"] {
790 assert_eq!(parse_duration(bad), None, "{bad:?}");
791 }
792 }
793
794 #[test]
795 fn min_remaining_must_be_from_0_to_1() {
796 assert_eq!(
797 invalid_key(&with("\n[policy]\nmin_remaining = 1.5")),
798 "policy.min_remaining"
799 );
800 assert_eq!(
801 invalid_key(&with("\n[policy]\nmin_remaining = -0.1")),
802 "policy.min_remaining"
803 );
804 assert_eq!(
805 parse(&with("\n[policy]\nmin_remaining = 1.0"), false)
806 .unwrap()
807 .policy
808 .min_remaining,
809 1.0
810 );
811 }
812
813 #[test]
814 fn a_lane_name_must_be_safe() {
815 let text = with("\n[lanes.Deep]\nharness = \"codex\"\nmodel = \"m\"");
816
817 assert_eq!(invalid_key(&text), "lanes.Deep");
818 }
819
820 #[test]
821 fn an_unknown_harness_is_rejected() {
822 let text = BASE.replace(r#"harness = "codex""#, r#"harness = "aider""#);
823
824 assert_eq!(invalid_key(&text), "lanes.deepseek.harness");
825 }
826
827 #[test]
828 fn a_key_on_a_lane_whose_harness_it_does_not_apply_to_is_rejected() {
829 assert_eq!(
830 invalid_key(&with("effort = \"low\"")),
831 "lanes.deepseek.effort"
832 );
833 assert_eq!(invalid_key(&with("mode = \"off\"")), "lanes.deepseek.mode");
834 assert_eq!(
835 invalid_key(&with("quota_group = \"g\"")),
836 "lanes.deepseek.quota_group"
837 );
838 assert_eq!(
839 invalid_key(&with("accept_vendor_terms_risk = true")),
840 "lanes.deepseek.accept_vendor_terms_risk"
841 );
842 assert_eq!(
843 invalid_key(&with("script = \"s.json\"")),
844 "lanes.deepseek.script"
845 );
846 assert_eq!(
847 invalid_key(&with(
848 "\n[lanes.other]\nharness = \"claude\"\nmodel = \"opus\"\nprovider = \"openai\""
849 )),
850 "lanes.other.provider"
851 );
852 }
853
854 #[test]
855 fn a_lane_needs_a_model() {
856 let text = BASE.replace("model = \"deepseek-flash\"\n", "");
857
858 assert_eq!(invalid_key(&text), "lanes.deepseek.model");
859 }
860
861 #[test]
862 fn effort_must_be_low_medium_or_high() {
863 let text = BASE.replacen(
864 "model = \"sonnet\"",
865 "model = \"sonnet\"\neffort = \"max\"",
866 1,
867 );
868
869 assert_eq!(invalid_key(&text), "lanes.plan.effort");
870 }
871
872 #[test]
873 fn an_agy_lane_is_manual_unless_told_otherwise() {
874 let config = parse(&with_gemini(""), false).unwrap();
875
876 assert_eq!(config.lanes["gemini"].mode, Mode::Handover);
877 assert_eq!(
878 invalid_key(&with_gemini("mode = \"auto\"")),
879 "lanes.gemini.mode"
880 );
881 }
882
883 #[test]
884 fn direct_agy_needs_the_risk_acknowledgement_and_a_quota_group() {
885 let no_ack = with_gemini("mode = \"direct\"\nquota_group = \"Gemini Models\"");
886 let no_group = with_gemini("mode = \"direct\"\naccept_vendor_terms_risk = true");
887 let both =
888 with_gemini("mode = \"direct\"\nquota_group = \"G\"\naccept_vendor_terms_risk = true");
889
890 assert_eq!(
891 invalid_key(&no_ack),
892 "lanes.gemini.accept_vendor_terms_risk"
893 );
894 assert_eq!(invalid_key(&no_group), "lanes.gemini.quota_group");
895 assert_eq!(
896 parse(&both, false).unwrap().lanes["gemini"].mode,
897 Mode::Direct
898 );
899 }
900
901 #[test]
902 fn fake_lanes_need_the_test_switch_and_a_script() {
903 let fake = BASE.replace(
904 "harness = \"codex\"\nmodel = \"deepseek-flash\"",
905 "harness = \"fake\"\nscript = \"s.json\"",
906 );
907 let no_script = BASE.replace(
908 "harness = \"codex\"\nmodel = \"deepseek-flash\"",
909 "harness = \"fake\"",
910 );
911
912 assert_eq!(invalid_key(&fake), "lanes.deepseek.harness");
913 assert_eq!(
914 parse(&fake, true).unwrap().lanes["deepseek"].script,
915 Some(PathBuf::from("s.json"))
916 );
917 assert!(
918 matches!(parse(&no_script, true), Err(ConfigError::Invalid { key, .. }) if key == "lanes.deepseek.script")
919 );
920 }
921
922 #[test]
923 fn a_fake_lane_may_serve_every_role() {
924 let text = r#"
925[roles]
926planner = ["f"]
927reviewer = ["f"]
928worker = ["f"]
929
930[lanes.f]
931harness = "fake"
932script = "s.json"
933"#;
934
935 assert!(parse(text, true).is_ok());
936 }
937
938 #[test]
939 fn planner_and_reviewer_accept_automatic_chains_and_reject_manual_or_off() {
940 let empty = BASE.replace(r#"planner = ["plan"]"#, "planner = []");
941 let dup = BASE.replace(r#"planner = ["plan"]"#, r#"planner = ["plan", "plan"]"#);
942 let two = BASE.replace(r#"planner = ["plan"]"#, r#"planner = ["plan", "review"]"#);
943 let unknown = BASE.replace(r#"reviewer = ["review"]"#, r#"reviewer = ["nobody"]"#);
944 let worker_as_reviewer =
945 BASE.replace(r#"reviewer = ["review"]"#, r#"reviewer = ["deepseek"]"#);
946 let manual_planner =
947 with_gemini("").replace(r#"planner = ["plan"]"#, r#"planner = ["gemini"]"#);
948 let off_reviewer = with_gemini("mode = \"off\"")
949 .replace(r#"reviewer = ["review"]"#, r#"reviewer = ["gemini"]"#);
950 let direct_agy_planner =
951 with_gemini("mode = \"direct\"\nquota_group = \"G\"\naccept_vendor_terms_risk = true")
952 .replace(r#"planner = ["plan"]"#, r#"planner = ["gemini"]"#);
953
954 assert_eq!(invalid_key(&empty), "roles.planner");
955 assert_eq!(invalid_key(&dup), "roles.planner");
956 assert_eq!(
957 parse(&two, false).unwrap().roles.planner,
958 ["plan", "review"]
959 );
960 assert_eq!(invalid_key(&unknown), "roles.reviewer");
961 assert_eq!(
962 parse(&worker_as_reviewer, false).unwrap().roles.reviewer,
963 ["deepseek"]
964 );
965 assert_eq!(invalid_key(&manual_planner), "roles.planner");
966 assert_eq!(invalid_key(&off_reviewer), "roles.reviewer");
967 assert_eq!(
968 parse(&direct_agy_planner, false).unwrap().roles.planner,
969 ["gemini"]
970 );
971 }
972
973 #[test]
974 fn the_worker_chain_accepts_any_distinct_lanes_with_one_not_off() {
975 let empty = BASE.replace(r#"worker = ["deepseek"]"#, "worker = []");
976 let twice = BASE.replace(
977 r#"worker = ["deepseek"]"#,
978 r#"worker = ["deepseek", "deepseek"]"#,
979 );
980 let claude = BASE.replace(r#"worker = ["deepseek"]"#, r#"worker = ["plan"]"#);
981 let all_off = with_gemini("mode = \"off\"").replace(
982 r#"worker = ["deepseek", "gemini"]"#,
983 r#"worker = ["gemini"]"#,
984 );
985
986 for text in [empty, twice, all_off] {
987 assert_eq!(invalid_key(&text), "roles.worker");
988 }
989 assert_eq!(parse(&claude, false).unwrap().roles.worker, ["plan"]);
990 }
991
992 #[test]
993 fn codex_provider_defaults_to_deepseek_and_accepts_openai() {
994 let openai =
995 with("\n[lanes.gpt]\nharness = \"codex\"\nprovider = \"openai\"\nmodel = \"gpt-5.4\"")
996 .replace(
997 r#"worker = ["deepseek"]"#,
998 r#"worker = ["deepseek", "gpt"]"#,
999 );
1000 let bad = with("provider = \"anthropic\"");
1001
1002 let config = parse(&openai, false).unwrap();
1003
1004 assert_eq!(
1005 config.lanes["deepseek"].provider,
1006 Some(CodexProvider::Deepseek)
1007 );
1008 assert_eq!(config.lanes["gpt"].provider, Some(CodexProvider::Openai));
1009 assert_eq!(invalid_key(&bad), "lanes.deepseek.provider");
1010 }
1011
1012 #[test]
1013 fn to_toml_and_save_round_trip_every_harness_cleanly() {
1014 let mut config = parse(EXAMPLE, false).unwrap();
1015 config.run.idle_timeout = Duration::from_secs(3600);
1016 config.run.job_timeout = Duration::from_secs(61);
1017 let openai_lane = Lane {
1018 harness: HarnessKind::Codex,
1019 bin: "/usr/local/bin/codex".into(),
1020 provider: Some(CodexProvider::Openai),
1021 model: Some("gpt-5.4".into()),
1022 effort: Effort::Medium,
1023 mode: Mode::Direct,
1024 quota_group: None,
1025 accept_vendor_terms_risk: false,
1026 script: None,
1027 };
1028 config.lanes.insert("openai".into(), openai_lane);
1029 config.roles.worker.push("openai".into());
1030
1031 let dir = tempfile::tempdir().unwrap();
1032 let path = dir.path().join("nested").join("config.toml");
1033 save(&path, &config).unwrap();
1034 let text = std::fs::read_to_string(&path).unwrap();
1035 assert!(text.contains("idle_timeout = \"1h\""));
1036 assert!(text.contains("job_timeout = \"61s\""));
1037 assert!(!text.contains("bin = \"codex\""));
1038 let reloaded = load(&path, false).unwrap();
1039
1040 assert_eq!(reloaded, config);
1041 assert_eq!(format_duration(Duration::from_secs(3601)), "3601s");
1042 assert_eq!(format_duration(Duration::from_secs(60)), "1m");
1043 }
1044
1045 #[test]
1046 fn the_error_message_names_the_key_and_the_fix() {
1047 let error = parse(&with("\n[run]\nmax_attempts = 0"), false).unwrap_err();
1048
1049 assert_eq!(
1050 error.to_string(),
1051 "run.max_attempts: use a number from 1 to 20"
1052 );
1053 }
1054
1055 #[test]
1056 fn load_reports_a_missing_file_with_its_path() {
1057 let dir = tempfile::tempdir().unwrap();
1058 let path = dir.path().join("config.toml");
1059
1060 assert_eq!(load(&path, false), Err(ConfigError::Missing(path.clone())));
1061 std::fs::write(&path, BASE).unwrap();
1062 assert!(load(&path, false).is_ok());
1063 }
1064
1065 #[test]
1066 fn the_default_path_prefers_xdg_and_falls_back_to_home() {
1067 assert_eq!(
1068 default_path(Some("/x"), Some("/h")),
1069 Some(PathBuf::from("/x/onerig/config.toml"))
1070 );
1071 assert_eq!(
1072 default_path(Some(""), Some("/h")),
1073 Some(PathBuf::from("/h/.config/onerig/config.toml"))
1074 );
1075 assert_eq!(
1076 default_path(None, Some("/h")),
1077 Some(PathBuf::from("/h/.config/onerig/config.toml"))
1078 );
1079 assert_eq!(default_path(None, None), None);
1080 }
1081}