voro-core 0.1.0

Core logic for Voro: the SQLite store, task state machine, scheduler, and scoring.
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
use std::fmt;

use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};

use crate::error::{Error, Result};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TaskState {
    Proposed,
    Parked,
    Ready,
    Running,
    NeedsInput,
    Review,
    Waiting,
    Stalled,
    Done,
    Rejected,
}

impl TaskState {
    pub const ALL: [TaskState; 10] = [
        TaskState::Proposed,
        TaskState::Parked,
        TaskState::Ready,
        TaskState::Running,
        TaskState::NeedsInput,
        TaskState::Review,
        TaskState::Waiting,
        TaskState::Stalled,
        TaskState::Done,
        TaskState::Rejected,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            TaskState::Proposed => "proposed",
            TaskState::Parked => "parked",
            TaskState::Ready => "ready",
            TaskState::Running => "running",
            TaskState::NeedsInput => "needs-input",
            TaskState::Review => "review",
            TaskState::Waiting => "waiting",
            TaskState::Stalled => "stalled",
            TaskState::Done => "done",
            TaskState::Rejected => "rejected",
        }
    }

    pub fn parse(s: &str) -> Result<TaskState> {
        Self::ALL
            .into_iter()
            .find(|state| state.as_str() == s)
            .ok_or_else(|| Error::Invalid(format!("unknown task state '{s}'")))
    }

    /// Closed states: nothing leaves them, and they do not block dependants.
    pub fn is_terminal(self) -> bool {
        matches!(self, TaskState::Done | TaskState::Rejected)
    }
}

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

impl FromSql for TaskState {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        let s = value.as_str()?;
        TaskState::parse(s).map_err(|e| FromSqlError::Other(Box::new(e)))
    }
}

impl ToSql for TaskState {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(self.as_str().into())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Priority {
    P0,
    P1,
    P2,
    P3,
}

impl Priority {
    pub fn from_int(n: i64) -> Result<Priority> {
        match n {
            0 => Ok(Priority::P0),
            1 => Ok(Priority::P1),
            2 => Ok(Priority::P2),
            3 => Ok(Priority::P3),
            _ => Err(Error::Invalid(format!("priority {n} out of range 0-3"))),
        }
    }

    pub fn as_int(self) -> i64 {
        match self {
            Priority::P0 => 0,
            Priority::P1 => 1,
            Priority::P2 => 2,
            Priority::P3 => 3,
        }
    }

    /// The geometric value used by the attention score (DESIGN.md §7).
    pub fn value(self) -> f64 {
        match self {
            Priority::P0 => 8.0,
            Priority::P1 => 4.0,
            Priority::P2 => 2.0,
            Priority::P3 => 1.0,
        }
    }
}

impl fmt::Display for Priority {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Priority::P0 => "P0",
            Priority::P1 => "P1",
            Priority::P2 => "P2",
            Priority::P3 => "P3",
        };
        f.pad(s)
    }
}

impl FromSql for Priority {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        Priority::from_int(value.as_i64()?).map_err(|e| FromSqlError::Other(Box::new(e)))
    }
}

impl ToSql for Priority {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(self.as_int().into())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DepKind {
    Blocks,
    DiscoveredFrom,
    Parent,
    Related,
}

impl DepKind {
    pub const ALL: [DepKind; 4] = [
        DepKind::Blocks,
        DepKind::DiscoveredFrom,
        DepKind::Parent,
        DepKind::Related,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            DepKind::Blocks => "blocks",
            DepKind::DiscoveredFrom => "discovered-from",
            DepKind::Parent => "parent",
            DepKind::Related => "related",
        }
    }

    pub fn parse(s: &str) -> Result<DepKind> {
        Self::ALL
            .into_iter()
            .find(|kind| kind.as_str() == s)
            .ok_or_else(|| Error::Invalid(format!("unknown dep kind '{s}'")))
    }
}

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

impl FromSql for DepKind {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        DepKind::parse(value.as_str()?).map_err(|e| FromSqlError::Other(Box::new(e)))
    }
}

impl ToSql for DepKind {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(self.as_str().into())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SessionOutcome {
    Completed,
    Asked,
    Failed,
    Capped,
    Aborted,
}

impl SessionOutcome {
    pub const ALL: [SessionOutcome; 5] = [
        SessionOutcome::Completed,
        SessionOutcome::Asked,
        SessionOutcome::Failed,
        SessionOutcome::Capped,
        SessionOutcome::Aborted,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            SessionOutcome::Completed => "completed",
            SessionOutcome::Asked => "asked",
            SessionOutcome::Failed => "failed",
            SessionOutcome::Capped => "capped",
            SessionOutcome::Aborted => "aborted",
        }
    }

    pub fn parse(s: &str) -> Result<SessionOutcome> {
        Self::ALL
            .into_iter()
            .find(|outcome| outcome.as_str() == s)
            .ok_or_else(|| Error::Invalid(format!("unknown session outcome '{s}'")))
    }
}

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

impl FromSql for SessionOutcome {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        SessionOutcome::parse(value.as_str()?).map_err(|e| FromSqlError::Other(Box::new(e)))
    }
}

impl ToSql for SessionOutcome {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(self.as_str().into())
    }
}

/// A project's review medium (DESIGN.md §8/§11a): which of the two media the
/// unified `pr` action uses to get a review task's diff in front of the
/// operator. Stored on the project (`projects.review_action`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ReviewAction {
    /// Resolve at use: GitHub when the checkout is a GitHub repo, otherwise
    /// the configured viewer. Stored as NULL — the unconfigured default.
    #[default]
    Auto,
    /// Always the GitHub PR flow (jump to the tracked PR, or push and create).
    Pr,
    /// Always a local viewer from `voro.toml`: the named `[viewers.<name>]`
    /// when one is given, otherwise the default viewer.
    Viewer(Option<String>),
}

impl ReviewAction {
    /// Parse the stored/CLI form: `auto`, `pr`, `viewer`, or `viewer:<name>`.
    pub fn parse(s: &str) -> Result<ReviewAction> {
        match s {
            "auto" => Ok(ReviewAction::Auto),
            "pr" => Ok(ReviewAction::Pr),
            "viewer" => Ok(ReviewAction::Viewer(None)),
            other => match other.strip_prefix("viewer:") {
                Some(name) if !name.trim().is_empty() => {
                    Ok(ReviewAction::Viewer(Some(name.trim().to_string())))
                }
                _ => Err(Error::Invalid(format!(
                    "unknown review action '{s}' — expected auto, pr, viewer, or viewer:<name>"
                ))),
            },
        }
    }

    /// Resolve the medium once the checkout's GitHub-ness is known. Only `Auto`
    /// consults the probe's answer.
    pub fn resolve(&self, on_github: bool) -> ReviewMedium {
        match self {
            ReviewAction::Auto if on_github => ReviewMedium::GithubPr,
            ReviewAction::Auto => ReviewMedium::Viewer(None),
            ReviewAction::Pr => ReviewMedium::GithubPr,
            ReviewAction::Viewer(name) => ReviewMedium::Viewer(name.clone()),
        }
    }

    /// Whether resolving this action needs the GitHub probe at all, so
    /// callers can skip the `gh` shell-out when the medium is pinned.
    pub fn needs_probe(&self) -> bool {
        matches!(self, ReviewAction::Auto)
    }
}

impl fmt::Display for ReviewAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ReviewAction::Auto => f.pad("auto"),
            ReviewAction::Pr => f.pad("pr"),
            ReviewAction::Viewer(None) => f.pad("viewer"),
            ReviewAction::Viewer(Some(name)) => f.pad(&format!("viewer:{name}")),
        }
    }
}

impl FromSql for ReviewAction {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        match value {
            ValueRef::Null => Ok(ReviewAction::Auto),
            _ => ReviewAction::parse(value.as_str()?).map_err(|e| FromSqlError::Other(Box::new(e))),
        }
    }
}

impl ToSql for ReviewAction {
    /// `Auto` writes NULL — absence of configuration — so the column stays
    /// empty until the operator pins a medium.
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        match self {
            ReviewAction::Auto => Ok(rusqlite::types::Null.into()),
            other => Ok(other.to_string().into()),
        }
    }
}

/// The concrete medium a [`ReviewAction`] resolves to: the single "show me
/// this task's diff" action, per project (DESIGN.md §8).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReviewMedium {
    /// Jump to / create the GitHub PR.
    GithubPr,
    /// Run a `voro.toml` viewer on the checkout; `Some` names a
    /// `[viewers.<name>]` entry, `None` is the default viewer.
    Viewer(Option<String>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Project {
    pub id: i64,
    pub name: String,
    pub path: String,
    pub weight: i64,
    /// How `pr` shows this project's review diffs (DESIGN.md §8/§11a).
    pub review_action: ReviewAction,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Task {
    pub id: i64,
    pub project_id: i64,
    pub title: String,
    pub body: String,
    pub priority: Priority,
    pub state: TaskState,
    pub agent: Option<String>,
    pub question: Option<String>,
    /// The canonical URL of a GitHub PR tracked on this task (DESIGN.md §11c),
    /// or `None`. Names the PR's base repo, so it survives forks where the
    /// checkout's `origin` is not that repo.
    pub pr_url: Option<String>,
    /// The git branch this task's work lives on, or `None`. Holds the *intended*
    /// name dispatch injects into the prompt, later overwritten by the branch
    /// the agent *reports* — Voro never runs git, it only records what returns.
    pub branch: Option<String>,
    pub state_since: String,
    pub created_at: String,
    pub closed_at: Option<String>,
    /// Marks a task no agent can execute — hands-on work at real hardware, say
    /// (DESIGN.md §3/§6). Dispatch, continuation, `ask`, and the agent override
    /// refuse it; completion goes `running → done` directly. Default `false`
    /// means dispatchable.
    pub human: bool,
}

/// The verb a task's queue row asks of the human (DESIGN.md §3), derived from
/// state × fields rather than stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NextAction {
    /// An untriaged proposal: accept, park, or reject it.
    Triage,
    /// A question is waiting; answering it unblocks the work.
    Answer,
    /// A review task with no tracked PR: open one from its done-time summary.
    Pr,
    /// A review task whose PR is open: review it there.
    ReviewPr,
    /// A ready human-only task: only the human can execute it.
    Do,
    /// A stalled task: its dispatch died, restart it with the prior
    /// session's context.
    Redispatch,
    /// A ready task an agent can take: hand it to one.
    Dispatch,
}

impl NextAction {
    pub fn as_str(self) -> &'static str {
        match self {
            NextAction::Triage => "triage",
            NextAction::Answer => "answer",
            NextAction::Pr => "pr",
            NextAction::ReviewPr => "review PR",
            NextAction::Do => "do",
            NextAction::Redispatch => "redispatch",
            NextAction::Dispatch => "dispatch",
        }
    }
}

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

impl Task {
    /// The single next-action derivation (DESIGN.md §3): what the human does
    /// next, from state × fields. `None` for states that ask nothing of the
    /// human — `running` belongs to the running strip, `parked`/`done`/`rejected`
    /// wait on nothing. `stalled` always means a dead agent dispatch, since
    /// dispatch refuses human tasks. `waiting` is handed off to an external
    /// party (DESIGN.md §6) and asks nothing of the operator.
    pub fn next_action(&self) -> Option<NextAction> {
        match self.state {
            TaskState::Proposed => Some(NextAction::Triage),
            TaskState::NeedsInput => Some(NextAction::Answer),
            TaskState::Review if self.pr_url.is_some() => Some(NextAction::ReviewPr),
            TaskState::Review => Some(NextAction::Pr),
            TaskState::Stalled => Some(NextAction::Redispatch),
            TaskState::Ready if self.human => Some(NextAction::Do),
            TaskState::Ready => Some(NextAction::Dispatch),
            TaskState::Running
            | TaskState::Waiting
            | TaskState::Parked
            | TaskState::Done
            | TaskState::Rejected => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dep {
    pub task_id: i64,
    pub depends_on: i64,
    pub kind: DepKind,
}

/// A dependency edge resolved for display: the task at the *other* end of the
/// edge with its current title and state, plus the edge's kind. Which end is
/// "other" depends on the query — the dependency for
/// [`Store::deps_by_task`](crate::Store::deps_by_task), the dependant for
/// [`Store::dependents_by_task`](crate::Store::dependents_by_task).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DepRef {
    pub id: i64,
    pub title: String,
    pub state: TaskState,
    pub kind: DepKind,
}

impl DepRef {
    /// The referenced task is not yet in a closed state.
    pub fn is_open(&self) -> bool {
        !self.state.is_terminal()
    }
}

#[derive(Debug, Clone)]
pub struct Event {
    pub id: i64,
    pub task_id: Option<i64>,
    pub at: String,
    pub kind: String,
    pub detail: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Session {
    pub id: i64,
    pub task_id: i64,
    pub agent: String,
    pub pid: Option<i64>,
    /// The agent's own reference for this session (a Claude session UUID, a
    /// Codex session id, a tmux session name), captured after launch and
    /// substituted into the agent's attach/resume/continue verb templates.
    /// `None` when the agent has no capture story or capture failed.
    pub session_ref: Option<String>,
    pub log_path: Option<String>,
    pub started_at: String,
    pub ended_at: Option<String>,
    pub outcome: Option<SessionOutcome>,
}

/// A row of the cockpit's running strip (DESIGN.md §9): one per `running` task,
/// joined with its open session if it has one. A task with no open session
/// (started by hand) still shows, with `session_id`/`agent` set to `None`.
/// `elapsed_secs` is computed in SQL against the database's clock, so the TUI
/// only has to format it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunningRow {
    pub session_id: Option<i64>,
    pub task_id: i64,
    pub task_title: String,
    pub task_state: TaskState,
    pub agent: Option<String>,
    pub started_at: String,
    pub elapsed_secs: i64,
}

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

    #[test]
    fn task_state_display_honors_width() {
        assert_eq!(format!("{:11}", TaskState::Ready), "ready      ");
        assert_eq!(format!("{:>6}", TaskState::Done), "  done");
        assert_eq!(format!("{:>6}", TaskState::NeedsInput), "needs-input");
    }

    #[test]
    fn priority_display_honors_width() {
        assert_eq!(format!("{:>6}", Priority::P0), "    P0");
        assert_eq!(format!("{:>6}", Priority::P2), "    P2");
    }

    fn task_in(state: TaskState, pr_url: Option<&str>, human: bool) -> Task {
        Task {
            id: 1,
            project_id: 1,
            title: "t".into(),
            body: String::new(),
            priority: Priority::P2,
            state,
            agent: None,
            question: None,
            pr_url: pr_url.map(str::to_string),
            branch: None,
            state_since: "2026-01-01T00:00:00Z".into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            closed_at: None,
            human,
        }
    }

    #[test]
    fn next_action_derives_every_arm() {
        for (state, pr_url, human, expected) in [
            (TaskState::Proposed, None, false, Some(NextAction::Triage)),
            (TaskState::NeedsInput, None, false, Some(NextAction::Answer)),
            (TaskState::Review, None, false, Some(NextAction::Pr)),
            (
                TaskState::Review,
                Some("https://github.com/o/r/pull/1"),
                false,
                Some(NextAction::ReviewPr),
            ),
            (TaskState::Ready, None, true, Some(NextAction::Do)),
            (TaskState::Ready, None, false, Some(NextAction::Dispatch)),
            (
                TaskState::Stalled,
                None,
                false,
                Some(NextAction::Redispatch),
            ),
            (TaskState::Running, None, false, None),
            (TaskState::Waiting, None, false, None),
            (TaskState::Parked, None, false, None),
            (TaskState::Done, None, false, None),
            (TaskState::Rejected, None, false, None),
        ] {
            assert_eq!(
                task_in(state, pr_url, human).next_action(),
                expected,
                "{state} pr_url={pr_url:?} human={human}"
            );
        }
    }

    #[test]
    fn next_action_ignores_fields_its_arm_does_not_read() {
        assert_eq!(
            task_in(TaskState::Proposed, Some("https://x"), true).next_action(),
            Some(NextAction::Triage)
        );
        assert_eq!(
            task_in(TaskState::NeedsInput, None, true).next_action(),
            Some(NextAction::Answer)
        );
        assert_eq!(
            task_in(TaskState::Ready, Some("https://x"), false).next_action(),
            Some(NextAction::Dispatch)
        );
    }

    #[test]
    fn next_action_display_honors_width() {
        assert_eq!(format!("{:10}", NextAction::Do), "do        ");
        assert_eq!(format!("{:10}", NextAction::ReviewPr), "review PR ");
        assert_eq!(format!("{:10}", NextAction::Redispatch), "redispatch");
    }

    #[test]
    fn review_action_parses_and_displays_every_form() {
        for (text, action) in [
            ("auto", ReviewAction::Auto),
            ("pr", ReviewAction::Pr),
            ("viewer", ReviewAction::Viewer(None)),
            ("viewer:zed", ReviewAction::Viewer(Some("zed".into()))),
        ] {
            assert_eq!(ReviewAction::parse(text).unwrap(), action, "{text}");
            assert_eq!(action.to_string(), text);
        }
        assert!(ReviewAction::parse("github").is_err());
        assert!(ReviewAction::parse("viewer:").is_err());
        assert!(ReviewAction::parse("viewer:  ").is_err());
    }

    #[test]
    fn review_action_resolves_the_medium() {
        assert_eq!(ReviewAction::Auto.resolve(true), ReviewMedium::GithubPr);
        assert_eq!(
            ReviewAction::Auto.resolve(false),
            ReviewMedium::Viewer(None)
        );
        assert!(ReviewAction::Auto.needs_probe());

        assert_eq!(ReviewAction::Pr.resolve(false), ReviewMedium::GithubPr);
        assert!(!ReviewAction::Pr.needs_probe());
        assert_eq!(
            ReviewAction::Viewer(Some("zed".into())).resolve(true),
            ReviewMedium::Viewer(Some("zed".into()))
        );
        assert!(!ReviewAction::Viewer(None).needs_probe());
    }
}