@@ -3,13 +3,72 @@ use std::{
33 path::{Path, PathBuf},
44};
55
6−use serde::Deserialize;
6+use serde::{Deserialize, Serialize};
7+
8+use crate::vm::DirectoryShare;
79
810pub const CONFIG_FILENAME: &str = "vibebox.toml";
911
10−#[derive(Debug, Default, Deserialize)]
11−pub struct ProjectConfig {
12− pub auto_shutdown_ms: Option<u64>,
12+const DEFAULT_CPU_COUNT: usize = 2;
13+const DEFAULT_RAM_MB: u64 = 2048;
14+const DEFAULT_AUTO_SHUTDOWN_MS: u64 = 20000;
15+
16+#[derive(Debug, Clone, Serialize, Deserialize)]
17+pub struct Config {
18+ #[serde(rename = "box")]
19+ pub box_cfg: BoxConfig,
20+ pub supervisor: SupervisorConfig,
21+}
22+
23+impl Default for Config {
24+ fn default() -> Self {
25+ Self {
26+ box_cfg: BoxConfig::default(),
27+ supervisor: SupervisorConfig::default(),
28+ }
29+ }
30+}
31+
32+#[derive(Debug, Clone, Serialize, Deserialize)]
33+pub struct BoxConfig {
34+ pub cpu_count: usize,
35+ pub ram_mb: u64,
36+ pub mounts: Vec<String>,
37+}
38+
39+impl Default for BoxConfig {
40+ fn default() -> Self {
41+ Self {
42+ cpu_count: default_cpu_count(),
43+ ram_mb: default_ram_mb(),
44+ mounts: Vec::new(),
45+ }
46+ }
47+}
48+
49+#[derive(Debug, Clone, Serialize, Deserialize)]
50+pub struct SupervisorConfig {
51+ pub auto_shutdown_ms: u64,
52+}
53+
54+impl Default for SupervisorConfig {
55+ fn default() -> Self {
56+ Self {
57+ auto_shutdown_ms: default_auto_shutdown_ms(),
58+ }
59+ }
60+}
61+
62+fn default_cpu_count() -> usize {
63+ DEFAULT_CPU_COUNT
64+}
65+
66+fn default_ram_mb() -> u64 {
67+ DEFAULT_RAM_MB
68+}
69+
70+fn default_auto_shutdown_ms() -> u64 {
71+ DEFAULT_AUTO_SHUTDOWN_MS
1372}
1473
1574pub fn config_path(project_root: &Path) -> PathBuf {
@@ -19,20 +78,147 @@ pub fn config_path(project_root: &Path) -> PathBuf {
1978pub fn ensure_config_file(project_root: &Path) -> Result<PathBuf, io::Error> {
2079 let path = config_path(project_root);
2180 if !path.exists() {
22− fs::write(&path, "")?;
81+ let default_config = Config::default();
82+ let contents = toml::to_string_pretty(&default_config).unwrap_or_default();
83+ fs::write(&path, contents)?;
2384 tracing::info!(path = %path.display(), "created vibebox config");
2485 }
2586 Ok(path)
2687}
2788
28−pub fn load_config(
29− project_root: &Path,
30−) -> Result<ProjectConfig, Box<dyn std::error::Error + Send + Sync>> {
31− let path = ensure_config_file(project_root)?;
32− let raw = fs::read_to_string(&path)?;
89+pub fn load_config(project_root: &Path) -> Config {
90+ let path = match ensure_config_file(project_root) {
91+ Ok(path) => path,
92+ Err(err) => die(&format!("failed to create config: {err}")),
93+ };
94+ let raw = match fs::read_to_string(&path) {
95+ Ok(raw) => raw,
96+ Err(err) => die(&format!("failed to read config: {err}")),
97+ };
98+ let trimmed = raw.trim();
3399 tracing::debug!(path = %path.display(), bytes = raw.len(), "loaded vibebox config");
34− if raw.trim().is_empty() {
35− return Ok(ProjectConfig::default());
100+ if trimmed.is_empty() {
101+ die(&format!(
102+ "config file ({}) is empty. Required fields: [box].cpu_count (integer), [box].ram_mb (integer), [box].mounts (array of strings), [supervisor].auto_shutdown_ms (integer)",
103+ path.display()
104+ ));
105+ }
106+
107+ let value: toml::Value = match toml::from_str(trimmed) {
108+ Ok(value) => value,
109+ Err(err) => die(&format!("invalid config: {err}")),
110+ };
111+ let schema_errors = validate_schema(&value);
112+ if !schema_errors.is_empty() {
113+ let message = format!(
114+ "config file ({}) is missing or invalid fields:\n- {}",
115+ path.display(),
116+ schema_errors.join("\n- ")
117+ );
118+ die(&message);
36119 }
37− Ok(toml::from_str::<ProjectConfig>(&raw)?)
120+
121+ let config: Config = match toml::from_str(trimmed) {
122+ Ok(config) => config,
123+ Err(err) => die(&format!("invalid config: {err}")),
124+ };
125+ validate_or_exit(&config);
126+ config
127+}
128+
129+fn validate_schema(value: &toml::Value) -> Vec<String> {
130+ let mut errors = Vec::new();
131+ let root = match value.as_table() {
132+ Some(table) => table,
133+ None => {
134+ errors.push("config must be a table".to_string());
135+ return errors;
136+ }
137+ };
138+
139+ match root.get("box") {
140+ None => errors.push("missing [box] table".to_string()),
141+ Some(value) => match value.as_table() {
142+ Some(table) => {
143+ validate_int(table, "cpu_count", "[box].cpu_count (integer)", &mut errors);
144+ validate_int(table, "ram_mb", "[box].ram_mb (integer)", &mut errors);
145+ validate_string_array(
146+ table,
147+ "mounts",
148+ "[box].mounts (array of strings)",
149+ &mut errors,
150+ );
151+ }
152+ None => errors.push("[box] must be a table".to_string()),
153+ },
154+ }
155+
156+ match root.get("supervisor") {
157+ None => errors.push("missing [supervisor] table".to_string()),
158+ Some(value) => match value.as_table() {
159+ Some(table) => {
160+ validate_int(
161+ table,
162+ "auto_shutdown_ms",
163+ "[supervisor].auto_shutdown_ms (integer)",
164+ &mut errors,
165+ );
166+ }
167+ None => errors.push("[supervisor] must be a table".to_string()),
168+ },
169+ }
170+
171+ errors
172+}
173+
174+fn validate_int(table: &toml::value::Table, key: &str, label: &str, errors: &mut Vec<String>) {
175+ match table.get(key) {
176+ None => errors.push(format!("missing {label}")),
177+ Some(value) => {
178+ if value.as_integer().is_none() {
179+ errors.push(format!("invalid {label}: expected integer"));
180+ }
181+ }
182+ }
183+}
184+
185+fn validate_string_array(
186+ table: &toml::value::Table,
187+ key: &str,
188+ label: &str,
189+ errors: &mut Vec<String>,
190+) {
191+ match table.get(key) {
192+ None => errors.push(format!("missing {label}")),
193+ Some(value) => match value.as_array() {
194+ Some(values) => {
195+ if values.iter().any(|value| !value.is_str()) {
196+ errors.push(format!("invalid {label}: expected array of strings"));
197+ }
198+ }
199+ None => errors.push(format!("invalid {label}: expected array of strings")),
200+ },
201+ }
202+}
203+
204+fn validate_or_exit(config: &Config) {
205+ if config.box_cfg.cpu_count == 0 {
206+ die("box.cpu_count must be >= 1");
207+ }
208+ if config.box_cfg.ram_mb == 0 {
209+ die("box.ram_mb must be >= 1");
210+ }
211+ if config.supervisor.auto_shutdown_ms == 0 {
212+ die("supervisor.auto_shutdown_ms must be >= 1");
213+ }
214+ for spec in &config.box_cfg.mounts {
215+ if let Err(err) = DirectoryShare::from_mount_spec(spec) {
216+ die(&format!("invalid mount spec '{spec}': {err}"));
217+ }
218+ }
219+}
220+
221+fn die(message: &str) -> ! {
222+ eprintln!("[vibebox] {message}");
223+ std::process::exit(1);
38224}