marver 0.0.29

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
Documentation
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
//! Defaults, read from a file instead of typed every time.
//!
//! ```text
//! $XDG_CONFIG_HOME/marver/config.toml     or  ~/.config/marver/config.toml
//! ```
//!
//! ```toml
//! # marver
//! data-dir  = "~/.local/share/marver"
//! scan-root = "~/code"
//! cap       = 3
//! harness   = "codex"
//! ```
//!
//! **The file sets defaults for the options, and nothing else.** Every key here
//! is the name of a flag with the dashes kept, so there is one name per thing
//! and no table mapping one spelling to another. A flag beats the file, the
//! file beats the built-in default, and nothing else gets a vote.
//!
//! Nothing here can put the interface and the daemon out of step. An auto-
//! started daemon is handed the *resolved* values as flags, so it inherits
//! whatever the interface worked out rather than reading the file a second time
//! and possibly differently.
//!
//! The format is a flat `key = value` list with `#` comments — a subset of TOML
//! small enough to parse by hand, and a strict enough subset that a real parser
//! could be dropped in later without invalidating anyone's file. marver
//! hand-rolls its argument parsing for the same reason: four scalar options do
//! not earn a dependency.
//!
//! **A line that does not make sense is said out loud.** Options behave the
//! other way — an unrecognised value falls back to a default in silence —
//! because a flag is typed once and read back immediately, while a file is
//! written once and trusted for months. A key with a typo in it that quietly
//! did nothing for ever is the failure mode config files actually have.

use std::path::{Path, PathBuf};

/// What the file is called, wherever it is.
pub const FILE_NAME: &str = "config.toml";

/// What the file asked for. Every field is optional: absent means "no opinion",
/// which is what lets a flag and a default both still apply.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Settings {
    pub data_dir: Option<PathBuf>,
    pub scan_root: Option<PathBuf>,
    pub cap: Option<usize>,
    /// Left as written. Parsing it means deciding what to do about a bad one,
    /// and that is a decision about how the program exits, not about a file.
    pub harness: Option<String>,
    /// The file this came from, if there was one. Reported by `marver status`,
    /// since "which file is doing this to me" is the question a config file
    /// creates.
    pub path: Option<PathBuf>,
}

/// Something in the file that could not be used.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Problem {
    Unreadable {
        path: PathBuf,
        why: String,
    },
    Malformed {
        line: usize,
    },
    UnknownKey {
        line: usize,
        key: String,
    },
    BadValue {
        line: usize,
        key: String,
        value: String,
    },
}

impl std::fmt::Display for Problem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Problem::Unreadable { path, why } => {
                write!(f, "could not read {}: {why}", path.display())
            }
            Problem::Malformed { line } => {
                write!(f, "{FILE_NAME} line {line}: not `key = value`")
            }
            Problem::UnknownKey { line, key } => write!(
                f,
                "{FILE_NAME} line {line}: no option is called `{key}` — known keys are {}",
                KEYS.join(", ")
            ),
            Problem::BadValue { line, key, value } => {
                write!(f, "{FILE_NAME} line {line}: `{key}` cannot be `{value}`")
            }
        }
    }
}

/// Every key the file may contain, for the message a typo gets.
const KEYS: &[&str] = &["data-dir", "scan-root", "cap", "harness"];

impl Settings {
    /// Read the file, or `explicit` if one was named.
    ///
    /// A file that is not there is the ordinary case and says nothing. One that
    /// is there and cannot be read is a problem, including when it was named on
    /// the command line — asking for a file by name and being given the
    /// defaults in silence is the worst of both.
    pub fn load(explicit: Option<&Path>) -> (Self, Vec<Problem>) {
        let path = explicit.map(Path::to_path_buf).unwrap_or_else(default_path);
        let text = match std::fs::read_to_string(&path) {
            Ok(text) => text,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                return (Self::default(), Vec::new());
            }
            Err(err) => {
                return (
                    Self::default(),
                    vec![Problem::Unreadable {
                        path,
                        why: err.to_string(),
                    }],
                );
            }
        };
        let (mut settings, problems) = parse(&text);
        settings.path = Some(path);
        (settings, problems)
    }
}

/// `$XDG_CONFIG_HOME/marver/config.toml`, or `~/.config/marver/config.toml`.
///
/// Fixed, rather than under the data directory, because `data-dir` is one of
/// the things the file sets — a file that lived inside the directory it names
/// could never be found in order to be asked where that directory is.
pub fn default_path() -> PathBuf {
    if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME")
        && !xdg.is_empty()
    {
        return PathBuf::from(xdg).join("marver").join(FILE_NAME);
    }
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home)
        .join(".config")
        .join("marver")
        .join(FILE_NAME)
}

fn parse(text: &str) -> (Settings, Vec<Problem>) {
    let mut settings = Settings::default();
    let mut problems = Vec::new();

    for (index, raw) in text.lines().enumerate() {
        let line = index + 1;
        let trimmed = raw.trim();
        // A `[table]` header is skipped rather than refused. There are no
        // tables to put anything in yet, and refusing one would make a file
        // that a future marver reads happily fail on this one.
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('[') {
            continue;
        }
        let Some((key, value)) = trimmed.split_once('=') else {
            problems.push(Problem::Malformed { line });
            continue;
        };
        let key = key.trim();
        let value = unquote(value.trim());

        // No key here has a useful empty value, and the two paths are the ones
        // that would take one quietly: `data-dir =` would make every path
        // marver owns relative to whichever directory it was run from. A key
        // written down and left blank is someone half-finished, so say so —
        // after the key itself is known, or a blank line under a typo would be
        // reported as the wrong mistake.
        if KEYS.contains(&key) && value.is_empty() {
            problems.push(Problem::BadValue {
                line,
                key: key.to_string(),
                value,
            });
            continue;
        }

        match key {
            "data-dir" => settings.data_dir = Some(expand(&value)),
            "scan-root" => settings.scan_root = Some(expand(&value)),
            "cap" => match value.parse() {
                Ok(cap) => settings.cap = Some(cap),
                Err(_) => problems.push(Problem::BadValue {
                    line,
                    key: key.to_string(),
                    value,
                }),
            },
            // Not parsed here — see the field.
            "harness" => settings.harness = Some(value),
            _ => problems.push(Problem::UnknownKey {
                line,
                key: key.to_string(),
            }),
        }
    }

    (settings, problems)
}

/// A value with its quotes taken off, and a trailing `#` comment dropped from
/// the ones that had none.
///
/// A comment cannot be found inside a quoted value without ambiguity — a
/// harness command may legitimately contain a `#` — so only bare values are
/// searched for one.
fn unquote(value: &str) -> String {
    for quote in ['"', '\''] {
        if let Some(rest) = value.strip_prefix(quote) {
            // From the LAST quote, not the first. Splitting at the first one
            // silently dropped everything after it, so a harness written
            // `"claude --settings "a b.json""` became `claude --settings ` and
            // started a different command line than the one on the page.
            let Some((inner, after)) = rest.rsplit_once(quote) else {
                // No closing quote at all. Everything after the opening one is
                // the value, which is what the writer meant.
                return rest.to_string();
            };
            // A `#` comment may follow the closing quote; anything else means
            // the quoting is not what the writer thought it was.
            let after = after.trim();
            if after.is_empty() || after.starts_with('#') {
                return inner.to_string();
            }
            return rest.to_string();
        }
    }
    match value.split_once('#') {
        Some((before, _)) => before.trim_end().to_string(),
        None => value.to_string(),
    }
}

/// `~` at the front of a path, made absolute.
///
/// The shell does this for a flag and not for a file, and the difference is not
/// something anyone should have to know: `data-dir = "~/marver"` written the
/// obvious way would otherwise create a directory actually called `~`.
fn expand(value: &str) -> PathBuf {
    let Some(rest) = value.strip_prefix('~') else {
        return PathBuf::from(value);
    };
    // `~other` is someone else's home, which needs a password database to
    // resolve. Left alone rather than guessed at.
    if !(rest.is_empty() || rest.starts_with('/')) {
        return PathBuf::from(value);
    }
    let Ok(home) = std::env::var("HOME") else {
        return PathBuf::from(value);
    };
    PathBuf::from(home).join(rest.trim_start_matches('/'))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn an_empty_file_asks_for_nothing() {
        let (settings, problems) = parse("");
        assert_eq!(settings, Settings::default());
        assert!(problems.is_empty());
    }

    #[test]
    fn every_option_can_be_set() {
        let (settings, problems) = parse(
            "data-dir = \"/tmp/data\"\nscan-root = \"/tmp/code\"\ncap = 3\nharness = \"codex\"\n",
        );

        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(settings.data_dir, Some(PathBuf::from("/tmp/data")));
        assert_eq!(settings.scan_root, Some(PathBuf::from("/tmp/code")));
        assert_eq!(settings.cap, Some(3));
        assert_eq!(settings.harness.as_deref(), Some("codex"));
    }

    #[test]
    fn comments_and_blank_lines_are_skipped() {
        let (settings, problems) = parse("# marver\n\n   \ncap = 2   # how many at once\n");
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(settings.cap, Some(2));
    }

    #[test]
    fn quotes_are_optional_and_spacing_is_free() {
        let (settings, _) = parse("cap=1\nscan-root   =    /tmp/code   \nharness = 'codex'\n");
        assert_eq!(settings.cap, Some(1));
        assert_eq!(settings.scan_root, Some(PathBuf::from("/tmp/code")));
        assert_eq!(settings.harness.as_deref(), Some("codex"));
    }

    #[test]
    fn a_hash_inside_a_quoted_value_is_kept() {
        // A harness command is an arbitrary command line, and taking a `#` out
        // of one would corrupt it silently.
        let (settings, problems) = parse("harness = \"x:prog --tag '#1'\"\n");
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(settings.harness.as_deref(), Some("x:prog --tag '#1'"));
    }

    #[test]
    fn a_key_with_a_typo_in_it_is_said_out_loud() {
        // The whole reason this is not silent: a file is written once and
        // trusted for months.
        let (settings, problems) = parse("scanroot = \"/tmp\"\n");

        assert_eq!(settings.scan_root, None);
        assert_eq!(
            problems,
            vec![Problem::UnknownKey {
                line: 1,
                key: "scanroot".to_string()
            }]
        );
        let said = problems[0].to_string();
        assert!(said.contains("scanroot"), "{said}");
        assert!(
            said.contains("scan-root"),
            "it must say what was meant: {said}"
        );
    }

    #[test]
    fn a_bad_value_keeps_the_default_and_complains() {
        let (settings, problems) = parse("cap = lots\n");
        assert_eq!(settings.cap, None, "the default still applies");
        assert_eq!(
            problems,
            vec![Problem::BadValue {
                line: 1,
                key: "cap".to_string(),
                value: "lots".to_string()
            }]
        );
    }

    #[test]
    fn a_line_that_is_not_a_pair_is_reported_with_its_number() {
        let (_, problems) = parse("cap = 2\nnonsense\nharness = \"claude\"\n");
        assert_eq!(problems, vec![Problem::Malformed { line: 2 }]);
    }

    #[test]
    fn one_bad_line_does_not_cost_the_others() {
        let (settings, problems) = parse("cap = 2\nwat = 1\nharness = \"codex\"\n");
        assert_eq!(settings.cap, Some(2));
        assert_eq!(settings.harness.as_deref(), Some("codex"));
        assert_eq!(problems.len(), 1);
    }

    #[test]
    fn a_table_header_is_skipped_rather_than_refused() {
        // Nothing writes one yet, but a file a later marver reads happily must
        // not fail on this one.
        let (settings, problems) = parse("[marver]\ncap = 2\n");
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(settings.cap, Some(2));
    }

    #[test]
    fn a_tilde_is_expanded_because_no_shell_will_do_it() {
        // The environment is the process's, not this test's — see `env_lock`.
        let _env = crate::env_lock();
        // SAFETY: no other test is reading it while the lock is held, and the
        // variable is put back.
        let before = std::env::var("HOME").ok();
        unsafe { std::env::set_var("HOME", "/home/someone") };

        let (settings, _) = parse("data-dir = \"~/marver\"\nscan-root = \"~\"\n");
        assert_eq!(
            settings.data_dir,
            Some(PathBuf::from("/home/someone/marver"))
        );
        assert_eq!(settings.scan_root, Some(PathBuf::from("/home/someone")));

        // Someone else's home needs a password database; left alone.
        let (other, _) = parse("data-dir = \"~root/x\"\n");
        assert_eq!(other.data_dir, Some(PathBuf::from("~root/x")));

        match before {
            Some(home) => unsafe { std::env::set_var("HOME", home) },
            None => unsafe { std::env::remove_var("HOME") },
        }
    }

    #[test]
    fn a_file_that_is_not_there_says_nothing() {
        let tmp = TempDir::new().unwrap();
        let (settings, problems) = Settings::load(Some(&tmp.path().join("nope.toml")));
        assert_eq!(settings.path, None, "nothing was read");
        assert!(problems.is_empty(), "and nothing is wrong with that");
    }

    #[test]
    fn a_file_that_is_there_records_where_it_came_from() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join(FILE_NAME);
        std::fs::write(&path, "cap = 4\n").unwrap();

        let (settings, problems) = Settings::load(Some(&path));

        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(settings.cap, Some(4));
        assert_eq!(settings.path.as_deref(), Some(path.as_path()));
    }

    #[test]
    fn a_directory_where_a_file_was_asked_for_is_a_problem() {
        // Named on the command line and unreadable: falling back to the
        // defaults in silence is the worst of both.
        let tmp = TempDir::new().unwrap();
        let (settings, problems) = Settings::load(Some(tmp.path()));
        assert_eq!(settings, Settings::default());
        assert_eq!(problems.len(), 1, "{problems:?}");
        assert!(matches!(problems[0], Problem::Unreadable { .. }));
    }

    #[test]
    fn a_key_left_blank_is_refused_rather_than_applied() {
        // `data-dir =` is the dangerous one: taken at face value it makes
        // every path marver owns relative to the current directory, so the
        // database found depends on where the daemon was started.
        let (settings, problems) = parse("data-dir =\nscan-root = \"\"\n");
        assert_eq!(settings, Settings::default());
        assert_eq!(problems.len(), 2, "{problems:?}");
        assert!(
            problems
                .iter()
                .all(|p| matches!(p, Problem::BadValue { .. }))
        );
    }

    #[test]
    fn a_blank_value_under_an_unknown_key_is_still_an_unknown_key() {
        let (_, problems) = parse("data-directory =\n");
        assert!(
            matches!(&problems[..], [Problem::UnknownKey { key, .. }] if key == "data-directory"),
            "{problems:?}"
        );
    }

    #[test]
    fn a_quoted_value_keeps_everything_inside_its_quotes() {
        // Splitting at the FIRST closing quote silently dropped the rest, so a
        // harness whose own arguments were quoted became a shorter, different
        // command line — and marver started something other than what the file
        // says, without a word.
        let (settings, problems) = parse("harness = \"claude --settings \"a b.json\"\"\n");
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(
            settings.harness.as_deref(),
            Some("claude --settings \"a b.json\"")
        );
    }

    #[test]
    fn a_comment_after_a_quoted_value_is_still_a_comment() {
        let (settings, _) = parse("harness = \"codex\"  # the other one\n");
        assert_eq!(settings.harness.as_deref(), Some("codex"));
    }

    #[test]
    fn the_default_path_follows_xdg_then_home() {
        // The environment is the process's, not this test's — see `env_lock`.
        let _env = crate::env_lock();
        // SAFETY: no other test is reading these while the lock is held, and
        // both variables are put back.
        let config_home = std::env::var("XDG_CONFIG_HOME").ok();
        let home = std::env::var("HOME").ok();

        unsafe { std::env::set_var("XDG_CONFIG_HOME", "/xdg") };
        assert_eq!(default_path(), PathBuf::from("/xdg/marver/config.toml"));

        unsafe { std::env::remove_var("XDG_CONFIG_HOME") };
        unsafe { std::env::set_var("HOME", "/home/someone") };
        assert_eq!(
            default_path(),
            PathBuf::from("/home/someone/.config/marver/config.toml")
        );

        // An empty XDG_CONFIG_HOME is not a directory called nothing.
        unsafe { std::env::set_var("XDG_CONFIG_HOME", "") };
        assert_eq!(
            default_path(),
            PathBuf::from("/home/someone/.config/marver/config.toml")
        );

        match config_home {
            Some(v) => unsafe { std::env::set_var("XDG_CONFIG_HOME", v) },
            None => unsafe { std::env::remove_var("XDG_CONFIG_HOME") },
        }
        match home {
            Some(v) => unsafe { std::env::set_var("HOME", v) },
            None => unsafe { std::env::remove_var("HOME") },
        }
    }
}