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: String,
37 pub reviewer: 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: single_lane("roles.planner", &raw.planner, lanes)?,
482 reviewer: single_lane("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 single_lane(
498 key: &str,
499 names: &[String],
500 lanes: &BTreeMap<String, Lane>,
501) -> Result<String, ConfigError> {
502 let [name] = names else {
503 return Err(invalid(key, "name exactly one lane"));
504 };
505 let lane = existing(key, name, lanes)?;
506 if lane.is_off() || lane.is_manual() {
507 return Err(invalid(
508 key,
509 format!(
510 "lane {name} is manual or off; planner and reviewer lanes must run automatically"
511 ),
512 ));
513 }
514 Ok(name.clone())
515}
516
517fn worker_lanes(
518 names: &[String],
519 lanes: &BTreeMap<String, Lane>,
520) -> Result<Vec<String>, ConfigError> {
521 const KEY: &str = "roles.worker";
522 if names.is_empty() {
523 return Err(invalid(KEY, "name at least one lane"));
524 }
525 for (index, name) in names.iter().enumerate() {
526 if names[..index].contains(name) {
527 return Err(invalid(KEY, format!("lane {name} is named twice")));
528 }
529 let _ = existing(KEY, name, lanes)?;
530 }
531 if names.iter().all(|name| lanes[name].is_off()) {
532 return Err(invalid(KEY, "at least one worker lane must not be off"));
533 }
534 Ok(names.to_vec())
535}
536
537pub fn to_toml(config: &Config) -> String {
539 let out = OutConfig {
540 run: OutRun {
541 max_attempts: config.run.max_attempts,
542 idle_timeout: format_duration(config.run.idle_timeout),
543 job_timeout: format_duration(config.run.job_timeout),
544 },
545 policy: OutPolicy {
546 min_remaining: config.policy.min_remaining,
547 },
548 roles: OutRoles {
549 planner: [&config.roles.planner],
550 reviewer: [&config.roles.reviewer],
551 worker: &config.roles.worker,
552 },
553 lanes: config
554 .lanes
555 .iter()
556 .map(|(name, lane)| (name.clone(), out_lane(lane)))
557 .collect(),
558 };
559 toml::to_string_pretty(&out).unwrap_or_default()
560}
561
562pub fn save(path: &Path, config: &Config) -> Result<(), ConfigError> {
564 let err = |e: std::io::Error| ConfigError::Unwritable {
565 path: path.to_path_buf(),
566 message: e.to_string(),
567 };
568 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
569 std::fs::create_dir_all(parent).map_err(err)?;
570 }
571 write_text_atomically(path, &to_toml(config)).map_err(err)
572}
573
574#[derive(Serialize)]
575struct OutConfig<'a> {
576 run: OutRun,
577 policy: OutPolicy,
578 roles: OutRoles<'a>,
579 lanes: BTreeMap<String, OutLane<'a>>,
580}
581
582#[derive(Serialize)]
583struct OutRun {
584 max_attempts: u32,
585 idle_timeout: String,
586 job_timeout: String,
587}
588
589#[derive(Serialize)]
590struct OutPolicy {
591 min_remaining: f64,
592}
593
594#[derive(Serialize)]
595struct OutRoles<'a> {
596 planner: [&'a String; 1],
597 reviewer: [&'a String; 1],
598 worker: &'a [String],
599}
600
601#[derive(Serialize)]
602struct OutLane<'a> {
603 harness: &'static str,
604 #[serde(skip_serializing_if = "Option::is_none")]
605 bin: Option<&'a str>,
606 #[serde(skip_serializing_if = "Option::is_none")]
607 provider: Option<CodexProvider>,
608 #[serde(skip_serializing_if = "Option::is_none")]
609 model: Option<&'a str>,
610 #[serde(skip_serializing_if = "Option::is_none")]
611 effort: Option<Effort>,
612 #[serde(skip_serializing_if = "Option::is_none")]
613 mode: Option<Mode>,
614 #[serde(skip_serializing_if = "Option::is_none")]
615 quota_group: Option<&'a str>,
616 #[serde(skip_serializing_if = "Option::is_none")]
617 accept_vendor_terms_risk: Option<bool>,
618 #[serde(skip_serializing_if = "Option::is_none")]
619 script: Option<String>,
620}
621
622fn out_lane(lane: &Lane) -> OutLane<'_> {
623 let custom_bin = (lane.bin != lane.harness.name()).then_some(lane.bin.as_str());
624 let is = |kind| lane.harness == kind;
625 OutLane {
626 harness: lane.harness.name(),
627 bin: custom_bin,
628 provider: lane.provider.filter(|_| is(HarnessKind::Codex)),
629 model: (!is(HarnessKind::Fake))
630 .then_some(lane.model.as_deref())
631 .flatten(),
632 effort: is(HarnessKind::Claude).then_some(lane.effort),
633 mode: is(HarnessKind::Agy).then_some(lane.mode),
634 quota_group: is(HarnessKind::Agy)
635 .then_some(lane.quota_group.as_deref())
636 .flatten(),
637 accept_vendor_terms_risk: (is(HarnessKind::Agy) && lane.accept_vendor_terms_risk)
638 .then_some(true),
639 script: is(HarnessKind::Fake)
640 .then(|| lane.script.as_ref().map(|p| p.display().to_string()))
641 .flatten(),
642 }
643}
644
645fn format_duration(duration: Duration) -> String {
646 let secs = duration.as_secs();
647 if secs >= 3600 && secs.is_multiple_of(3600) {
648 format!("{}h", secs / 3600)
649 } else if secs >= 60 && secs.is_multiple_of(60) {
650 format!("{}m", secs / 60)
651 } else {
652 format!("{secs}s")
653 }
654}
655
656#[cfg(test)]
657mod tests {
658 use super::*;
659
660 const BASE: &str = r#"
661[roles]
662planner = ["plan"]
663reviewer = ["review"]
664worker = ["deepseek"]
665
666[lanes.plan]
667harness = "claude"
668model = "sonnet"
669
670[lanes.review]
671harness = "claude"
672model = "sonnet"
673
674[lanes.deepseek]
675harness = "codex"
676model = "deepseek-flash"
677"#;
678
679 const GEMINI: &str = "\n[lanes.gemini]\nharness = \"agy\"\nmodel = \"m\"\n";
680
681 fn with(extra: &str) -> String {
683 format!("{BASE}{extra}\n")
684 }
685
686 fn with_gemini(extra: &str) -> String {
687 with(&format!("{GEMINI}{extra}")).replace(
688 r#"worker = ["deepseek"]"#,
689 r#"worker = ["deepseek", "gemini"]"#,
690 )
691 }
692
693 fn invalid_key(text: &str) -> String {
694 match parse(text, false) {
695 Err(ConfigError::Invalid { key, .. }) => key,
696 other => panic!("expected an invalid key, got {other:?}"),
697 }
698 }
699
700 #[test]
701 fn the_example_is_valid_and_keeps_agy_manual() {
702 let config = parse(EXAMPLE, false).unwrap();
703
704 assert_eq!(config.roles.worker, ["gemini", "deepseek"]);
705 assert_eq!(config.lanes["plan"].model.as_deref(), Some("opus"));
706 assert_eq!(config.lanes["gemini"].mode, Mode::Handover);
707 assert!(config.lanes["gemini"].is_manual());
708 assert_eq!(config.lanes["deepseek"].mode, Mode::Direct);
709 assert_eq!(
710 config.lanes["deepseek"].provider,
711 Some(CodexProvider::Deepseek)
712 );
713 assert_eq!(config.lanes["review"].effort, Effort::Low);
714 }
715
716 #[test]
717 fn missing_settings_take_their_defaults() {
718 let config = parse(BASE, false).unwrap();
719
720 assert_eq!(config.run.max_attempts, 5);
721 assert_eq!(config.run.idle_timeout, Duration::from_secs(300));
722 assert_eq!(config.run.job_timeout, Duration::from_secs(1800));
723 assert_eq!(config.policy.min_remaining, 0.05);
724 assert_eq!(config.lanes["deepseek"].bin, "codex");
725 assert_eq!(config.lanes["plan"].effort, Effort::Medium);
726 assert_eq!(config.roles.planner, "plan");
727 }
728
729 #[test]
730 fn an_unknown_key_or_a_wrong_type_is_a_syntax_error_naming_it() {
731 let unknown = parse(&with("\n[run]\nmax_attempt = 3"), false);
732 let wrong_type = parse(&with("\n[run]\nmax_attempts = \"3\""), false);
733
734 assert!(matches!(&unknown, Err(ConfigError::Syntax(m)) if m.contains("max_attempt")));
735 assert!(matches!(wrong_type, Err(ConfigError::Syntax(_))));
736 }
737
738 #[test]
739 fn max_attempts_must_be_from_1_to_20() {
740 assert_eq!(
741 invalid_key(&with("\n[run]\nmax_attempts = 0")),
742 "run.max_attempts"
743 );
744 assert_eq!(
745 invalid_key(&with("\n[run]\nmax_attempts = 21")),
746 "run.max_attempts"
747 );
748 assert_eq!(
749 parse(&with("\n[run]\nmax_attempts = 20"), false)
750 .unwrap()
751 .run
752 .max_attempts,
753 20
754 );
755 }
756
757 #[test]
758 fn durations_need_a_unit_and_at_least_one_second() {
759 for bad in ["\"5\"", "\"5d\"", "\"m\"", "\"0s\"", "\"-1s\""] {
760 assert_eq!(
761 invalid_key(&with(&format!("\n[run]\nidle_timeout = {bad}"))),
762 "run.idle_timeout",
763 "{bad}"
764 );
765 }
766 let config = parse(
767 &with("\n[run]\nidle_timeout = \"1s\"\njob_timeout = \"2h\""),
768 false,
769 )
770 .unwrap();
771 assert_eq!(config.run.idle_timeout, Duration::from_secs(1));
772 assert_eq!(config.run.job_timeout, Duration::from_secs(7200));
773 }
774
775 #[test]
776 fn parse_duration_reads_seconds_minutes_and_hours_only() {
777 assert_eq!(parse_duration("45s"), Some(Duration::from_secs(45)));
778 assert_eq!(parse_duration("5m"), Some(Duration::from_secs(300)));
779 assert_eq!(parse_duration("1h"), Some(Duration::from_secs(3600)));
780 for bad in ["", "s", "5", "5x", " 5m", "5.5m", "+5m", "é"] {
781 assert_eq!(parse_duration(bad), None, "{bad:?}");
782 }
783 }
784
785 #[test]
786 fn min_remaining_must_be_from_0_to_1() {
787 assert_eq!(
788 invalid_key(&with("\n[policy]\nmin_remaining = 1.5")),
789 "policy.min_remaining"
790 );
791 assert_eq!(
792 invalid_key(&with("\n[policy]\nmin_remaining = -0.1")),
793 "policy.min_remaining"
794 );
795 assert_eq!(
796 parse(&with("\n[policy]\nmin_remaining = 1.0"), false)
797 .unwrap()
798 .policy
799 .min_remaining,
800 1.0
801 );
802 }
803
804 #[test]
805 fn a_lane_name_must_be_safe() {
806 let text = with("\n[lanes.Deep]\nharness = \"codex\"\nmodel = \"m\"");
807
808 assert_eq!(invalid_key(&text), "lanes.Deep");
809 }
810
811 #[test]
812 fn an_unknown_harness_is_rejected() {
813 let text = BASE.replace(r#"harness = "codex""#, r#"harness = "aider""#);
814
815 assert_eq!(invalid_key(&text), "lanes.deepseek.harness");
816 }
817
818 #[test]
819 fn a_key_on_a_lane_whose_harness_it_does_not_apply_to_is_rejected() {
820 assert_eq!(
821 invalid_key(&with("effort = \"low\"")),
822 "lanes.deepseek.effort"
823 );
824 assert_eq!(invalid_key(&with("mode = \"off\"")), "lanes.deepseek.mode");
825 assert_eq!(
826 invalid_key(&with("quota_group = \"g\"")),
827 "lanes.deepseek.quota_group"
828 );
829 assert_eq!(
830 invalid_key(&with("accept_vendor_terms_risk = true")),
831 "lanes.deepseek.accept_vendor_terms_risk"
832 );
833 assert_eq!(
834 invalid_key(&with("script = \"s.json\"")),
835 "lanes.deepseek.script"
836 );
837 assert_eq!(
838 invalid_key(&with(
839 "\n[lanes.other]\nharness = \"claude\"\nmodel = \"opus\"\nprovider = \"openai\""
840 )),
841 "lanes.other.provider"
842 );
843 }
844
845 #[test]
846 fn a_lane_needs_a_model() {
847 let text = BASE.replace("model = \"deepseek-flash\"\n", "");
848
849 assert_eq!(invalid_key(&text), "lanes.deepseek.model");
850 }
851
852 #[test]
853 fn effort_must_be_low_medium_or_high() {
854 let text = BASE.replacen(
855 "model = \"sonnet\"",
856 "model = \"sonnet\"\neffort = \"max\"",
857 1,
858 );
859
860 assert_eq!(invalid_key(&text), "lanes.plan.effort");
861 }
862
863 #[test]
864 fn an_agy_lane_is_manual_unless_told_otherwise() {
865 let config = parse(&with_gemini(""), false).unwrap();
866
867 assert_eq!(config.lanes["gemini"].mode, Mode::Handover);
868 assert_eq!(
869 invalid_key(&with_gemini("mode = \"auto\"")),
870 "lanes.gemini.mode"
871 );
872 }
873
874 #[test]
875 fn direct_agy_needs_the_risk_acknowledgement_and_a_quota_group() {
876 let no_ack = with_gemini("mode = \"direct\"\nquota_group = \"Gemini Models\"");
877 let no_group = with_gemini("mode = \"direct\"\naccept_vendor_terms_risk = true");
878 let both =
879 with_gemini("mode = \"direct\"\nquota_group = \"G\"\naccept_vendor_terms_risk = true");
880
881 assert_eq!(
882 invalid_key(&no_ack),
883 "lanes.gemini.accept_vendor_terms_risk"
884 );
885 assert_eq!(invalid_key(&no_group), "lanes.gemini.quota_group");
886 assert_eq!(
887 parse(&both, false).unwrap().lanes["gemini"].mode,
888 Mode::Direct
889 );
890 }
891
892 #[test]
893 fn fake_lanes_need_the_test_switch_and_a_script() {
894 let fake = BASE.replace(
895 "harness = \"codex\"\nmodel = \"deepseek-flash\"",
896 "harness = \"fake\"\nscript = \"s.json\"",
897 );
898 let no_script = BASE.replace(
899 "harness = \"codex\"\nmodel = \"deepseek-flash\"",
900 "harness = \"fake\"",
901 );
902
903 assert_eq!(invalid_key(&fake), "lanes.deepseek.harness");
904 assert_eq!(
905 parse(&fake, true).unwrap().lanes["deepseek"].script,
906 Some(PathBuf::from("s.json"))
907 );
908 assert!(
909 matches!(parse(&no_script, true), Err(ConfigError::Invalid { key, .. }) if key == "lanes.deepseek.script")
910 );
911 }
912
913 #[test]
914 fn a_fake_lane_may_serve_every_role() {
915 let text = r#"
916[roles]
917planner = ["f"]
918reviewer = ["f"]
919worker = ["f"]
920
921[lanes.f]
922harness = "fake"
923script = "s.json"
924"#;
925
926 assert!(parse(text, true).is_ok());
927 }
928
929 #[test]
930 fn planner_and_reviewer_accept_any_automatic_lane_and_reject_manual_or_off() {
931 let two = BASE.replace(r#"planner = ["plan"]"#, r#"planner = ["plan", "review"]"#);
932 let unknown = BASE.replace(r#"reviewer = ["review"]"#, r#"reviewer = ["nobody"]"#);
933 let worker_as_reviewer =
934 BASE.replace(r#"reviewer = ["review"]"#, r#"reviewer = ["deepseek"]"#);
935 let manual_planner =
936 with_gemini("").replace(r#"planner = ["plan"]"#, r#"planner = ["gemini"]"#);
937 let off_reviewer = with_gemini("mode = \"off\"")
938 .replace(r#"reviewer = ["review"]"#, r#"reviewer = ["gemini"]"#);
939 let direct_agy_planner =
940 with_gemini("mode = \"direct\"\nquota_group = \"G\"\naccept_vendor_terms_risk = true")
941 .replace(r#"planner = ["plan"]"#, r#"planner = ["gemini"]"#);
942
943 assert_eq!(invalid_key(&two), "roles.planner");
944 assert_eq!(invalid_key(&unknown), "roles.reviewer");
945 assert_eq!(
946 parse(&worker_as_reviewer, false).unwrap().roles.reviewer,
947 "deepseek"
948 );
949 assert_eq!(invalid_key(&manual_planner), "roles.planner");
950 assert_eq!(invalid_key(&off_reviewer), "roles.reviewer");
951 assert_eq!(
952 parse(&direct_agy_planner, false).unwrap().roles.planner,
953 "gemini"
954 );
955 }
956
957 #[test]
958 fn the_worker_chain_accepts_any_distinct_lanes_with_one_not_off() {
959 let empty = BASE.replace(r#"worker = ["deepseek"]"#, "worker = []");
960 let twice = BASE.replace(
961 r#"worker = ["deepseek"]"#,
962 r#"worker = ["deepseek", "deepseek"]"#,
963 );
964 let claude = BASE.replace(r#"worker = ["deepseek"]"#, r#"worker = ["plan"]"#);
965 let all_off = with_gemini("mode = \"off\"").replace(
966 r#"worker = ["deepseek", "gemini"]"#,
967 r#"worker = ["gemini"]"#,
968 );
969
970 for text in [empty, twice, all_off] {
971 assert_eq!(invalid_key(&text), "roles.worker");
972 }
973 assert_eq!(parse(&claude, false).unwrap().roles.worker, ["plan"]);
974 }
975
976 #[test]
977 fn codex_provider_defaults_to_deepseek_and_accepts_openai() {
978 let openai =
979 with("\n[lanes.gpt]\nharness = \"codex\"\nprovider = \"openai\"\nmodel = \"gpt-5.4\"")
980 .replace(
981 r#"worker = ["deepseek"]"#,
982 r#"worker = ["deepseek", "gpt"]"#,
983 );
984 let bad = with("provider = \"anthropic\"");
985
986 let config = parse(&openai, false).unwrap();
987
988 assert_eq!(
989 config.lanes["deepseek"].provider,
990 Some(CodexProvider::Deepseek)
991 );
992 assert_eq!(config.lanes["gpt"].provider, Some(CodexProvider::Openai));
993 assert_eq!(invalid_key(&bad), "lanes.deepseek.provider");
994 }
995
996 #[test]
997 fn to_toml_and_save_round_trip_every_harness_cleanly() {
998 let mut config = parse(EXAMPLE, false).unwrap();
999 config.run.idle_timeout = Duration::from_secs(3600);
1000 config.run.job_timeout = Duration::from_secs(61);
1001 let openai_lane = Lane {
1002 harness: HarnessKind::Codex,
1003 bin: "/usr/local/bin/codex".into(),
1004 provider: Some(CodexProvider::Openai),
1005 model: Some("gpt-5.4".into()),
1006 effort: Effort::Medium,
1007 mode: Mode::Direct,
1008 quota_group: None,
1009 accept_vendor_terms_risk: false,
1010 script: None,
1011 };
1012 config.lanes.insert("openai".into(), openai_lane);
1013 config.roles.worker.push("openai".into());
1014
1015 let dir = tempfile::tempdir().unwrap();
1016 let path = dir.path().join("nested").join("config.toml");
1017 save(&path, &config).unwrap();
1018 let text = std::fs::read_to_string(&path).unwrap();
1019 assert!(text.contains("idle_timeout = \"1h\""));
1020 assert!(text.contains("job_timeout = \"61s\""));
1021 assert!(!text.contains("bin = \"codex\""));
1022 let reloaded = load(&path, false).unwrap();
1023
1024 assert_eq!(reloaded, config);
1025 assert_eq!(format_duration(Duration::from_secs(3601)), "3601s");
1026 assert_eq!(format_duration(Duration::from_secs(60)), "1m");
1027 }
1028
1029 #[test]
1030 fn the_error_message_names_the_key_and_the_fix() {
1031 let error = parse(&with("\n[run]\nmax_attempts = 0"), false).unwrap_err();
1032
1033 assert_eq!(
1034 error.to_string(),
1035 "run.max_attempts: use a number from 1 to 20"
1036 );
1037 }
1038
1039 #[test]
1040 fn load_reports_a_missing_file_with_its_path() {
1041 let dir = tempfile::tempdir().unwrap();
1042 let path = dir.path().join("config.toml");
1043
1044 assert_eq!(load(&path, false), Err(ConfigError::Missing(path.clone())));
1045 std::fs::write(&path, BASE).unwrap();
1046 assert!(load(&path, false).is_ok());
1047 }
1048
1049 #[test]
1050 fn the_default_path_prefers_xdg_and_falls_back_to_home() {
1051 assert_eq!(
1052 default_path(Some("/x"), Some("/h")),
1053 Some(PathBuf::from("/x/onerig/config.toml"))
1054 );
1055 assert_eq!(
1056 default_path(Some(""), Some("/h")),
1057 Some(PathBuf::from("/h/.config/onerig/config.toml"))
1058 );
1059 assert_eq!(
1060 default_path(None, Some("/h")),
1061 Some(PathBuf::from("/h/.config/onerig/config.toml"))
1062 );
1063 assert_eq!(default_path(None, None), None);
1064 }
1065}