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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Core domain types. The task state machine lives here;
//! [`TaskState::can_transition_to`] is the executable copy of `ARCHITECTURE.md`
//! §4.

use std::fmt;
use std::path::PathBuf;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Where a task is in its lifecycle.
///
/// ```text
/// queued ──▶ running ⟷ blocked ──▶ awaiting-review ──▶ committed
///               ▲                          │
///               └────────── reject ────────┘
///
/// queued | running | blocked ⟷ paused
/// any non-terminal state ──▶ cancelled
/// queued | running | blocked | paused ──▶ failed
/// ```
///
/// Where a paused task returns to is not stored — it is whether the task has a
/// tmux session. See [`TaskState::Paused`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TaskState {
    /// Created, waiting for a concurrency slot.
    Queued,
    /// Agent is working.
    Running,
    /// Agent needs the user. Entered via the Claude Code `Notification` hook.
    Blocked,
    /// Agent finished; the diff needs review. Entered via the `Stop` hook.
    AwaitingReview,
    /// Set aside by the user. Holds no concurrency slot.
    Paused,
    /// Changes committed locally. Terminal.
    Committed,
    /// The agent crashed, the session died, or setup never completed.
    /// Terminal.
    Failed,
    /// Abandoned by the user. Terminal.
    Cancelled,
}

impl TaskState {
    /// Every state, in lifecycle order. Useful for filters and exhaustive
    /// tests.
    pub const ALL: &'static [TaskState] = &[
        Self::Queued,
        Self::Running,
        Self::Blocked,
        Self::AwaitingReview,
        Self::Paused,
        Self::Committed,
        Self::Failed,
        Self::Cancelled,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Queued => "queued",
            Self::Running => "running",
            Self::Blocked => "blocked",
            Self::AwaitingReview => "awaiting-review",
            Self::Paused => "paused",
            Self::Committed => "committed",
            Self::Failed => "failed",
            Self::Cancelled => "cancelled",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        Some(match s {
            "queued" => Self::Queued,
            "running" => Self::Running,
            "blocked" => Self::Blocked,
            "awaiting-review" => Self::AwaitingReview,
            "paused" => Self::Paused,
            "committed" => Self::Committed,
            "failed" => Self::Failed,
            "cancelled" => Self::Cancelled,
            _ => return None,
        })
    }

    /// Every state a task may legally move to from here.
    pub fn allowed_next(self) -> &'static [TaskState] {
        match self {
            Self::Queued => &[Self::Running, Self::Paused, Self::Failed, Self::Cancelled],
            // Blocked and finished are both reachable while running.
            Self::Running => &[
                Self::Blocked,
                Self::AwaitingReview,
                Self::Paused,
                Self::Failed,
                Self::Cancelled,
            ],
            // A typed reply returns it to running, via `UserPromptSubmit`. A
            // dismissed permission dialog emits nothing, so that one goes
            // straight to review on the `Stop` that says it finished.
            Self::Blocked => &[
                Self::Running,
                Self::AwaitingReview,
                Self::Paused,
                Self::Failed,
                Self::Cancelled,
            ],
            // Accept commits; reject resumes the same live session.
            Self::AwaitingReview => &[Self::Committed, Self::Running, Self::Cancelled],
            // Back where it came from, told apart by whether a session exists.
            Self::Paused => &[Self::Queued, Self::Running, Self::Failed, Self::Cancelled],
            Self::Committed => &[],
            Self::Failed => &[],
            Self::Cancelled => &[],
        }
    }

    pub fn can_transition_to(self, next: TaskState) -> bool {
        self.allowed_next().contains(&next)
    }

    /// Terminal states have no outgoing transitions.
    pub fn is_terminal(self) -> bool {
        self.allowed_next().is_empty()
    }
}

impl fmt::Display for TaskState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why a task is blocked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BlockedKind {
    /// Waiting on a permission prompt (`permission_prompt`).
    PermissionPrompt,
    /// Asked the user something (`elicitation_dialog`, `agent_needs_input`).
    Question,
    /// Went idle waiting for input (`idle_prompt`).
    Silence,
}

impl BlockedKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::PermissionPrompt => "permission-prompt",
            Self::Question => "question",
            Self::Silence => "silence",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        Some(match s {
            "permission-prompt" => Self::PermissionPrompt,
            "question" => Self::Question,
            "silence" => Self::Silence,
            _ => return None,
        })
    }
}

impl fmt::Display for BlockedKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A git repository discovered under the scan root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Repo {
    pub id: i64,
    /// Absolute path to the repository working directory.
    pub path: PathBuf,
    /// Directory name, used for display and worktree naming.
    pub name: String,
    /// Hidden from repo pickers without being forgotten.
    pub ignored: bool,
    pub discovered_at: DateTime<Utc>,
    /// Updated on every scan that still finds it; lets us spot vanished repos.
    pub last_seen_at: DateTime<Utc>,
}

/// The unit of work: one agent, one session, one workspace directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Task {
    pub id: i64,
    pub title: String,
    /// What the agent was asked to do.
    pub prompt: String,
    pub state: TaskState,
    /// Set only while `state` is [`TaskState::Blocked`].
    pub blocked_kind: Option<BlockedKind>,
    pub blocked_reason: Option<String>,
    /// Set only while `state` is [`TaskState::Failed`].
    pub failure_reason: Option<String>,
    /// Parent directory holding this task's worktrees; the session's cwd.
    pub workspace_dir: PathBuf,
    /// tmux session name, once one exists. Recorded rather than derived: the
    /// name carries a tag for the data directory that minted it, and this is
    /// the only thing that remembers which.
    pub session_name: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    /// What the agent has spent, as far as its transcript says.
    pub usage: TaskUsage,
    /// When it was put out of the way, if it has been.
    pub archived_at: Option<DateTime<Utc>>,
}

impl Task {
    pub fn is_archived(&self) -> bool {
        self.archived_at.is_some()
    }
}

/// What a task's agent has spent.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TaskUsage {
    /// Model named by the most recent assistant turn, verbatim.
    pub model: Option<String>,
    /// How full the context window was on that turn. A level, not a total.
    pub context_tokens: Option<u64>,
    /// Output tokens across every turn so far. A total, not a level.
    pub output_tokens: Option<u64>,
    /// Where the transcript has been read up to.
    pub transcript_offset: u64,
    /// Where the transcript is, as the hooks reported it.
    pub transcript_path: Option<PathBuf>,
}

impl TaskUsage {
    /// Whether there is anything worth showing.
    pub fn is_known(&self) -> bool {
        self.model.is_some() || self.context_tokens.is_some() || self.output_tokens.is_some()
    }
}

/// A repo a task targets, and the worktree made for it once provisioned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskRepo {
    pub task_id: i64,
    pub repo_id: i64,
    /// Absolute path to the worktree, once it exists.
    pub worktree_path: Option<PathBuf>,
    /// Branch created for this task in this repo, once provisioned.
    pub branch: Option<String>,
    /// What `branch` was cut from, as resolved at provision time.
    pub base_ref: Option<String>,
}

impl TaskRepo {
    /// Whether a worktree exists on disk for this pairing.
    pub fn is_provisioned(&self) -> bool {
        self.worktree_path.is_some()
    }
}

/// Something to do, at one of two scopes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Todo {
    pub id: i64,
    /// `None` for a global todo.
    pub task_id: Option<i64>,
    pub text: String,
    pub done: bool,
    pub created_at: DateTime<Utc>,
}

impl Todo {
    pub fn is_global(&self) -> bool {
        self.task_id.is_none()
    }
}

/// Which todos to read or write.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TodoScope {
    /// Not yet scoped to any task.
    Global,
    /// Belonging to one task.
    Task(i64),
}

impl TodoScope {
    pub fn task_id(self) -> Option<i64> {
        match self {
            Self::Global => None,
            Self::Task(id) => Some(id),
        }
    }
}

/// An append-only record of something that happened.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Event {
    pub id: i64,
    /// `None` for events not tied to a task, such as a repo scan.
    pub task_id: Option<i64>,
    /// Dotted identifier, e.g. `task.transition` or `hook.notification`.
    pub kind: String,
    /// Arbitrary JSON payload.
    pub payload: serde_json::Value,
    pub created_at: DateTime<Utc>,
}

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

    #[test]
    fn state_strings_round_trip() {
        for &state in TaskState::ALL {
            assert_eq!(TaskState::parse(state.as_str()), Some(state));
        }
        assert_eq!(TaskState::parse("nonsense"), None);
    }

    #[test]
    fn blocked_kind_strings_round_trip() {
        for kind in [
            BlockedKind::PermissionPrompt,
            BlockedKind::Question,
            BlockedKind::Silence,
        ] {
            assert_eq!(BlockedKind::parse(kind.as_str()), Some(kind));
        }
        assert_eq!(BlockedKind::parse("nonsense"), None);
    }

    #[test]
    fn happy_path_is_walkable() {
        let path = [
            TaskState::Queued,
            TaskState::Running,
            TaskState::AwaitingReview,
            TaskState::Committed,
        ];
        for pair in path.windows(2) {
            assert!(
                pair[0].can_transition_to(pair[1]),
                "{} should reach {}",
                pair[0],
                pair[1]
            );
        }
    }

    #[test]
    fn blocking_round_trips_through_running() {
        assert!(TaskState::Running.can_transition_to(TaskState::Blocked));
        assert!(TaskState::Blocked.can_transition_to(TaskState::Running));
    }

    #[test]
    fn a_blocked_agent_can_finish_without_being_seen_to_resume() {
        // Answering a permission prompt emits no hook, so the next thing
        // marver hears is the `Stop` that means "done".
        assert!(TaskState::Blocked.can_transition_to(TaskState::AwaitingReview));
    }

    #[test]
    fn rejection_resumes_the_same_session() {
        assert!(TaskState::AwaitingReview.can_transition_to(TaskState::Running));
    }

    #[test]
    fn only_the_three_end_states_are_terminal() {
        let terminal = [
            TaskState::Committed,
            TaskState::Failed,
            TaskState::Cancelled,
        ];
        for &state in TaskState::ALL {
            assert_eq!(
                state.is_terminal(),
                terminal.contains(&state),
                "{state} has the wrong terminality"
            );
        }
    }

    #[test]
    fn anything_unfinished_can_be_cancelled() {
        for &state in TaskState::ALL {
            if state.is_terminal() {
                continue;
            }
            assert!(
                state.can_transition_to(TaskState::Cancelled),
                "{state} should be cancellable"
            );
        }
    }

    #[test]
    fn failure_is_reachable_only_while_work_is_outstanding() {
        for &state in &[TaskState::Queued, TaskState::Running, TaskState::Blocked] {
            assert!(
                state.can_transition_to(TaskState::Failed),
                "{state} should be able to fail"
            );
        }
        // The agent has already finished by this point; there is nothing left
        // to crash.
        assert!(!TaskState::AwaitingReview.can_transition_to(TaskState::Failed));
    }

    #[test]
    fn terminal_states_never_resume() {
        for &state in TaskState::ALL {
            if !state.is_terminal() {
                continue;
            }
            for &next in TaskState::ALL {
                assert!(
                    !state.can_transition_to(next),
                    "{state} should not reach {next}"
                );
            }
        }
    }

    #[test]
    fn queued_cannot_skip_running() {
        assert!(!TaskState::Queued.can_transition_to(TaskState::AwaitingReview));
        assert!(!TaskState::Queued.can_transition_to(TaskState::Committed));
        assert!(!TaskState::Queued.can_transition_to(TaskState::Blocked));
    }

    #[test]
    fn no_state_transitions_to_itself() {
        for &state in TaskState::ALL {
            assert!(!state.can_transition_to(state), "{state} loops on itself");
        }
    }
}