voro-core 0.2.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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
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,
    /// An agent is rewriting this proposal's body right now (DESIGN.md §6). It
    /// is out of the triage queue until the round concludes and the task
    /// returns to `proposed`.
    Refining,
    Parked,
    Ready,
    Running,
    NeedsInput,
    Review,
    Waiting,
    Stalled,
    Done,
    Rejected,
}

impl TaskState {
    pub const ALL: [TaskState; 11] = [
        TaskState::Proposed,
        TaskState::Refining,
        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::Refining => "refining",
            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())
    }
}

/// Which source of liveness is authoritative for a session (DESIGN.md §8),
/// recorded by the code that spawned the process because only it knows what it
/// spawned. The two differ in one respect: whether the pid the session row
/// holds is the work itself or a launcher that spawned it and exited.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LivenessSource {
    /// The recorded pid *is* the work — a foreground child Voro owns, or an
    /// agent with no `sessions` verb, where the spawned pid is the only source
    /// there is. `kill -0` answers.
    Pid,
    /// The work belongs to a supervisor the launch handed it to, so the
    /// recorded pid dies at birth and only the agent's own `sessions` listing
    /// can say whether the session is still working.
    Listing,
}

impl LivenessSource {
    pub const ALL: [LivenessSource; 2] = [LivenessSource::Pid, LivenessSource::Listing];

    pub fn as_str(self) -> &'static str {
        match self {
            LivenessSource::Pid => "pid",
            LivenessSource::Listing => "listing",
        }
    }

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

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

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

impl ToSql for LivenessSource {
    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())
    }
}

/// How a refine round ended (DESIGN.md §6). It rides the `refining → proposed`
/// transition, is logged as the detail of a `refine` event, and picks the
/// outcome the round's session closes with — so the markers on the returned
/// proposal are derived from the round that just concluded rather than from
/// the whole history of the task.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RefineOutcome {
    /// The agent rewrote the body and applied it with `set --body-file`.
    Applied,
    /// The agent died without applying anything (reconcile, DESIGN.md §8).
    Failed,
    /// The operator quit the session or cancelled the round; nothing landed,
    /// which is a no-op rather than a failure.
    Cancelled,
}

impl RefineOutcome {
    pub const ALL: [RefineOutcome; 3] = [
        RefineOutcome::Applied,
        RefineOutcome::Failed,
        RefineOutcome::Cancelled,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            RefineOutcome::Applied => "applied",
            RefineOutcome::Failed => "failed",
            RefineOutcome::Cancelled => "cancelled",
        }
    }

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

    /// The outcome the round's session closes with, since a session's life
    /// follows its task (DESIGN.md §8).
    pub fn session_outcome(self) -> SessionOutcome {
        match self {
            RefineOutcome::Applied => SessionOutcome::Completed,
            RefineOutcome::Failed => SessionOutcome::Failed,
            RefineOutcome::Cancelled => SessionOutcome::Aborted,
        }
    }
}

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

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Project {
    pub id: i64,
    pub name: String,
    pub weight: i64,
    /// The `voro.toml` viewer this project's local diffs open in (DESIGN.md
    /// §8/§11a): a `[viewers.<name>]` name, or `None` for the default viewer.
    /// The review keys are static — `g`/`pr` are always the GitHub PR flow,
    /// `o`/`open` always a local viewer — so this picks no medium, only the
    /// viewer `o`/`open` resolve for this project.
    pub viewer: Option<String>,
    /// Retired (DESIGN.md §5): the project and all its tasks leave the cockpit
    /// — queue, stats, running strip — until unarchived. Tasks freeze in
    /// whatever state they hold; only the projects screen still shows the
    /// project, tagged, so it can be found and unarchived.
    pub archived: bool,
}

/// The projects a new task can be created in, in the order to offer them
/// (DESIGN.md §9). Archived projects are dropped — `Store::create_task` refuses
/// them (§5), so offering one is offering a choice that can only fail, and in
/// the `$EDITOR` and planning flows it fails only after the operator has
/// written the task out. The rest sort by weight descending, which is the one
/// per-project priority Voro holds (§7), with name ascending inside a weight so
/// the order is stable. Weight 0 is a snooze rather than a retirement, so a
/// parked project stays offered and sorts last.
pub fn projects_for_new_task(projects: &[Project]) -> Vec<&Project> {
    let mut offered: Vec<&Project> = projects.iter().filter(|p| !p.archived).collect();
    offered.sort_by(|a, b| b.weight.cmp(&a.weight).then_with(|| a.name.cmp(&b.name)));
    offered
}

/// A checkout a project's work runs in (DESIGN.md §3): the execution target
/// dispatch, `pr`/`open`, worktree cleanup, and `import` resolve against. A
/// project owns at least one, exactly one of which is its default.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Repo {
    pub id: i64,
    pub project_id: i64,
    /// Unique within the project; what `--repo` and the `repo` verbs name.
    pub name: String,
    pub path: String,
    /// The repo a task with no `repo_id` resolves to. Exactly one per project.
    pub is_default: bool,
}

/// A plan or design document a project's work derives from (DESIGN.md §3), and
/// the thing tasks link to so "which tasks came from this plan?" is a query
/// rather than a grep over task bodies. Owned by one project — which is where a
/// relative location resolves — but linkable from a task in any project, since
/// one plan routinely spawns work across several.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Doc {
    pub id: i64,
    pub project_id: i64,
    /// Which of the project's checkouts a relative `location` resolves against,
    /// or `None` for the project's default — the same shape as `Task::repo_id`.
    /// Always `None` for a URL or an absolute path, which resolve unaided.
    pub repo_id: Option<i64>,
    /// An operator-supplied label, or `None` to read as the location itself.
    pub title: Option<String>,
    /// A checkout-relative path (preferred, so it survives a checkout move), an
    /// absolute path outside every checkout, or a URL.
    pub location: String,
    pub created_at: String,
}

impl Doc {
    /// Whether the location addresses the network rather than a file. A URL is
    /// handed to a reader verbatim; a path is resolved against a checkout.
    pub fn is_url(&self) -> bool {
        location_is_url(&self.location)
    }

    /// What a rendered row calls this doc: its title when it has one, else the
    /// location, which is then the only name it has.
    pub fn label(&self) -> &str {
        match &self.title {
            Some(title) => title,
            None => &self.location,
        }
    }
}

/// Whether a doc location is a URL rather than a path. Deliberately a narrow
/// scheme test, so a bare `docs/plan.md` never has to be escaped to read as a
/// path.
pub fn location_is_url(location: &str) -> bool {
    location.starts_with("http://") || location.starts_with("https://")
}

#[derive(Debug, Clone, PartialEq)]
pub struct Task {
    pub id: i64,
    pub project_id: i64,
    /// The repo this task's work runs in, or `None` for the project's default
    /// (DESIGN.md §3/§8). Resolved through `Store::repo_for_task`; never read
    /// raw by a consumer that wants a checkout.
    pub repo_id: Option<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, `ask`, and the agent override refuse it;
    /// completion goes `running → done` directly. Default `false` means
    /// dispatchable.
    pub human: bool,
    /// Marks work that warrants the strongest model its agent offers rather
    /// than the workhorse (DESIGN.md §8). Read only at dispatch, where it
    /// picks which model fills the agent's `{model}` placeholder; an agent
    /// whose templates carry none ignores it. Orthogonal to priority, which
    /// orders the queue, and to the agent override, which picks which agent
    /// runs. Default `false` means the workhorse.
    pub deep: 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 a branch and no tracked PR: open one from its
    /// done-time summary.
    Pr,
    /// A review task whose PR is open: review it there.
    ReviewPr,
    /// A review task with nothing to push — an investigation, a triage, an
    /// audit whose whole product is its completion summary: read the report
    /// and close it out.
    Accept,
    /// A review task in a checkout no pull request can be opened from: read the
    /// diff in a local viewer. Never derived from state alone — a caller that
    /// knows the checkout degrades [`NextAction::Pr`] to it.
    Open,
    /// 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::Accept => "accept",
            NextAction::Open => "open",
            NextAction::Do => "do",
            NextAction::Redispatch => "redispatch",
            NextAction::Dispatch => "dispatch",
        }
    }

    /// The same verb in a checkout that cannot take a pull request (DESIGN.md
    /// §8): `pr` there is a recommendation that can only fail, so it degrades
    /// to the local review path the operator does have. Every other verb is
    /// forge-independent and passes through. Pure — whether a given checkout
    /// can take a pull request is decided in the `voro` crate, which owns the
    /// git and `gh` seams, and handed here.
    pub fn without_pull_requests(self) -> NextAction {
        match self {
            NextAction::Pr => NextAction::Open,
            other => other,
        }
    }
}

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

impl Task {
    /// The branch this task's work lives on, blank treated as absent — the one
    /// reading of the column both the next-action derivation and
    /// [`plan_pr`](crate::plan_pr) use, so a task advertised as PR-able is
    /// exactly one `pr` accepts.
    pub fn branch_name(&self) -> Option<&str> {
        self.branch
            .as_deref()
            .map(str::trim)
            .filter(|b| !b.is_empty())
    }

    /// 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` and `refining` belong 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.
    ///
    /// `review` is the one arm that reads past the state (DESIGN.md §6): a
    /// tracked PR asks to be reviewed, a recorded branch asks for one to be
    /// opened, and a task carrying neither produced no code at all — its
    /// summary is the whole deliverable — so the move is *accept*. The summary
    /// itself is not consulted: it lives in the event log rather than on this
    /// row, and a task with nothing to push has no other move regardless.
    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 if self.branch_name().is_some() => Some(NextAction::Pr),
            TaskState::Review => Some(NextAction::Accept),
            TaskState::Stalled => Some(NextAction::Redispatch),
            TaskState::Ready if self.human => Some(NextAction::Do),
            TaskState::Ready => Some(NextAction::Dispatch),
            TaskState::Running
            | TaskState::Refining
            | 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>,
    /// Which source reconciliation must read this session's liveness by,
    /// recorded at launch by whichever code spawned the process (DESIGN.md §8).
    pub liveness_source: LivenessSource,
    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`,
/// `refining`, or `waiting` 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` `None`. `started_at` is what `elapsed_secs` counts from — the
/// session for work under way, the hand-off for a `waiting` task — and
/// `elapsed_secs` is computed in SQL against the database's clock, so the TUI
/// only has to format it. `pr_url` carries the strip's PR marker.
#[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 pr_url: 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 project(name: &str, weight: i64, archived: bool) -> Project {
        Project {
            id: 1,
            name: name.into(),
            weight,
            viewer: None,
            archived,
        }
    }

    #[test]
    fn new_task_projects_drop_the_archived_at_any_weight() {
        let projects = [
            project("live", 1, false),
            project("retired-heavy", 5, true),
            project("retired-parked", 0, true),
        ];
        let offered = projects_for_new_task(&projects);
        assert_eq!(
            offered.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(),
            ["live"]
        );
    }

    #[test]
    fn new_task_projects_sort_by_weight_then_name() {
        let projects = [
            project("beta", 3, false),
            project("parked", 0, false),
            project("alpha", 3, false),
            project("heaviest", 5, false),
        ];
        let offered = projects_for_new_task(&projects);
        assert_eq!(
            offered.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(),
            ["heaviest", "alpha", "beta", "parked"]
        );
    }

    fn task_in(state: TaskState, pr_url: Option<&str>, human: bool) -> Task {
        task_with(state, pr_url, human, None)
    }

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

    #[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)),
            // no branch: nothing to push, so the report is the deliverable
            (TaskState::Review, None, false, Some(NextAction::Accept)),
            (
                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}"
            );
        }
    }

    /// The `review` arm reads two further columns (DESIGN.md §6). A task with a
    /// branch has code to push and asks for `pr`; one with none produced only
    /// its summary — an investigation, an audit — and asks to be accepted,
    /// since `pr` on it could only refuse.
    #[test]
    fn the_review_verb_follows_the_branch() {
        assert_eq!(
            task_with(TaskState::Review, None, false, Some("feat/x")).next_action(),
            Some(NextAction::Pr)
        );
        assert_eq!(
            task_with(TaskState::Review, None, false, None).next_action(),
            Some(NextAction::Accept)
        );
        // a blank branch is no branch, exactly as `plan_pr` reads it
        for blank in ["", "   "] {
            assert_eq!(
                task_with(TaskState::Review, None, false, Some(blank)).next_action(),
                Some(NextAction::Accept),
                "{blank:?}"
            );
        }
    }

    /// A tracked PR outranks both: there is a diff open to read, however the
    /// branch column reads.
    #[test]
    fn a_tracked_pr_outranks_the_branch() {
        for branch in [None, Some("feat/x")] {
            assert_eq!(
                task_with(TaskState::Review, Some("https://x"), false, branch).next_action(),
                Some(NextAction::ReviewPr),
                "{branch:?}"
            );
        }
    }

    /// Only `review` reads the branch — no other state's verb moves with it.
    #[test]
    fn the_branch_moves_no_other_verb() {
        for state in TaskState::ALL.iter().filter(|s| **s != TaskState::Review) {
            assert_eq!(
                task_with(*state, None, false, Some("feat/x")).next_action(),
                task_in(*state, None, false).next_action(),
                "{state}"
            );
        }
    }

    #[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)
        );
    }

    /// The one verb that depends on the checkout rather than the task: where no
    /// pull request can be opened, `pr` reads as the local review path instead
    /// (DESIGN.md §8). Every other verb is forge-independent and holds still.
    #[test]
    fn without_pull_requests_degrades_pr_and_nothing_else() {
        assert_eq!(NextAction::Pr.without_pull_requests(), NextAction::Open);
        for verb in [
            NextAction::Triage,
            NextAction::Answer,
            NextAction::ReviewPr,
            NextAction::Accept,
            NextAction::Open,
            NextAction::Do,
            NextAction::Redispatch,
            NextAction::Dispatch,
        ] {
            assert_eq!(verb.without_pull_requests(), verb, "{verb}");
        }
    }

    /// `open` is never derived from state — a checkout that cannot take a pull
    /// request is what produces it, and the derivation stays pure.
    #[test]
    fn open_is_not_derived_from_state() {
        for state in TaskState::ALL {
            for pr_url in [None, Some("https://x")] {
                for human in [false, true] {
                    assert_ne!(
                        task_in(state, pr_url, human).next_action(),
                        Some(NextAction::Open),
                        "{state} pr_url={pr_url:?} human={human}"
                    );
                }
            }
        }
    }

    #[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");
    }
}