marver 0.0.11

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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! marver's binary.
//!
//! One executable with subcommands rather than a separate `marverd`. The daemon
//! generates hook settings that invoke `marver hook`, and it finds that path via
//! `current_exe` — with two binaries it would have to guess where its sibling
//! was installed, and guess wrong whenever only one of them was on `PATH`.
//!
//! `marver` with no arguments opens the interface, starting a daemon first if
//! none is listening. That is tmux's arrangement — a client starts the server
//! it needs — and marver is built on tmux. `marver daemon` remains for running
//! it under a supervisor, or watching it in the foreground.

use std::io::Read;
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant};

use marver::Scanner;
use marver::daemon::{self, Config, Daemon};
use marver::hook::{self, Delivery, Payload};
use marver::notify::SystemNotifier;
use marver::tmux::Tmux;

const USAGE: &str = "usage:
  marver [options]                   open the interface, starting a daemon if needed
  marver status [options]            report whether a daemon is running
  marver restart [options]           stop the running daemon and start this version
      --force                        restart even with agents mid-turn
  marver upgrade [options]           install the newest published marver (cargo only)
      --restart                      restart the daemon afterwards too
  marver daemon [options]            run the scheduler and hook receiver in the foreground
  marver scan [root]                 list git repos under a root
  marver hook --task <id> --socket <path>
                                     forward a Claude Code hook to the daemon

options:
      --data-dir <path>              where the database, socket, and log live
      --scan-root <path>             directory scanned for repos
      --cap <n>                      how many agents may run at once
  -V, --version                      print the version and exit";

/// Write to stdout, treating a closed pipe as an ordinary end.
///
/// `println!` panics on `EPIPE`, and Rust ignores `SIGPIPE` at startup — so the
/// reader going away, which is all `marver status | head -1` means, arrived as
/// an error the macro then panicked on. Every command that prints goes through
/// here.
fn print_out(text: &str) -> ExitCode {
    use std::io::Write;
    let mut out = std::io::stdout().lock();
    match out.write_all(text.as_bytes()).and_then(|()| out.flush()) {
        Ok(()) => ExitCode::SUCCESS,
        // `head` closing the pipe is the reader saying it has enough, not a
        // failure of ours. Exiting quietly is the whole convention.
        Err(err) if err.kind() == std::io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("marver: could not write output: {err}");
            ExitCode::FAILURE
        }
    }
}

/// Help because it was asked for: stdout, and a success exit.
///
/// Separate from [`usage`] because the two are not the same event. `marver
/// --help | less` is someone reading, and a shell that treats it as a failure
/// is wrong about what happened.
fn help() -> ExitCode {
    print_out(&format!("{USAGE}\n"))
}

/// Help as a correction: stderr, and a failure exit.
fn usage() -> ExitCode {
    eprintln!("{USAGE}");
    ExitCode::FAILURE
}

/// Options that belong to a command rather than being one.
///
/// A leading dash used to be taken as "this is for the interface", so any
/// mistyped flag opened the TUI — and, since the interface started spawning
/// daemons, left one running behind the error it then printed. Anything not on
/// this list is a mistake now, and says so.
const OPTIONS: &[&str] = &["--data-dir", "--scan-root", "--cap"];

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.first().map(String::as_str) {
        Some("hook") => hook_command(&args[1..]),
        Some("daemon") => daemon_command(&args[1..]),
        Some("status") => status_command(&args[1..]),
        Some("restart") => restart_command(&args[1..]),
        Some("upgrade") => upgrade_command(&args[1..]),
        Some("scan") => scan_command(args.get(1).map(PathBuf::from)),
        Some("-h" | "--help") => help(),
        // Ahead of the option handling below, which would otherwise read these
        // as something the interface wants.
        //
        // `-v` as well as `-V`: it is what people type, there is no verbosity
        // flag for it to collide with, and the alternative was opening the
        // whole interface at them.
        Some("-v" | "-V" | "--version") => version(),
        // No subcommand opens the interface, with or without options.
        None => tui_command(&args),
        Some(arg) if arg.starts_with('-') => match unknown_option(&args) {
            Some(bad) => {
                eprintln!("marver: unknown option {bad:?}");
                usage()
            }
            None => tui_command(&args),
        },
        Some(other) => {
            eprintln!("marver: unknown command {other:?}");
            usage()
        }
    }
}

/// The first dash-led argument that is not a known option.
///
/// Values are skipped rather than inspected, so a path that happens to start
/// with a dash is still a path.
fn unknown_option(args: &[String]) -> Option<String> {
    let mut rest = args.iter();
    while let Some(arg) = rest.next() {
        if !arg.starts_with('-') {
            continue;
        }
        if !OPTIONS.contains(&arg.as_str()) {
            return Some(arg.clone());
        }
        rest.next();
    }
    None
}

fn version() -> ExitCode {
    print_out(&format!("marver {}\n", env!("CARGO_PKG_VERSION")))
}

/// Build a configuration from the options every subcommand shares.
///
/// One reader for all of them, because the daemon and the interface find each
/// other through the paths these produce: a `--data-dir` understood by one and
/// ignored by the other would leave two processes talking past each other with
/// nothing to show for it.
fn config_from(args: &[String]) -> Config {
    let data_dir = flag(args, "--data-dir")
        .map(PathBuf::from)
        .unwrap_or_else(Config::default_data_dir);
    let scan_root = flag(args, "--scan-root")
        .map(PathBuf::from)
        .unwrap_or_else(Config::default_scan_root);
    let mut config = Config::new(&data_dir, scan_root);
    if let Some(cap) = flag(args, "--cap").and_then(|v| v.parse().ok()) {
        config.cap = cap;
    }
    config
}

fn tui_command(args: &[String]) -> ExitCode {
    let config = config_from(args);

    // Before the store, and before the screen: an interface with no daemon
    // behind it looks entirely healthy and schedules nothing for ever.
    //
    // Silent when it works. The message would be erased by the alternate screen
    // a moment later, and a client quietly starting the server it needs is what
    // tmux does too. `marver status` is there for anyone who wants to look.
    match daemon::ensure_running(&config) {
        // Not restarted for them: it is supervising live agents, and killing it
        // to pick up a newer build would fail every task it was watching.
        Ok(daemon::Startup::Outdated { running }) => eprintln!(
            "marver: this is {}, but the daemon already running is {running}; \
             run `marver restart` when nothing is mid-turn",
            daemon::VERSION
        ),
        Ok(_) => {}
        Err(err) => {
            eprintln!("marver: {err}");
            return ExitCode::FAILURE;
        }
    }

    // Opens the same database the daemon writes to. WAL allows that; see the
    // note at the top of `tui`.
    let store = match marver::Store::open(&config.db) {
        Ok(store) => store,
        Err(err) => {
            eprintln!("marver: could not open {}: {err}", config.db.display());
            return ExitCode::FAILURE;
        }
    };

    if let Err(err) = marver::tui::run(store, config) {
        eprintln!("marver: {err}");
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}

/// Read `--name value` pairs, ignoring anything unrecognised.
fn flag(args: &[String], name: &str) -> Option<String> {
    args.iter()
        .position(|a| a == name)
        .and_then(|i| args.get(i + 1))
        .cloned()
}

fn daemon_command(args: &[String]) -> ExitCode {
    let config = config_from(args);

    let mut daemon = match Daemon::new(config.clone(), Tmux::new(), SystemNotifier) {
        Ok(daemon) => daemon,
        Err(err) => {
            eprintln!("marverd: {err}");
            return ExitCode::FAILURE;
        }
    };

    // Printed once there is something to report, not before. The banner used to
    // come first, so a refused start announced four lines of healthy-looking
    // configuration and only contradicted itself on the fifth.
    print_out(&format!(
        "marverd: version  {}\nmarverd: database {}\nmarverd: socket   {}\nmarverd: scanning {}\nmarverd: cap      {}\n",
        daemon::VERSION,
        config.db.display(),
        config.socket.display(),
        config.scan_root.display(),
        config.cap,
    ));

    // No signal handler: an unclean exit leaves the socket file behind, and
    // binding already removes a stale socket that nothing is listening on. A
    // crash therefore costs nothing a restart does not fix.
    if let Err(err) = daemon.run(Arc::new(AtomicBool::new(false))) {
        eprintln!("marverd: {err}");
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}

/// Forward a hook payload to the daemon.
///
/// **Always exits 0.** Claude Code treats a non-zero exit as an error on the
/// agent's critical path, and a marver outage must never interfere with the
/// agent it is only observing. Failures go to stderr, which lands in the hook
/// debug log.
fn hook_command(args: &[String]) -> ExitCode {
    let task_id: Option<i64> = flag(args, "--task").and_then(|v| v.parse().ok());
    let socket = flag(args, "--socket").map(PathBuf::from);

    let (Some(task_id), Some(socket)) = (task_id, socket) else {
        eprintln!("marver hook: --task and --socket are both required");
        return ExitCode::SUCCESS;
    };

    let mut body = Vec::new();
    if let Err(err) = std::io::stdin().read_to_end(&mut body) {
        eprintln!("marver hook: could not read the payload: {err}");
        return ExitCode::SUCCESS;
    }

    match Payload::parse(&body) {
        Ok(payload) => {
            let delivery = Delivery { task_id, payload };
            if let Err(err) = hook::send(&socket, &delivery) {
                eprintln!("marver hook: could not reach the daemon: {err}");
            }
        }
        Err(err) => eprintln!("marver hook: {err}"),
    }
    ExitCode::SUCCESS
}

/// Install the newest published marver over this one.
///
/// cargo is the only installer marver knows how to drive, because it is how the
/// crate is distributed. A binary drop or a package manager owns its own upgrade
/// path, and guessing at one would be worse than saying so.
///
/// The binary is replaced underneath a *running* process — this one — so the
/// version this code knows is the old one until it exits. That is why the new
/// version is read back by asking the freshly installed binary rather than
/// printed from a constant.
fn upgrade_command(args: &[String]) -> ExitCode {
    let restart_after = args.iter().any(|arg| arg == "--restart");
    let before = daemon::VERSION;

    // Overridable so the flow can be tested without installing anything. Also
    // lets a caller point at a particular toolchain.
    let cargo = std::env::var("MARVER_CARGO").unwrap_or_else(|_| "cargo".to_string());

    eprintln!("marver: {cargo} install marver --force");
    let status = std::process::Command::new(&cargo)
        .args(["install", "marver", "--force"])
        .status();

    match status {
        Ok(status) if status.success() => {}
        Ok(status) => {
            eprintln!("marver: {cargo} exited with {status}; nothing was changed");
            return ExitCode::FAILURE;
        }
        Err(err) => {
            eprintln!(
                "marver: could not run {cargo}: {err}\n\
                 \x20       marver upgrades itself only when installed with cargo;\n\
                 \x20       otherwise upgrade it the way you installed it"
            );
            return ExitCode::FAILURE;
        }
    }

    match installed_version() {
        Some(now) if now == before => eprintln!("marver: already on {now}"),
        Some(now) => eprintln!("marver: upgraded {before} -> {now}"),
        None => eprintln!("marver: upgraded from {before}"),
    }

    // The daemon is untouched by any of the above: it is still executing the
    // binary that was replaced. Restarting is a separate decision, and
    // `restart_command` is where the cost of making it lives.
    if restart_after {
        return restart_command(args);
    }
    let config = config_from(args);
    if daemon::is_running(&config) {
        eprintln!(
            "marver: the daemon is still running {}; `marver restart` swaps it\n\
             \x20       when nothing is mid-turn, or `marver upgrade --restart` next time",
            daemon::running_version(&config).unwrap_or_else(|| "an older version".to_string())
        );
    }
    ExitCode::SUCCESS
}

/// The version of the binary now on disk, which is not this process's own.
fn installed_version() -> Option<String> {
    let exe = std::env::current_exe().ok()?;
    let out = std::process::Command::new(exe)
        .arg("--version")
        .output()
        .ok()?;
    String::from_utf8_lossy(&out.stdout)
        .trim()
        .strip_prefix("marver ")
        .map(str::to_string)
}

/// Tasks whose agent might still have something to report.
///
/// This is the whole cost of a restart. `marver hook` exits 0 whatever happens
/// — deliberately, so marver being down never interferes with an agent — which
/// means a `Stop` that arrives while nothing is listening is simply gone. The
/// task then sits in `running` with an idle agent for ever, because reconcile
/// only fails tasks whose *session* has died, and the session is still there.
///
/// `awaiting-review` and `queued` have nothing outstanding, so they are free.
fn agents_mid_turn(config: &Config) -> Vec<(marver::TaskState, usize)> {
    let Ok(store) = marver::Store::open(&config.db) else {
        return Vec::new();
    };
    [marver::TaskState::Running, marver::TaskState::Blocked]
        .into_iter()
        .filter_map(|state| match store.list_tasks_in_state(state) {
            Ok(tasks) if !tasks.is_empty() => Some((state, tasks.len())),
            _ => None,
        })
        .collect()
}

/// Stop the running daemon and start one on this version.
///
/// Not done automatically on an upgrade, and not done by the interface. The
/// daemon is supervising live agents, and the moment to interrupt that belongs
/// to whoever knows what those agents are in the middle of.
fn restart_command(args: &[String]) -> ExitCode {
    let config = config_from(args);
    let force = args.iter().any(|arg| arg == "--force");
    let was = daemon::running_version(&config);

    if !force {
        let busy = agents_mid_turn(&config);
        if !busy.is_empty() {
            let counts: Vec<String> = busy
                .iter()
                .map(|(state, count)| format!("{count} {state}"))
                .collect();
            eprintln!(
                "marver: {} may still report ({})\n\
                 \x20       a hook arriving while nothing is listening is lost, and the task\n\
                 \x20       is left running behind an agent that has already finished\n\
                 \x20       wait for review, or restart anyway with --force",
                if busy.iter().map(|(_, n)| n).sum::<usize>() == 1 {
                    "a task"
                } else {
                    "tasks"
                },
                counts.join(", "),
            );
            return ExitCode::FAILURE;
        }
    }

    match daemon::stop(&config) {
        Ok(true) => eprintln!(
            "marver: stopped the daemon ({})",
            was.as_deref().unwrap_or("unknown version")
        ),
        Ok(false) => eprintln!("marver: no daemon was running"),
        Err(err) => {
            eprintln!("marver: {err}");
            return ExitCode::FAILURE;
        }
    }

    match daemon::ensure_running(&config) {
        Ok(daemon::Startup::Started { pid }) => {
            eprintln!("marver: started a daemon ({}), pid {pid}", daemon::VERSION);
            ExitCode::SUCCESS
        }
        // Someone else won the race to replace it. Still the outcome asked for.
        Ok(_) => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("marver: {err}");
            ExitCode::FAILURE
        }
    }
}

/// Report whether a daemon is running, and what it has to work with.
///
/// Exits non-zero when nothing is listening, so a shell can ask too.
fn status_command(args: &[String]) -> ExitCode {
    let config = config_from(args);
    let running = daemon::is_running(&config);
    let mut out = String::new();

    let version = running
        .then(|| daemon::running_version(&config))
        .flatten()
        .unwrap_or_else(|| "unknown".to_string());
    out.push_str(&if running {
        format!("daemon    running ({version})\n")
    } else {
        "daemon    not running\n".to_string()
    });
    out.push_str(&format!("socket    {}\n", config.socket.display()));
    out.push_str(&format!("database  {}\n", config.db.display()));
    out.push_str(&format!("log       {}\n", config.log.display()));

    // Only read a database that exists. `Store::open` would otherwise create
    // one, and a command that reports on the system should not build part of it.
    if !config.db.exists() {
        out.push_str("tasks     no database yet\n");
    } else {
        match marver::Store::open(&config.db) {
            Ok(store) => {
                let counts: Vec<String> = marver::TaskState::ALL
                    .iter()
                    .filter_map(|&state| match store.list_tasks_in_state(state) {
                        Ok(tasks) if !tasks.is_empty() => Some(format!("{} {state}", tasks.len())),
                        _ => None,
                    })
                    .collect();
                out.push_str(&format!(
                    "tasks     {}\n",
                    if counts.is_empty() {
                        "none".to_string()
                    } else {
                        counts.join(", ")
                    }
                ));
            }
            Err(err) => out.push_str(&format!("tasks     unreadable: {err}\n")),
        }
    }

    // Upgrading replaces the binary while the running daemon keeps executing the
    // old one, and because it still holds the socket nothing starts a
    // replacement. Worth saying plainly: everything looks fine in that state.
    if running && version != daemon::VERSION {
        out.push_str(&format!(
            "\nwarning   this marver is {}, the daemon is {version}\n\
             \x20         it keeps running until restarted: marver restart\n",
            daemon::VERSION
        ));
    }

    let wrote = print_out(&out);
    if running { wrote } else { ExitCode::FAILURE }
}

fn scan_command(root: Option<PathBuf>) -> ExitCode {
    let root = root.unwrap_or_else(Config::default_scan_root);
    let started = Instant::now();
    let scan = match Scanner::new(&root).walk() {
        Ok(scan) => scan,
        Err(err) => {
            eprintln!("marver: {err}");
            return ExitCode::FAILURE;
        }
    };
    let elapsed: Duration = started.elapsed();

    let mut out = format!("scanning {}\n", root.display());
    for repo in &scan.repos {
        out.push_str(&format!("  {:<24} {}\n", repo.name, repo.path.display()));
    }
    if !scan.unreadable.is_empty() {
        out.push_str(&format!("\n{} unreadable:\n", scan.unreadable.len()));
        for path in &scan.unreadable {
            out.push_str(&format!("  {}\n", path.display()));
        }
    }
    out.push_str(&format!(
        "\n{} repos in {:.0?}\n",
        scan.repos.len(),
        elapsed
    ));
    print_out(&out)
}