marver 0.0.12

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
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
//! Turning a queued task into a live agent.
//!
//! This is the glue the numbered components leave out: it composes the worktree
//! manager, tmux, and the hook receiver into the one operation the scheduler
//! actually needs.
//!
//! ```text
//! provision worktrees  →  write hook settings  →  create session  →  start agent
//! ```
//!
//! The order matters and is not arbitrary. Worktrees come first because the
//! session's working directory must exist before tmux is asked to start there.
//! Hook settings are written before the agent starts, since a settings file
//! appearing afterwards would be read too late. The session name is recorded
//! last, once there is genuinely something to record.
//!
//! Launching is all-or-nothing. A half-launched task — worktrees but no session,
//! or a session running an agent marver has not recorded — is worse than one
//! that plainly failed, because nothing will ever clean it up.

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

use chrono::{DateTime, Utc};

use crate::domain::Task;
use crate::hook;
use crate::scheduler::Launch;
use crate::store::Store;
use crate::tmux::{self, Tmux};
use crate::worktree::{Teardown, WorktreeManager};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("could not prepare worktrees: {0}")]
    Worktree(#[from] crate::worktree::Error),
    #[error("could not write hook settings: {0}")]
    Hooks(#[from] hook::Error),
    #[error("tmux: {0}")]
    Tmux(#[from] tmux::Error),
    #[error(transparent)]
    Store(#[from] crate::store::Error),
    #[error("session {0} already exists")]
    SessionExists(String),
    #[error("session {0} reported no panes")]
    NoPane(String),
}

pub type Result<T> = std::result::Result<T, Error>;

/// How to start the agent inside a task's session.
#[derive(Debug, Clone)]
pub struct AgentCommand {
    pub program: String,
    /// Arguments placed before `--settings` and the prompt.
    pub args: Vec<String>,
}

impl AgentCommand {
    pub fn claude() -> Self {
        Self {
            program: "claude".to_string(),
            args: Vec::new(),
        }
    }

    /// The argument vector the agent is launched with.
    ///
    /// An argv, not a shell line. Quoting a prompt correctly is not enough when
    /// the result is *typed* into an interactive shell: control bytes in the
    /// text are consumed by the terminal's line discipline and by readline
    /// before the shell parses any quoting, so a prompt containing `\x03` or
    /// `\x15` — which survive a paste from an issue body or a terminal log —
    /// discards the half-typed line and leaves the remainder to run on its own.
    /// Handing tmux an argv means nothing interprets the prompt at all.
    pub fn argv(&self, settings: &Path, prompt: &str) -> Vec<OsString> {
        let mut argv: Vec<OsString> = vec![self.program.clone().into()];
        argv.extend(self.args.iter().map(OsString::from));
        argv.push("--settings".into());
        argv.push(settings.as_os_str().to_owned());
        argv.push(prompt.into());
        argv
    }
}

/// What a successful launch produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Launched {
    pub session: String,
    pub settings: PathBuf,
    pub worktrees: Vec<PathBuf>,
}

pub struct Launcher {
    tmux: Tmux,
    worktrees: WorktreeManager,
    /// Path to the marver binary, baked into generated hook commands.
    hook_bin: PathBuf,
    /// Socket the daemon listens on.
    hook_socket: PathBuf,
    agent: AgentCommand,
    size: (u16, u16),
}

impl Launcher {
    pub fn new(
        tmux: Tmux,
        worktrees: WorktreeManager,
        hook_bin: impl Into<PathBuf>,
        hook_socket: impl Into<PathBuf>,
    ) -> Self {
        Self {
            tmux,
            worktrees,
            hook_bin: hook_bin.into(),
            hook_socket: hook_socket.into(),
            agent: AgentCommand::claude(),
            size: tmux::DEFAULT_SIZE,
        }
    }

    /// Override the agent command. Tests use this to avoid starting a real agent.
    pub fn agent(mut self, agent: AgentCommand) -> Self {
        self.agent = agent;
        self
    }

    pub fn size(mut self, size: (u16, u16)) -> Self {
        self.size = size;
        self
    }

    /// Bring a task to life.
    pub fn launch(&self, store: &mut Store, task: &Task, now: DateTime<Utc>) -> Result<Launched> {
        let session = tmux::session_name(task.id);
        if self.tmux.has_session(&session) {
            return Err(Error::SessionExists(session));
        }

        let provisioned = self.worktrees.provision(store, task)?;
        let worktrees: Vec<PathBuf> = provisioned
            .iter()
            .filter_map(|link| link.worktree_path.clone())
            .collect();

        // From here on any failure has something to undo.
        match self.finish(store, task, &session, now) {
            Ok(settings) => Ok(Launched {
                session,
                settings,
                worktrees,
            }),
            Err(err) => {
                self.unwind(store, task, &session);
                Err(err)
            }
        }
    }

    /// Everything after provisioning, so the caller has one place to unwind from.
    fn finish(
        &self,
        store: &mut Store,
        task: &Task,
        session: &str,
        now: DateTime<Utc>,
    ) -> Result<PathBuf> {
        let settings = hook::write_settings(
            &task.workspace_dir,
            task.id,
            &self.hook_bin,
            &self.hook_socket,
        )?;

        // The agent is the session's own process, not something typed at a
        // shell prompt inside it.
        self.tmux.new_session_running(
            session,
            &task.workspace_dir,
            self.size,
            &self.agent.argv(&settings, &task.prompt),
        )?;

        // Still checked: a session with no pane means the agent never started,
        // and the caller needs to unwind rather than record a live session.
        if self.tmux.list_panes(session)?.is_empty() {
            return Err(Error::NoPane(session.to_string()));
        }

        store.set_session_name(task.id, session, now)?;
        Ok(settings)
    }

    /// Undo a partial launch. Best effort: it runs while already failing.
    fn unwind(&self, store: &Store, task: &Task, session: &str) {
        let _ = self.tmux.kill_session(session);
        let _ = self.worktrees.teardown(store, task, true);
        let _ = store.clear_worktrees(task.id);
    }

    /// Stop a task's agent and remove what the launch created.
    ///
    /// The session is killed before the worktrees, since it is sitting in the
    /// directory being removed.
    pub fn shut_down(&self, store: &Store, task: &Task, delete_branches: bool) -> Result<Teardown> {
        let session = task
            .session_name
            .clone()
            .unwrap_or_else(|| tmux::session_name(task.id));
        if self.tmux.has_session(&session) {
            self.tmux.kill_session(&session)?;
        }
        let teardown = self.worktrees.teardown(store, task, delete_branches)?;
        if teardown.failed.is_empty() {
            store.clear_worktrees(task.id)?;
        }
        Ok(teardown)
    }
}

#[cfg(test)]
pub(crate) mod testing {
    use super::*;

    /// A script standing in for the agent: it prints the argv it was given, one
    /// element per line, then stays alive as a real agent would.
    ///
    /// Printing each element separately is the point. A stub that echoed its
    /// arguments as one line could not tell "the prompt arrived as a single
    /// argument" from "the prompt was split into several" — which is exactly
    /// the difference an injection makes. Staying alive matters too: the agent
    /// is now the session's own process, so a stub that exits takes the session
    /// with it.
    pub fn stub_agent(dir: &Path) -> AgentCommand {
        let path = dir.join("stub-agent");
        std::fs::write(
            &path,
            "#!/bin/sh\nfor a in \"$@\"; do echo \"ARG[$a]\"; done\nexec sleep 300\n",
        )
        .expect("write stub agent");
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
            .expect("make stub executable");
        AgentCommand {
            program: path.to_string_lossy().into_owned(),
            args: Vec::new(),
        }
    }
}

impl Launch for Launcher {
    fn launch(&self, store: &mut Store, task: &Task) -> std::result::Result<(), String> {
        // The scheduler records the moment; the clock is only needed for the
        // session-name write, which happens within this call.
        Launcher::launch(self, store, task, Utc::now())
            .map(|_| ())
            .map_err(|err| err.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{Repo, TaskState};
    use crate::git::testing::init_repo;
    use crate::tmux::testing::TestServer;
    use tempfile::TempDir;

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).expect("valid timestamp")
    }

    struct Fixture {
        _tmp: TempDir,
        server: TestServer,
        repos_dir: PathBuf,
        store: Store,
        launcher: Launcher,
    }

    impl Fixture {
        fn new() -> Self {
            let tmp = TempDir::new().unwrap();
            let server = TestServer::new();
            let repos_dir = tmp.path().join("repos");
            std::fs::create_dir_all(&repos_dir).unwrap();

            let launcher = Launcher::new(
                server.tmux.clone(),
                WorktreeManager::new(tmp.path().join("tasks")),
                PathBuf::from("/usr/local/bin/marver"),
                tmp.path().join("hooks.sock"),
            )
            .agent(testing::stub_agent(tmp.path()));

            Self {
                repos_dir,
                store: Store::open_in_memory().unwrap(),
                launcher,
                server,
                _tmp: tmp,
            }
        }

        fn repo(&self, name: &str) -> Repo {
            let path = self.repos_dir.join(name);
            init_repo(&path, "main");
            self.store.upsert_repo(&path, name, at(0)).unwrap()
        }

        fn task(&mut self, title: &str, prompt: &str, repos: &[Repo]) -> Task {
            let root = self.launcher.worktrees.workspace_root().to_path_buf();
            let ids: Vec<i64> = repos.iter().map(|r| r.id).collect();
            self.store
                .create_task(title, prompt, &root, &ids, at(0))
                .unwrap()
        }

        /// Poll a pane until it shows `needle`, so tests do not race the shell.
        fn wait_for_pane(&self, session: &str, needle: &str) -> String {
            let mut seen = String::new();
            for _ in 0..60 {
                if let Ok(panes) = self.server.tmux.list_panes(session)
                    && let Some(pane) = panes.first()
                    && let Ok(text) = self.server.tmux.capture_pane(pane)
                {
                    seen = text;
                    if seen.contains(needle) {
                        return seen;
                    }
                }
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            seen
        }
    }

    #[test]
    fn the_prompt_is_one_argument_however_it_is_written() {
        let agent = AgentCommand::claude();
        let argv = agent.argv(Path::new("/s/settings.json"), "fix the auth flow");
        assert_eq!(
            argv,
            [
                "claude",
                "--settings",
                "/s/settings.json",
                "fix the auth flow"
            ]
        );
    }

    #[test]
    fn a_prompt_with_spaces_and_quotes_survives_to_the_agent() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task(
            "Quoting",
            "fix the user's login flow",
            std::slice::from_ref(&repo),
        );

        let launched = fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();
        let pane = fx.wait_for_pane(&launched.session, "ARG[--settings]");

        assert!(
            pane.contains("ARG[fix the user's login flow]"),
            "the prompt must arrive as one argument, intact; pane was {pane:?}"
        );
    }

    #[test]
    fn a_prompt_cannot_escape_into_the_shell() {
        // Shell metacharacters, and — the case quoting could never cover — the
        // control bytes that a paste from an issue body or a terminal log
        // carries. Typed at an interactive shell, \x03 discards the half-written
        // line and leaves the rest to run on its own; \x15 does the same via
        // readline. Nothing here is typed, so nothing interprets any of it.
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let canary = fx.repos_dir.join("PWNED");
        let prompt = format!(
            "fix\u{3}touch {} $(touch {}) `touch {}` '; touch {}; echo '",
            canary.display(),
            canary.display(),
            canary.display(),
            canary.display()
        );
        let task = fx.task("Nasty", &prompt, std::slice::from_ref(&repo));

        let launched = fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();
        fx.wait_for_pane(&launched.session, "ARG[--settings]");

        assert!(
            !canary.exists(),
            "the prompt must never reach a shell as executable input"
        );
    }

    #[test]
    fn the_agent_is_the_sessions_own_process() {
        // Not a command typed at a shell prompt inside it. If a shell is what
        // the session runs, every byte of the prompt goes through the line
        // discipline first and the test above cannot hold.
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task("Direct", "do it", std::slice::from_ref(&repo));

        let launched = fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();
        fx.wait_for_pane(&launched.session, "ARG[do it]");

        let cmd = fx
            .server
            .tmux
            .run(&[
                "list-panes",
                "-t",
                &format!("={}", launched.session),
                "-F",
                "#{pane_current_command}",
            ])
            .unwrap();
        assert!(
            !cmd.trim().ends_with("sh")
                && !cmd.trim().ends_with("zsh")
                && !cmd.trim().contains("bash"),
            "the pane must not be running a shell, got {cmd:?}"
        );
    }

    #[test]
    fn launching_creates_worktree_session_and_settings() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task("Fix auth", "fix it", std::slice::from_ref(&repo));

        let launched = fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();

        assert_eq!(launched.session, "marver-1");
        assert_eq!(launched.worktrees.len(), 1);
        assert!(launched.worktrees[0].join("README.md").exists());
        assert!(launched.settings.exists(), "hook settings must exist");
        assert!(fx.server.tmux.has_session(&launched.session));

        // The session sits in the workspace, so the agent sees every worktree.
        let cwd = fx.server.tmux.session_cwd(&launched.session).unwrap();
        assert_eq!(
            std::fs::canonicalize(cwd).unwrap(),
            std::fs::canonicalize(&task.workspace_dir).unwrap()
        );
    }

    #[test]
    fn the_session_name_is_recorded_so_the_agent_can_be_found_again() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task("Fix auth", "fix it", std::slice::from_ref(&repo));

        fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();

        let stored = fx.store.get_task(task.id).unwrap();
        assert_eq!(stored.session_name.as_deref(), Some("marver-1"));
        assert_eq!(stored.updated_at, at(5));
    }

    #[test]
    fn the_agent_command_is_actually_run() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task("Fix auth", "fix the thing", std::slice::from_ref(&repo));

        let launched = fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();
        let pane = fx.wait_for_pane(&launched.session, "ARG[--settings]");

        assert!(
            pane.contains("ARG[--settings]"),
            "the command must actually run; pane was {pane:?}"
        );
        assert!(
            pane.contains("ARG[fix the thing]"),
            "the prompt must reach the agent; pane was {pane:?}"
        );
    }

    #[test]
    fn hook_settings_carry_this_task_id() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task("Fix auth", "fix it", std::slice::from_ref(&repo));

        let launched = fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();
        let settings: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&launched.settings).unwrap()).unwrap();

        assert_eq!(
            settings["hooks"]["Stop"][0]["hooks"][0]["args"][2],
            task.id.to_string()
        );
    }

    #[test]
    fn a_multi_repo_task_gets_a_worktree_each() {
        let mut fx = Fixture::new();
        let api = fx.repo("api");
        let web = fx.repo("web");
        let task = fx.task("Cross cutting", "change both", &[api, web]);

        let launched = fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();

        assert_eq!(launched.worktrees.len(), 2);
        assert!(task.workspace_dir.join("api").exists());
        assert!(task.workspace_dir.join("web").exists());
    }

    #[test]
    fn a_task_with_no_repos_cannot_launch() {
        let mut fx = Fixture::new();
        let task = fx.task("Nothing", "nope", &[]);
        assert!(fx.launcher.launch(&mut fx.store, &task, at(5)).is_err());
        assert!(!fx.server.tmux.has_session("marver-1"));
    }

    #[test]
    fn a_failed_launch_leaves_nothing_running_or_on_disk() {
        let mut fx = Fixture::new();
        let good = fx.repo("api");
        // Registered but never initialised as a repo, so provisioning fails
        // partway.
        let broken_path = fx.repos_dir.join("broken");
        std::fs::create_dir_all(&broken_path).unwrap();
        let broken = fx.store.upsert_repo(&broken_path, "broken", at(0)).unwrap();
        let task = fx.task("Will fail", "x", &[good, broken]);

        assert!(fx.launcher.launch(&mut fx.store, &task, at(5)).is_err());

        assert!(!task.workspace_dir.exists(), "workspace must be gone");
        assert!(
            !fx.server.tmux.has_session("marver-1"),
            "no session may survive a failed launch"
        );
        assert_eq!(
            fx.store.get_task(task.id).unwrap().session_name,
            None,
            "nothing should claim a session that does not exist"
        );
    }

    #[test]
    fn relaunching_a_live_task_is_refused() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task("Fix auth", "fix it", std::slice::from_ref(&repo));
        fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();

        let again = fx.launcher.launch(&mut fx.store, &task, at(6));
        assert!(
            matches!(again, Err(Error::SessionExists(_))),
            "a second launch must not adopt or clobber the live session"
        );
        assert!(
            task.workspace_dir.exists(),
            "the refusal must not destroy the running task's workspace"
        );
    }

    #[test]
    fn shutting_down_removes_the_session_and_the_worktrees() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task("Fix auth", "fix it", std::slice::from_ref(&repo));
        fx.launcher.launch(&mut fx.store, &task, at(5)).unwrap();
        let task = fx.store.get_task(task.id).unwrap();

        let teardown = fx.launcher.shut_down(&fx.store, &task, false).unwrap();

        assert!(teardown.is_clean(), "{:?}", teardown.failed);
        assert!(!fx.server.tmux.has_session("marver-1"));
        assert!(!task.workspace_dir.exists());

        // The repo selection outlives the worktrees.
        let links = fx.store.list_task_repos(task.id).unwrap();
        assert_eq!(links.len(), 1);
        assert!(!links[0].is_provisioned());
    }

    #[test]
    fn shutting_down_a_task_that_never_launched_is_harmless() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task("Never", "x", std::slice::from_ref(&repo));
        let teardown = fx.launcher.shut_down(&fx.store, &task, false).unwrap();
        assert!(teardown.removed.is_empty());
    }

    #[test]
    fn the_scheduler_can_drive_the_launcher() {
        use crate::scheduler::Scheduler;

        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let a = fx.task("First", "one", std::slice::from_ref(&repo));
        let b = fx.task("Second", "two", std::slice::from_ref(&repo));

        // A cap of one: the second task must wait.
        let tick = Scheduler::new(1)
            .tick(&mut fx.store, &fx.launcher, at(5))
            .unwrap();

        assert_eq!(tick.started, [a.id]);
        assert_eq!(fx.store.get_task(a.id).unwrap().state, TaskState::Running);
        assert_eq!(fx.store.get_task(b.id).unwrap().state, TaskState::Queued);
        assert!(fx.server.tmux.has_session("marver-1"));
        assert!(!fx.server.tmux.has_session("marver-2"));
    }
}