marver 0.0.28

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
//! How the daemon is started, found, and refused — driven through the real
//! binary rather than the library.
//!
//! These live outside `src` because they need `marver` as an executable:
//! [`marver::daemon::ensure_running`] spawns `config.marver_bin`, and in a unit
//! test that path is the test harness itself, which would recursively re-run the
//! suite. `CARGO_BIN_EXE_marver` is only defined for integration tests.

use std::path::PathBuf;
use std::process::Command;
use std::time::Duration;

use chrono::Utc;
use marver::TaskState;
use marver::daemon::{self, Config, Startup};
use marver::store::{Store, Transition};
use tempfile::TempDir;

/// Kills the daemon it holds when the test ends, however the test ends.
struct Daemon(u32);

impl Drop for Daemon {
    fn drop(&mut self) {
        let _ = Command::new("kill").arg(self.0.to_string()).status();
    }
}

/// A config pointed at a private data directory and the real binary.
///
/// The directory has to stay short: a unix socket path is capped around 100
/// bytes, well under what any other path allows.
fn config(dir: &TempDir) -> Config {
    let mut config = Config::new(dir.path(), dir.path());
    config.marver_bin = PathBuf::from(env!("CARGO_BIN_EXE_marver"));
    config
}

/// The process group of `pid`, via ps. Avoids a libc dependency for one call.
fn process_group(pid: u32) -> String {
    let out = Command::new("ps")
        .args(["-o", "pgid=", "-p", &pid.to_string()])
        .output()
        .expect("ps");
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}

#[test]
fn a_daemon_is_started_on_demand_and_then_found_rather_than_duplicated() {
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    assert!(!daemon::is_running(&config), "nothing should be listening");

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("the first call should have started one");
    };
    let _guard = Daemon(pid);

    assert!(
        daemon::is_running(&config),
        "ensure_running must not return until the socket answers"
    );
    assert_eq!(
        daemon::ensure_running(&config).expect("second call"),
        Startup::AlreadyRunning,
        "a second caller must find the first daemon, not start another"
    );
}

#[test]
fn an_auto_started_daemon_is_in_its_own_process_group() {
    // The property behind "agents outlive the interface". Terminal signals go to
    // the foreground process group, so a daemon sharing ours would take ctrl-c
    // in the TUI along with it — killing the supervisor of every running agent.
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);

    let ours = process_group(std::process::id());
    let theirs = process_group(pid);
    assert!(!theirs.is_empty(), "the daemon should still be running");
    assert_ne!(
        ours, theirs,
        "the daemon shares our process group, so ctrl-c would kill it"
    );
}

#[test]
fn a_second_daemon_refuses_instead_of_stealing_the_socket() {
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);

    let out = Command::new(env!("CARGO_BIN_EXE_marver"))
        .args(["daemon", "--data-dir"])
        .arg(dir.path())
        .arg("--scan-root")
        .arg(dir.path())
        .output()
        .expect("run marver daemon");

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(!out.status.success(), "a second daemon must exit non-zero");
    assert!(
        stderr.contains("already running"),
        "it should say a daemon is running, not leak an errno: {stderr:?}"
    );
    // The banner used to print before the bind was attempted, so a refusal read
    // as four lines of successful startup followed by a contradiction.
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("cap"),
        "a refused start should announce no configuration: {stdout:?}"
    );
    assert!(
        daemon::is_running(&config),
        "the original daemon must still hold its socket"
    );
}

#[test]
fn status_reports_what_is_running_and_exits_accordingly() {
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    let status = |dir: &TempDir| {
        Command::new(env!("CARGO_BIN_EXE_marver"))
            .args(["status", "--data-dir"])
            .arg(dir.path())
            .output()
            .expect("run marver status")
    };

    let before = status(&dir);
    let text = String::from_utf8_lossy(&before.stdout).to_string();
    assert!(text.contains("not running"), "{text:?}");
    assert!(
        !before.status.success(),
        "a shell should be able to ask, so this exits non-zero"
    );
    assert!(
        !config.db.exists(),
        "reporting on the system must not create part of it"
    );

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);

    let after = status(&dir);
    let text = String::from_utf8_lossy(&after.stdout).to_string();
    assert!(after.status.success(), "{text:?}");
    assert!(
        text.contains("running") && !text.contains("not running"),
        "{text:?}"
    );
}

#[test]
fn an_upgrade_is_noticed_rather_than_silently_ignored() {
    // Installing a new marver replaces the binary while the running daemon keeps
    // executing the old inode — and because it still holds the socket,
    // ensure_running finds it and starts nothing. Everything then works, on the
    // previous version, with no sign of it anywhere.
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);

    assert_eq!(
        daemon::running_version(&config).as_deref(),
        Some(daemon::VERSION),
        "the daemon records what it is"
    );
    assert_eq!(
        daemon::ensure_running(&config).expect("second call"),
        Startup::AlreadyRunning,
        "matching versions are unremarkable"
    );

    // Stand in for an upgrade: the daemon on the socket is now a version this
    // binary is not.
    std::fs::write(&config.version_file, "0.0.1\n").unwrap();
    assert_eq!(
        daemon::ensure_running(&config).expect("third call"),
        Startup::Outdated {
            running: "0.0.1".to_string()
        },
    );
    assert!(
        daemon::is_running(&config),
        "noticing must not kill the daemon: it is supervising live agents"
    );

    let out = Command::new(env!("CARGO_BIN_EXE_marver"))
        .args(["status", "--data-dir"])
        .arg(dir.path())
        .output()
        .expect("run marver status");
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("running (0.0.1)"), "{text:?}");
    assert!(text.contains("warning"), "{text:?}");
    assert!(
        text.contains("marver restart"),
        "it names the command that fixes it: {text:?}"
    );
}

/// Run `marver restart` against this data directory.
fn restart(dir: &TempDir, extra: &[&str]) -> std::process::Output {
    let mut command = Command::new(env!("CARGO_BIN_EXE_marver"));
    command.args(["restart", "--data-dir"]).arg(dir.path());
    command.arg("--scan-root").arg(dir.path());
    command.args(extra);
    command.output().expect("run marver restart")
}

#[test]
fn restart_replaces_the_daemon_and_the_new_one_is_this_version() {
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);
    std::fs::write(&config.version_file, "0.0.1\n").unwrap();

    let out = restart(&dir, &[]);
    let stderr = String::from_utf8_lossy(&out.stderr);

    assert!(out.status.success(), "{stderr:?}");
    assert!(stderr.contains("stopped the daemon (0.0.1)"), "{stderr:?}");
    assert!(stderr.contains("started a daemon"), "{stderr:?}");
    assert!(daemon::is_running(&config), "something must be listening");
    assert_eq!(
        daemon::running_version(&config).as_deref(),
        Some(daemon::VERSION),
        "the replacement is this build"
    );

    let new_pid = daemon::running_pid(&config).expect("pid");
    assert_ne!(new_pid, pid, "the old process is gone, not reused");
    let _replacement = Daemon(new_pid);
}

#[test]
fn restart_refuses_while_an_agent_might_still_report() {
    // The whole cost of a restart: `marver hook` exits 0 whatever happens, so a
    // Stop arriving while nothing is listening is lost, and the task is left
    // running behind an agent that has already finished.
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);

    {
        let mut store = Store::open(&config.db).expect("store");
        let task = store
            .create_task("busy", "p", dir.path(), &[], Utc::now())
            .expect("create");
        store
            .transition(task.id, TaskState::Running, Transition::Plain, Utc::now())
            .expect("run it");
    }

    let refused = restart(&dir, &[]);
    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert!(!refused.status.success(), "{stderr:?}");
    assert!(stderr.contains("1 running"), "{stderr:?}");
    assert!(
        stderr.contains("--force"),
        "it offers the way out: {stderr:?}"
    );
    assert_eq!(
        daemon::running_pid(&config),
        Some(pid),
        "a refusal must leave the daemon alone"
    );

    let forced = restart(&dir, &["--force"]);
    let stderr = String::from_utf8_lossy(&forced.stderr);
    assert!(forced.status.success(), "{stderr:?}");
    assert_ne!(
        daemon::running_pid(&config),
        Some(pid),
        "--force goes through"
    );
    if let Some(new_pid) = daemon::running_pid(&config) {
        let _replacement = Daemon(new_pid);
    }
}

#[test]
fn restart_finds_a_daemon_that_left_no_pid_file() {
    // Daemons started before pid files existed leave none, and the first cut of
    // this reported that as "no daemon was running" — then exited 0 having done
    // nothing, while the old daemon carried on holding the socket.
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);
    std::fs::remove_file(&config.pid_file).expect("forget the pid");
    assert_eq!(daemon::running_pid(&config), None);

    let out = restart(&dir, &[]);
    let stderr = String::from_utf8_lossy(&out.stderr);

    assert!(out.status.success(), "{stderr:?}");
    assert!(
        !stderr.contains("no daemon was running"),
        "one was running: {stderr:?}"
    );
    assert!(stderr.contains("stopped the daemon"), "{stderr:?}");

    let new_pid = daemon::running_pid(&config).expect("the replacement records itself");
    assert_ne!(new_pid, pid, "the old one is actually gone");
    let _replacement = Daemon(new_pid);
}

#[test]
fn restart_with_nothing_running_just_starts_one() {
    let dir = TempDir::new().unwrap();
    let config = config(&dir);
    assert!(!daemon::is_running(&config));

    let out = restart(&dir, &[]);
    let stderr = String::from_utf8_lossy(&out.stderr);

    assert!(out.status.success(), "{stderr:?}");
    assert!(stderr.contains("no daemon was running"), "{stderr:?}");
    assert!(daemon::is_running(&config));
    if let Some(pid) = daemon::running_pid(&config) {
        let _guard = Daemon(pid);
    }
}

#[test]
fn a_liveness_probe_leaves_no_trace_in_the_log() {
    // `is_listening` connects and says nothing. If the daemon treated that as a
    // malformed hook, every status check would leave a complaint behind and the
    // log would stop being worth reading.
    let dir = TempDir::new().unwrap();
    let config = config(&dir);

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);

    for _ in 0..5 {
        assert!(daemon::is_running(&config));
    }
    // A fixed pause rather than a poll: the assertion is that nothing arrives,
    // and waiting for a deadline that must expire would cost the full timeout.
    std::thread::sleep(Duration::from_millis(300));

    let log = std::fs::read_to_string(&config.log).unwrap_or_default();
    assert!(!log.contains("ignoring hook"), "{log:?}");
}

#[test]
fn a_started_daemon_is_asked_its_version_rather_than_assumed() {
    // The bug this encodes shipped in 0.0.15 and was seen in the wild:
    //
    //   marver: upgraded 0.0.14 -> 0.0.15
    //   marver: stopped the daemon (0.0.13)
    //   marver: started a daemon (0.0.14), pid 1137   <- the daemon was 0.0.15
    //
    // `restart` printed its own `daemon::VERSION`, and under `upgrade --restart`
    // the process doing the printing is the binary that was just replaced. The
    // version has to come from the daemon.
    //
    // Reading the file directly is not the fix either: `ensure_running` returns
    // as soon as the socket answers, and the version is recorded just after, so
    // a bare read can still return the last daemon's. The stale entries seeded
    // here stand in for that. Whether a bare read loses the race is a matter of
    // timing, so this test is the happy path and the one below is the guard —
    // together they pin the rule that the answer comes from the daemon.
    let dir = TempDir::new().unwrap();
    let config = config(&dir);
    std::fs::write(&config.version_file, "0.0.1\n").unwrap();
    std::fs::write(&config.pid_file, "999999\n").unwrap();

    let Startup::Started { pid } = daemon::ensure_running(&config).expect("start") else {
        panic!("expected a fresh daemon");
    };
    let _guard = Daemon(pid);

    assert_eq!(
        daemon::announced_version(&config, pid).as_deref(),
        Some(daemon::VERSION),
        "the answer must come from the daemon that was just started"
    );
}

#[test]
fn a_daemon_that_says_nothing_gets_no_version_invented_for_it() {
    // No daemon at all, so nothing will ever announce itself. Better to report
    // no version than this process's own, which is the wrong one exactly when
    // the difference matters.
    let dir = TempDir::new().unwrap();
    let config = config(&dir);
    std::fs::write(&config.version_file, "0.0.1\n").unwrap();

    assert_eq!(daemon::announced_version(&config, 999_999), None);
}