summaryrefslogtreecommitdiff
path: root/makima/src/daemon/config.rs
blob: 79c93419128239347c73e407b862d185e0113ad7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! Configuration management for the makima daemon.

use config::{Config, Environment, File};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::PathBuf;

/// Bubblewrap sandbox configuration for Claude processes.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct BubblewrapConfig {
    /// Enable bubblewrap sandboxing.
    #[serde(default)]
    pub enabled: bool,

    /// Path to bwrap binary (default: 'bwrap').
    #[serde(default = "default_bwrap_command")]
    pub bwrap_command: String,

    /// Allow network access inside sandbox (default: true).
    #[serde(default = "default_true")]
    pub network: bool,

    /// Additional paths to bind read-only.
    #[serde(default)]
    pub ro_bind: Vec<PathBuf>,

    /// Additional paths to bind read-write.
    #[serde(default)]
    pub rw_bind: Vec<PathBuf>,
}

fn default_bwrap_command() -> String {
    "bwrap".to_string()
}

fn default_true() -> bool {
    true
}

/// Root daemon configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct DaemonConfig {
    /// Server connection settings.
    #[serde(default)]
    pub server: ServerConfig,

    /// Worktree settings.
    #[serde(default)]
    pub worktree: WorktreeConfig,

    /// Process settings.
    #[serde(default)]
    pub process: ProcessConfig,

    /// Local database settings.
    #[serde(default)]
    pub local_db: LocalDbConfig,

    /// Logging settings.
    #[serde(default)]
    pub logging: LoggingConfig,

    /// Repositories to auto-clone on startup.
    #[serde(default)]
    pub repos: ReposConfig,
}

/// Server connection configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct ServerConfig {
    /// WebSocket URL of makima server (e.g., ws://localhost:8080 or wss://makima.example.com).
    /// Defaults to wss://api.makima.jp.
    #[serde(default = "default_server_url")]
    pub url: String,

    /// API key for authentication.
    #[serde(default, alias = "apikey")]
    pub api_key: String,

    /// Heartbeat interval in seconds.
    #[serde(default = "default_heartbeat_interval", alias = "heartbeatintervalsecs")]
    pub heartbeat_interval_secs: u64,

    /// Reconnect interval in seconds after connection loss.
    #[serde(default = "default_reconnect_interval", alias = "reconnectintervalsecs")]
    pub reconnect_interval_secs: u64,

    /// Maximum reconnect attempts before giving up (0 = infinite).
    #[serde(default, alias = "maxreconnectattempts")]
    pub max_reconnect_attempts: u32,
}

fn default_heartbeat_interval() -> u64 {
    30
}

fn default_reconnect_interval() -> u64 {
    5
}

fn default_server_url() -> String {
    "wss://api.makima.jp".to_string()
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            url: default_server_url(),
            api_key: String::new(),
            heartbeat_interval_secs: default_heartbeat_interval(),
            reconnect_interval_secs: default_reconnect_interval(),
            max_reconnect_attempts: 0,
        }
    }
}

/// Worktree configuration for task isolation.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct WorktreeConfig {
    /// Base directory for worktrees (~/.makima/worktrees).
    #[serde(default = "default_worktree_base_dir", alias = "basedir")]
    pub base_dir: PathBuf,

    /// Base directory for cloned repositories (~/.makima/repos).
    #[serde(default = "default_repos_base_dir", alias = "reposdir")]
    pub repos_dir: PathBuf,

    /// Branch prefix for task branches.
    #[serde(default = "default_branch_prefix", alias = "branchprefix")]
    pub branch_prefix: String,

    /// Clean up worktrees on daemon start.
    #[serde(default, alias = "cleanuponstart")]
    pub cleanup_on_start: bool,

    /// Default target repository path for pushing completed branches.
    /// Used when task.target_repo_path is not set.
    #[serde(default, alias = "defaulttargetrepo")]
    pub default_target_repo: Option<PathBuf>,
}

fn default_worktree_base_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".makima")
        .join("worktrees")
}

fn default_repos_base_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".makima")
        .join("repos")
}

fn default_branch_prefix() -> String {
    "makima/task-".to_string()
}

impl Default for WorktreeConfig {
    fn default() -> Self {
        Self {
            base_dir: default_worktree_base_dir(),
            repos_dir: default_repos_base_dir(),
            branch_prefix: default_branch_prefix(),
            cleanup_on_start: false,
            default_target_repo: None,
        }
    }
}

/// Process configuration for Claude Code subprocess execution.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct ProcessConfig {
    /// Path or command for Claude Code CLI.
    #[serde(default = "default_claude_command", alias = "claudecommand")]
    pub claude_command: String,

    /// Additional arguments to pass to Claude Code.
    /// These are added after the default arguments.
    #[serde(default, alias = "claudeargs")]
    pub claude_args: Vec<String>,

    /// Arguments to pass before the default arguments.
    /// Useful for overriding defaults.
    #[serde(default, alias = "claudepreargs")]
    pub claude_pre_args: Vec<String>,

    /// Skip the --dangerously-skip-permissions flag (default: false).
    /// Set to true if you want to use Claude's permission system.
    #[serde(default, alias = "enablepermissions")]
    pub enable_permissions: bool,

    /// Skip the --verbose flag (default: false).
    #[serde(default, alias = "disableverbose")]
    pub disable_verbose: bool,

    /// Maximum concurrent tasks.
    #[serde(default = "default_max_tasks", alias = "maxconcurrenttasks")]
    pub max_concurrent_tasks: u32,

    /// Default timeout for tasks in seconds (0 = no timeout).
    #[serde(default, alias = "defaulttimeoutsecs")]
    pub default_timeout_secs: u64,

    /// Additional environment variables to pass to Claude Code.
    #[serde(default, alias = "envvars")]
    pub env_vars: HashMap<String, String>,

    /// Bubblewrap sandbox configuration.
    #[serde(default)]
    pub bubblewrap: BubblewrapConfig,

    /// Interval in seconds between heartbeat commits (WIP checkpoints).
    /// Set to 0 to disable. Default: 300 (5 minutes).
    #[serde(default = "default_heartbeat_commit_interval", alias = "heartbeatcommitintervalsecs")]
    pub heartbeat_commit_interval_secs: u64,

    /// Maximum iterations for autonomous task loops.
    /// Set to 0 for unlimited (not recommended). Default: 10.
    #[serde(default = "default_max_iterations", alias = "maxiterations")]
    pub max_iterations: u32,
}

fn default_claude_command() -> String {
    "claude".to_string()
}

fn default_heartbeat_commit_interval() -> u64 {
    300 // 5 minutes
}

fn default_max_iterations() -> u32 {
    10
}

fn default_max_tasks() -> u32 {
    4
}

impl Default for ProcessConfig {
    fn default() -> Self {
        Self {
            claude_command: default_claude_command(),
            claude_args: Vec::new(),
            claude_pre_args: Vec::new(),
            enable_permissions: false,
            disable_verbose: false,
            max_concurrent_tasks: default_max_tasks(),
            default_timeout_secs: 0,
            env_vars: HashMap::new(),
            bubblewrap: BubblewrapConfig::default(),
            heartbeat_commit_interval_secs: default_heartbeat_commit_interval(),
            max_iterations: default_max_iterations(),
        }
    }
}

/// Local database configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct LocalDbConfig {
    /// Path to local SQLite database.
    #[serde(default = "default_db_path")]
    pub path: PathBuf,
}

impl Default for LocalDbConfig {
    fn default() -> Self {
        Self {
            path: default_db_path(),
        }
    }
}

fn default_db_path() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".makima")
        .join("daemon.db")
}

/// Logging configuration.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct LoggingConfig {
    /// Log level: "trace", "debug", "info", "warn", "error".
    #[serde(default = "default_log_level")]
    pub level: String,

    /// Log format: "pretty" or "json".
    #[serde(default = "default_log_format")]
    pub format: String,
}

fn default_log_level() -> String {
    "info".to_string()
}

fn default_log_format() -> String {
    "pretty".to_string()
}

/// Repository auto-clone configuration.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ReposConfig {
    /// Directory to clone repositories into (default: ~/.makima/home).
    #[serde(default = "default_home_dir")]
    pub home_dir: PathBuf,

    /// List of repositories to auto-clone on startup.
    /// Each entry can be a URL (e.g., "https://github.com/user/repo.git")
    /// or a shorthand (e.g., "github:user/repo").
    #[serde(default, alias = "autoclone")]
    pub auto_clone: Vec<RepoEntry>,
}

/// A repository entry for auto-cloning.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum RepoEntry {
    /// Simple URL string.
    Url(String),
    /// Detailed configuration.
    Config {
        /// Repository URL.
        url: String,
        /// Custom directory name (defaults to repo name from URL).
        #[serde(default)]
        name: Option<String>,
        /// Branch to checkout after cloning (defaults to default branch).
        #[serde(default)]
        branch: Option<String>,
        /// Whether to do a shallow clone (default: false).
        #[serde(default)]
        shallow: bool,
    },
}

impl RepoEntry {
    /// Get the URL for this repo entry.
    pub fn url(&self) -> &str {
        match self {
            RepoEntry::Url(url) => url,
            RepoEntry::Config { url, .. } => url,
        }
    }

    /// Get the custom name, if any.
    pub fn name(&self) -> Option<&str> {
        match self {
            RepoEntry::Url(_) => None,
            RepoEntry::Config { name, .. } => name.as_deref(),
        }
    }

    /// Get the branch to checkout, if any.
    pub fn branch(&self) -> Option<&str> {
        match self {
            RepoEntry::Url(_) => None,
            RepoEntry::Config { branch, .. } => branch.as_deref(),
        }
    }

    /// Whether to do a shallow clone.
    pub fn shallow(&self) -> bool {
        match self {
            RepoEntry::Url(_) => false,
            RepoEntry::Config { shallow, .. } => *shallow,
        }
    }

    /// Get the directory name to use (either custom name or derived from URL).
    pub fn dir_name(&self) -> Option<String> {
        if let Some(name) = self.name() {
            return Some(name.to_string());
        }

        // Derive from URL
        let url = self.url();

        // Handle shorthand formats
        let url = if url.starts_with("github:") {
            url.strip_prefix("github:").unwrap_or(url)
        } else if url.starts_with("gitlab:") {
            url.strip_prefix("gitlab:").unwrap_or(url)
        } else {
            url
        };

        // Extract repo name from URL
        url.trim_end_matches('/')
            .trim_end_matches(".git")
            .rsplit('/')
            .next()
            .map(|s| s.to_string())
    }

    /// Expand the URL (e.g., convert shorthand to full URL).
    pub fn expanded_url(&self) -> String {
        let url = self.url();

        if url.starts_with("github:") {
            format!("https://github.com/{}.git", url.strip_prefix("github:").unwrap_or(""))
        } else if url.starts_with("gitlab:") {
            format!("https://gitlab.com/{}.git", url.strip_prefix("gitlab:").unwrap_or(""))
        } else {
            url.to_string()
        }
    }
}

fn default_home_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".makima")
        .join("home")
}

impl DaemonConfig {
    /// Load configuration from files and environment variables.
    ///
    /// Configuration sources (in order of precedence):
    /// 1. Environment variables (MAKIMA_API_KEY, MAKIMA_DAEMON_SERVER_URL, etc.)
    /// 2. ./makima-daemon.toml (current directory)
    /// 3. ~/.config/makima-daemon/config.toml
    /// 4. /etc/makima-daemon/config.toml (Linux only)
    ///
    /// Environment variable examples:
    /// - MAKIMA_API_KEY=your-api-key (preferred)
    /// - MAKIMA_DAEMON_SERVER_URL=ws://localhost:8080
    /// - MAKIMA_DAEMON_PROCESS_MAXCONCURRENTTASKS=4
    pub fn load() -> Result<Self, config::ConfigError> {
        Self::load_from_path(None)
    }

    /// Load configuration from a specific path plus standard sources.
    fn load_from_path(config_path: Option<&std::path::Path>) -> Result<Self, config::ConfigError> {
        let mut builder = Config::builder();

        // System-wide config (Linux only)
        #[cfg(target_os = "linux")]
        {
            builder = builder.add_source(
                File::with_name("/etc/makima-daemon/config").required(false),
            );
        }

        // User config
        if let Some(config_dir) = dirs::config_dir() {
            let user_config = config_dir.join("makima-daemon").join("config");
            builder = builder.add_source(
                File::with_name(user_config.to_str().unwrap_or("")).required(false),
            );
        }

        // Local config
        builder = builder.add_source(File::with_name("makima-daemon").required(false));

        // Custom config file (if provided)
        if let Some(path) = config_path {
            builder = builder.add_source(
                File::with_name(path.to_str().unwrap_or("")).required(true),
            );
        }

        // Environment variables with underscore separator for nesting
        // e.g., MAKIMA_DAEMON_SERVER_URL -> server.url
        //       MAKIMA_DAEMON_SERVER_APIKEY -> server.api_key
        builder = builder.add_source(
            Environment::with_prefix("MAKIMA_DAEMON")
                .separator("_")
                .try_parsing(true),
        );

        let config = builder.build()?;
        let mut config: DaemonConfig = config.try_deserialize()?;

        // Check for MAKIMA_API_KEY environment variable (preferred over MAKIMA_DAEMON_SERVER_APIKEY)
        if let Ok(api_key) = std::env::var("MAKIMA_API_KEY") {
            config.server.api_key = api_key;
        }

        // Validate required fields (don't validate here - let load_with_cli do final validation)
        Ok(config)
    }

    /// Validate that required configuration fields are set.
    pub fn validate(&self) -> Result<(), config::ConfigError> {
        if self.server.api_key.is_empty() {
            return Err(config::ConfigError::Message(
                "API key is required. Set via MAKIMA_API_KEY, config file, or --api-key".to_string()
            ));
        }
        Ok(())
    }

    /// Load configuration with CLI argument overrides.
    ///
    /// Configuration sources (in order of precedence, highest first):
    /// 1. CLI arguments
    /// 2. Environment variables
    /// 3. Custom config file (if --config specified)
    /// 4. ./makima-daemon.toml (current directory)
    /// 5. ~/.config/makima-daemon/config.toml
    /// 6. /etc/makima-daemon/config.toml (Linux only)
    /// 7. Default values
    pub fn load_with_cli(cli: &super::cli::daemon::DaemonArgs) -> Result<Self, config::ConfigError> {
        Self::load_with_daemon_args(cli)
    }

    /// Load configuration from various sources with daemon CLI overrides.
    pub fn load_with_daemon_args(args: &super::cli::daemon::DaemonArgs) -> Result<Self, config::ConfigError> {
        // Load base config (with optional custom config file)
        let mut config = Self::load_from_path(args.config.as_deref())?;

        // Apply CLI overrides (highest priority)
        if let Some(ref repos_dir) = args.repos_dir {
            config.worktree.repos_dir = repos_dir.clone();
        }
        if let Some(ref worktrees_dir) = args.worktrees_dir {
            config.worktree.base_dir = worktrees_dir.clone();
        }
        if let Some(ref server_url) = args.server_url {
            config.server.url = server_url.clone();
        }
        if let Some(ref api_key) = args.api_key {
            config.server.api_key = api_key.clone();
        }
        if let Some(max_tasks) = args.max_tasks {
            config.process.max_concurrent_tasks = max_tasks;
        }
        // Log level is always set (has default)
        config.logging.level = args.log_level.clone();

        // Enable bubblewrap if --bubblewrap flag is set
        if args.bubblewrap {
            config.process.bubblewrap.enabled = true;
        }

        // Apply max_iterations if CLI flag is set
        if let Some(max_iterations) = args.max_iterations {
            config.process.max_iterations = max_iterations;
        }

        // Validate required fields after all sources are merged
        config.validate()?;

        Ok(config)
    }

    /// Create a minimal config for testing.
    #[cfg(test)]
    pub fn test_config() -> Self {
        Self {
            server: ServerConfig {
                url: "ws://localhost:8080".to_string(),
                api_key: "test-key".to_string(),
                heartbeat_interval_secs: 30,
                reconnect_interval_secs: 5,
                max_reconnect_attempts: 0,
            },
            worktree: WorktreeConfig {
                base_dir: PathBuf::from("/tmp/makima-daemon-test/worktrees"),
                repos_dir: PathBuf::from("/tmp/makima-daemon-test/repos"),
                branch_prefix: "makima/task-".to_string(),
                cleanup_on_start: true,
                default_target_repo: None,
            },
            process: ProcessConfig {
                claude_command: "claude".to_string(),
                claude_args: Vec::new(),
                claude_pre_args: Vec::new(),
                enable_permissions: false,
                disable_verbose: false,
                max_concurrent_tasks: 2,
                default_timeout_secs: 0,
                env_vars: HashMap::new(),
                bubblewrap: BubblewrapConfig::default(),
                heartbeat_commit_interval_secs: 300,
                max_iterations: 10,
            },
            local_db: LocalDbConfig {
                path: PathBuf::from("/tmp/makima-daemon-test/state.db"),
            },
            logging: LoggingConfig::default(),
            repos: ReposConfig::default(),
        }
    }
}

/// Helper module for dirs crate (minimal subset).
mod dirs {
    use std::path::PathBuf;

    pub fn home_dir() -> Option<PathBuf> {
        std::env::var("HOME").ok().map(PathBuf::from)
    }

    pub fn config_dir() -> Option<PathBuf> {
        #[cfg(target_os = "macos")]
        {
            std::env::var("HOME")
                .ok()
                .map(|h| PathBuf::from(h).join("Library").join("Application Support"))
        }
        #[cfg(target_os = "linux")]
        {
            std::env::var("XDG_CONFIG_HOME")
                .ok()
                .map(PathBuf::from)
                .or_else(|| std::env::var("HOME").ok().map(|h| PathBuf::from(h).join(".config")))
        }
        #[cfg(target_os = "windows")]
        {
            std::env::var("APPDATA").ok().map(PathBuf::from)
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
        {
            None
        }
    }
}