todoapp-core 0.2.0

tda domain core: entities, capabilities, ports. No I/O deps (see spec §5).
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
//! Entities, capability components, and value objects (spec §3, §7).
//!
//! Storage is one component per capability (spec §7): the durable `task` entity
//! is just identity + timestamps, and each capability is a separate component
//! whose *presence* means the task has it. [`TaskState`] is the in-memory
//! *aggregate* — a task assembled from the components a caller projected (see
//! [`crate::Projection`]) — and is what `decide`/`apply` operate on.

use jiff::ToSpan;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use crate::temporal::{Date, Due, Duration, Time};

/// Stable identity for tasks, actors, collections. Opaque string (a random ULID
/// in real adapters; a sequence in tests). Serializes transparently as that
/// string.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Id(pub String);

impl Id {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }
    pub fn as_str(&self) -> &str {
        &self.0
    }
    /// The invisible structural root (spec §7 virtual-root sentinel). Never a
    /// `task` entity — only ever a `child` link `from`. The reserved string
    /// can't collide with a 26-char base32 ULID.
    pub fn root() -> Self {
        Self("__root__".into())
    }
    pub fn is_root(&self) -> bool {
        self.0 == "__root__"
    }
    /// Content-addressed id for a blob: same bytes ⇒ same id (cheap incidental
    /// dedup, not a content-hash identity guarantee — collisions are possible
    /// but not a practical concern at this scale). Shared by every `BlobStore`
    /// adapter so they agree on ids for the same bytes.
    pub fn for_blob(bytes: &[u8]) -> Self {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut h = DefaultHasher::new();
        bytes.hash(&mut h);
        Self(format!("blob_{:016x}", h.finish()))
    }
}

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

/// Required `Status` capability (spec §8). `blocked` is *derived*, not stored.
/// Transitions between any two values are unrestricted (no guard) — `rank` is
/// just for ordering/display, not a legality check.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    Draft,
    Todo,
    Wip,
    Paused,
    Done,
}

impl Status {
    /// Position in the `draft→todo→wip→paused→done` chain, for ordering/display only.
    pub fn rank(self) -> i8 {
        match self {
            Status::Draft => 0,
            Status::Todo => 1,
            Status::Wip => 2,
            Status::Paused => 3,
            Status::Done => 4,
        }
    }
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Status::Draft => "draft",
            Status::Todo => "todo",
            Status::Wip => "wip",
            Status::Paused => "paused",
            Status::Done => "done",
        };
        f.write_str(s)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ActorKind {
    Person,
    Agent,
}

/// A human or agent. Not persisted via a port in M1 (the spec lists no
/// `ActorRepository`); `Assignment`/`Claim` only ever reference an actor `Id`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Actor {
    pub id: Id,
    pub kind: ActorKind,
    pub name: String,
}

/// One assignee on a task; `claimed` flips when that actor claims it (§8).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Assignment {
    pub actor: Id,
    pub claimed: bool,
}

/// A capability component (spec §3): a unit of data keyed by task `Id` in the
/// store. **Presence of the value *is* the capability** — there is no monolithic
/// `Task` struct; a task is the set of components attached to its id, fetched and
/// mutated one capability at a time (`store.get::<Status>(id)` /
/// `store.set(id, Status::Wip)`). `NAME` keys the per-capability map/table
/// (spec §7). Adding a capability = a new `Component` type; the generic store
/// needs no change.
///
/// The in-memory store only needs `Clone + 'static` (typed `Box<dyn Any>`); the
/// serde bounds are for durable stores that map a component to its row(s).
///
/// The `Serialize`/`DeserializeOwned` bound lets a store map a component
/// generically to/from its row(s): the Turso adapter (M2) bridges each value
/// through `serde_json::to_value`/`from_value` to its typed `c_*` column(s).
pub trait Component: Clone + 'static + Serialize + serde::de::DeserializeOwned {
    const NAME: &'static str;
}

/// Required `Title` capability.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Title(pub String);
impl Component for Title {
    const NAME: &'static str = "title";
}

/// Required `Status` capability (the enum is the component value itself).
impl Component for Status {
    const NAME: &'static str = "status";
}

/// `Notes` capability: Markdown body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Notes(pub String);
impl Component for Notes {
    const NAME: &'static str = "notes";
}

/// `Schedule` capability: a due date, optionally with a time-of-day.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Schedule(pub Due);
impl Component for Schedule {
    const NAME: &'static str = "schedule";
}

/// `Estimate` capability (effort estimate).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Estimate(pub Duration);
impl Component for Estimate {
    const NAME: &'static str = "estimate";
}

/// `TimeSpent` capability (accumulated time).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeSpent(pub Duration);
impl Component for TimeSpent {
    const NAME: &'static str = "timespent";
}

/// `TimeLog` capability: a per-day breakdown of time spent, keyed by calendar
/// date. `TimeSpent` stays the fast-path cumulative total — it's recomputed
/// as this map's sum whenever it's set (see the `Event::TimeLogSet` apply
/// arm), so aggregation (FR-13) keeps reading `TimeSpent` unchanged. Mixing
/// this with the plain `AddTimeSpent` command (no date) can leave the two
/// slightly inconsistent — a known, accepted edge case, not guarded against.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeLog(pub BTreeMap<Date, Duration>);
impl Component for TimeLog {
    const NAME: &'static str = "timelog";
}

/// `Tags` capability: the whole set is one component value (empty ⇒ remove it).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tags(pub BTreeSet<String>);
impl Component for Tags {
    const NAME: &'static str = "tags";
}

/// `Assignment` capability: the whole assignee list is one component value
/// (empty ⇒ remove it). Its presence/contents drive `Claim` (spec §8).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Assignments(pub Vec<Assignment>);
impl Component for Assignments {
    const NAME: &'static str = "assignments";
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AttachmentKind {
    Link,
    File,
    Image,
}

/// One attachment: a `Link` never has a `blob` (it's just a URL); `File`/
/// `Image` may or may not have one — `url` keeps the original source
/// path/URL either way (e.g. from an import), `blob` is `Some` once actual
/// bytes have been stored via [`crate::BlobStore`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
    pub id: Id,
    pub kind: AttachmentKind,
    pub title: String,
    pub url: Option<String>,
    pub blob: Option<Id>,
    pub mime: Option<String>,
}

/// `Attachments` capability: the whole list is one component value (empty ⇒
/// remove it), like `Tags`/`Assignments`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachments(pub Vec<Attachment>);
impl Component for Attachments {
    const NAME: &'static str = "attachments";
}

/// `Archived` capability: an orthogonal flag, independent of `Status` (a task
/// can be `done` and archived, or archived without being `done`) — presence
/// *is* the flag, no payload needed. Hidden from default views by callers
/// passing `Filter { archived: Some(false), .. }` (spec §13 Q4 direction);
/// `QueryEngine`/`Filter` itself stay neutral (`None` = no restriction).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Archived;
impl Component for Archived {
    const NAME: &'static str = "archived";
}

/// `IssueRef` capability: a static reference to an external issue tracker's
/// issue (e.g. imported from another tool). `provider` is freeform (no closed
/// enum) — no live sync, no computed URL.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IssueRef {
    pub provider: String,
    pub id: String,
    pub url: Option<String>,
}
impl Component for IssueRef {
    const NAME: &'static str = "issueref";
}

/// A day of the week, for [`RepeatCycle::Weekly`]. A local enum (not jiff's)
/// so serde stays as simple as [`Status`]'s.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Weekday {
    Mon,
    Tue,
    Wed,
    Thu,
    Fri,
    Sat,
    Sun,
}

impl Weekday {
    fn from_jiff(w: jiff::civil::Weekday) -> Self {
        match w.to_monday_zero_offset() {
            0 => Weekday::Mon,
            1 => Weekday::Tue,
            2 => Weekday::Wed,
            3 => Weekday::Thu,
            4 => Weekday::Fri,
            5 => Weekday::Sat,
            _ => Weekday::Sun,
        }
    }
}

/// A recurrence rule (spec §3): how often a [`Recurrence`]-carrying task's due
/// date advances when it's completed (see `Recurrence::next_due`). Covers the
/// common cases (daily interval, weekly weekday set, monthly same-day) — not a
/// full RRULE engine.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RepeatCycle {
    Daily { every_n_days: u32 },
    Weekly { weekdays: BTreeSet<Weekday> },
    Monthly { every_n_months: u32 },
}

/// `Recurrence` capability: a task carrying this **resets in place** on
/// completion instead of staying `done` — spec decision: no per-occurrence
/// task spawning, the same task's `Schedule` advances and its `Status` goes
/// back to `todo` (see the `Event::StatusSet(Status::Done)` apply arm).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Recurrence {
    pub cycle: RepeatCycle,
    /// Time-of-day to carry onto the recomputed due date; falls back to the
    /// current due's time if unset.
    pub time: Option<Time>,
}
impl Component for Recurrence {
    const NAME: &'static str = "recurrence";
}

impl Recurrence {
    /// The next due date/time after `current`, per this rule.
    pub fn next_due(&self, current: Due) -> Due {
        let date = match &self.cycle {
            RepeatCycle::Daily { every_n_days } => {
                let n = i64::from((*every_n_days).max(1));
                current
                    .date
                    .0
                    .checked_add(n.days())
                    .map(Date)
                    .unwrap_or(current.date)
            }
            RepeatCycle::Weekly { weekdays } => next_weekday(current.date, weekdays),
            RepeatCycle::Monthly { every_n_months } => {
                let n = i64::from((*every_n_months).max(1));
                current
                    .date
                    .0
                    .checked_add(n.months())
                    .map(Date)
                    .unwrap_or(current.date)
            }
        };
        Due {
            date,
            time: self.time.or(current.time),
        }
    }
}

/// The next date after `from` whose weekday is in `weekdays` (or, if empty,
/// just the next day — an under-specified rule still advances).
fn next_weekday(from: Date, weekdays: &BTreeSet<Weekday>) -> Date {
    let mut d = from.0;
    for _ in 0..7 {
        d = d.checked_add(1.day()).unwrap_or(d);
        if weekdays.is_empty() || weekdays.contains(&Weekday::from_jiff(d.weekday())) {
            return Date(d);
        }
    }
    from
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LinkKind {
    Child,
    Blocks,
}

/// Fractional index (spec §7): insert between two neighbours by averaging, so a
/// reorder or subtree move touches one row, never the siblings.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Position(pub f64);

impl Position {
    /// A position strictly between `before` and `after` (either may be open).
    pub fn between(before: Option<f64>, after: Option<f64>) -> f64 {
        match (before, after) {
            (None, None) => 0.0,
            (Some(b), None) => b + 1.0,
            (None, Some(a)) => a - 1.0,
            (Some(b), Some(a)) => (b + a) / 2.0,
        }
    }
}

/// A typed, ordered directed edge. `child` is a single-parent tree; `blocks` is
/// a DAG (invariants enforced in `todoapp-app`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Link {
    pub from: Id,
    pub to: Id,
    pub kind: LinkKind,
    pub position: Position,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CollectionKind {
    Tree,
    Query,
}

/// A saved tree or saved query (spec §7). `spec` holds the query for `query` kind.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Collection {
    pub id: Id,
    pub name: String,
    pub kind: CollectionKind,
    pub spec: Option<Query>,
}

// ---- Query model (spec §7 "Query model") ----------------------------------

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Query {
    #[serde(default)]
    pub filter: Filter,
    #[serde(default)]
    pub sort: Vec<SortKey>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Filter {
    pub text: Option<String>,
    #[serde(default)]
    pub status: Vec<Status>,
    pub assignee: Option<Id>,
    /// all-of (spec §13 default).
    #[serde(default)]
    pub tags: Vec<String>,
    pub within: Option<Id>,
    pub due: Option<DueFilter>,
    pub claimed: Option<bool>,
    /// `None` = no restriction (matches archived and non-archived alike);
    /// hiding archived tasks by default is a caller-side choice, not a
    /// query-engine special case.
    pub archived: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DueFilter {
    Today,
    Overdue,
    Before(Date),
    On(Date),
    After(Date),
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SortField {
    Priority,
    Due,
    Created,
    Updated,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Dir {
    Asc,
    Desc,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SortKey {
    pub key: SortField,
    pub dir: Dir,
}

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

    fn due(s: &str) -> Due {
        Due::parse(s).unwrap()
    }

    #[test]
    fn daily_advances_by_n_days() {
        let rec = Recurrence {
            cycle: RepeatCycle::Daily { every_n_days: 3 },
            time: None,
        };
        assert_eq!(rec.next_due(due("2026-07-01")).date, due("2026-07-04").date);
    }

    #[test]
    fn weekly_finds_next_matching_weekday() {
        // 2026-07-01 is a Wednesday; next Mon/Wed/Fri after it is Friday.
        let rec = Recurrence {
            cycle: RepeatCycle::Weekly {
                weekdays: BTreeSet::from([Weekday::Mon, Weekday::Wed, Weekday::Fri]),
            },
            time: None,
        };
        assert_eq!(rec.next_due(due("2026-07-01")).date, due("2026-07-03").date);
    }

    #[test]
    fn monthly_advances_by_n_months_same_day() {
        let rec = Recurrence {
            cycle: RepeatCycle::Monthly { every_n_months: 1 },
            time: None,
        };
        assert_eq!(rec.next_due(due("2026-07-15")).date, due("2026-08-15").date);
    }

    #[test]
    fn recurrence_time_wins_over_carried_time() {
        let rec = Recurrence {
            cycle: RepeatCycle::Daily { every_n_days: 1 },
            time: Some(Time::parse("09:00").unwrap()),
        };
        let next = rec.next_due(due("2026-07-01 18:00"));
        assert_eq!(next.time, Some(Time::parse("09:00").unwrap()));
    }
}