wipe-core 0.3.1

Core storage engine and domain model for wipe.
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
//! The wipe domain model.
//!
//! These types map 1:1 onto the JSON files under `.wipe/`. Field order is
//! significant: `serde_json` serializes struct fields in declaration order, and we
//! rely on that (plus `Vec` ordering and no hash maps) to keep on-disk output
//! deterministic. Optional/empty fields are skipped so diffs stay minimal.

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

use crate::id::slug;

/// On-disk format version. Bumped when the JSON schema changes in a
/// backwards-incompatible way; every top-level file carries it for migration.
pub const FORMAT_VERSION: u32 = 1;

/// Default port the local daemon listens on when the user hasn't chosen one.
pub const DEFAULT_PORT: u16 = 6737;

// ---------------------------------------------------------------------------
// board.json
// ---------------------------------------------------------------------------

/// The board - the top-level object of a project. Holds ordered [`List`]s whose
/// `cards` reference ticket IDs. Ticket *content* lives in separate files under
/// `tickets/`, so moving a card and editing a ticket never touch the same file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Board {
    /// On-disk format version.
    pub version: u32,
    /// Stable unique board ID (UUID v4).
    pub id: String,
    /// Human-readable board name.
    pub name: String,
    /// Optional longer description (Markdown allowed).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
    /// Ordered lists (columns) of the board.
    pub lists: Vec<List>,
    /// Next ticket counter; `T-<next_ticket>` is the next ID to allocate.
    pub next_ticket: u64,
    /// Next forum-thread counter; `F-<next_thread>` is the next thread ID.
    #[serde(default = "one")]
    pub next_thread: u64,
    /// When the board was created.
    pub created: DateTime<Utc>,
    /// When the board was last modified.
    pub updated: DateTime<Utc>,
}

/// What to pre-populate a new board with (chosen during `wipe init`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Starter {
    /// Default lists (Backlog/Todo/In Progress/Done) and default labels.
    #[default]
    Standard,
    /// Default lists, but no labels.
    ListsOnly,
    /// No lists and no labels - a blank board.
    Empty,
}

impl Board {
    /// Create a fresh board with the default set of lists.
    pub fn new(name: impl Into<String>, now: DateTime<Utc>) -> Self {
        Board {
            version: FORMAT_VERSION,
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            description: String::new(),
            lists: default_lists(),
            next_ticket: 1,
            next_thread: 1,
            created: now,
            updated: now,
        }
    }

    /// Create a board with no lists (used by the "empty" starter).
    pub fn empty(name: impl Into<String>, now: DateTime<Utc>) -> Self {
        let mut b = Board::new(name, now);
        b.lists.clear();
        b
    }

    /// Find a list by ID.
    pub fn list(&self, id: &str) -> Option<&List> {
        self.lists.iter().find(|l| l.id == id)
    }

    /// Find a list by ID (mutable).
    pub fn list_mut(&mut self, id: &str) -> Option<&mut List> {
        self.lists.iter_mut().find(|l| l.id == id)
    }

    /// Return `(list_id, index)` of the list currently containing `ticket_id`.
    pub fn locate_card(&self, ticket_id: &str) -> Option<(String, usize)> {
        for list in &self.lists {
            if let Some(idx) = list.cards.iter().position(|c| c == ticket_id) {
                return Some((list.id.clone(), idx));
            }
        }
        None
    }
}

/// A list (column) on the board. `cards` is the ordered set of ticket IDs it holds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct List {
    /// Stable list ID (kebab-case slug of the original name).
    pub id: String,
    /// Display name.
    pub name: String,
    /// Optional UI color (hex or token).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// Optional work-in-progress limit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wip_limit: Option<u32>,
    /// Ordered ticket IDs contained in this list.
    #[serde(default)]
    pub cards: Vec<String>,
}

impl List {
    /// Create an empty list from a display name.
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        List {
            id: slug(&name),
            name,
            color: None,
            wip_limit: None,
            cards: Vec::new(),
        }
    }
}

/// The default lists created by `wipe init`.
fn default_lists() -> Vec<List> {
    ["Backlog", "Todo", "In Progress", "Done"]
        .into_iter()
        .map(List::new)
        .collect()
}

// ---------------------------------------------------------------------------
// tickets/T-###.json
// ---------------------------------------------------------------------------

/// A ticket (card). Stored as its own file; comments are inline and short.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ticket {
    /// On-disk format version.
    pub version: u32,
    /// Ticket ID, e.g. `T-23`.
    pub id: String,
    /// Short title.
    pub title: String,
    /// Long-form body (Markdown allowed inside the JSON string).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub body: String,
    /// Priority (references a name in `definitions.json`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub priority: Option<String>,
    /// Applied label names (the only categorization mechanism).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
    /// Assignee identities (git-style `Name <email>` or agent IDs).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assignees: Vec<String>,
    /// Relations to other tickets.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub relations: Vec<Relation>,
    /// Attached media/files (stored under `.wipe/media/` or referenced in-repo).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<Attachment>,
    /// Inline comment thread.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub comments: Vec<Comment>,
    /// Activity log (moves, label/assignee/priority changes, attachments). Shown
    /// interleaved with comments in the ticket's activity timeline.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub activity: Vec<Activity>,
    /// Next comment counter for this ticket.
    #[serde(default = "one")]
    pub next_comment: u64,
    /// When the ticket was created.
    pub created: DateTime<Utc>,
    /// When the ticket was last modified.
    pub updated: DateTime<Utc>,
}

fn one() -> u64 {
    1
}

impl Ticket {
    /// Create a new ticket with the given ID and title.
    pub fn new(id: impl Into<String>, title: impl Into<String>, now: DateTime<Utc>) -> Self {
        Ticket {
            version: FORMAT_VERSION,
            id: id.into(),
            title: title.into(),
            body: String::new(),
            priority: None,
            labels: Vec::new(),
            assignees: Vec::new(),
            relations: Vec::new(),
            attachments: Vec::new(),
            comments: Vec::new(),
            activity: Vec::new(),
            next_comment: 1,
            created: now,
            updated: now,
        }
    }

    /// Append a comment, allocating the next comment ID. Returns the new comment ID.
    pub fn add_comment(
        &mut self,
        author: impl Into<String>,
        body: impl Into<String>,
        now: DateTime<Utc>,
    ) -> String {
        let id = crate::id::comment_id(self.next_comment);
        self.next_comment += 1;
        self.comments.push(Comment {
            id: id.clone(),
            author: author.into(),
            body: body.into(),
            created: now,
            edited: None,
        });
        self.updated = now;
        id
    }

    /// Append an activity event. `detail` may be empty when `kind` is self-explanatory.
    pub fn log_activity(
        &mut self,
        actor: impl Into<String>,
        kind: impl Into<String>,
        detail: impl Into<String>,
        now: DateTime<Utc>,
    ) {
        self.activity.push(Activity {
            ts: now,
            actor: actor.into(),
            kind: kind.into(),
            detail: detail.into(),
        });
    }
}

/// A relation from one ticket to another.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Relation {
    /// Kind of relation.
    pub kind: RelationKind,
    /// Target ticket ID.
    pub target: String,
}

/// The kind of a [`Relation`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RelationKind {
    /// This ticket blocks the target.
    Blocks,
    /// This ticket is blocked by the target.
    BlockedBy,
    /// The target is a parent of this ticket.
    Parent,
    /// The target is a child of this ticket.
    Child,
    /// A soft relationship.
    Relates,
}

/// An inline comment on a ticket.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Comment {
    /// Comment ID, e.g. `c-7`.
    pub id: String,
    /// Author identity (git `Name <email>` or agent ID).
    pub author: String,
    /// Comment body (Markdown allowed).
    pub body: String,
    /// When the comment was posted.
    pub created: DateTime<Utc>,
    /// When the comment was last edited, if ever.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edited: Option<DateTime<Utc>>,
}

/// A recorded change to a ticket, shown in the activity timeline alongside
/// comments. Kept deliberately small and pre-classified so any front-end can
/// render a phrase from `kind` + `detail` without re-deriving it from diffs.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Activity {
    /// When it happened.
    pub ts: DateTime<Utc>,
    /// Who did it (git `Name <email>` or agent ID).
    pub actor: String,
    /// Event kind: one of `created`, `moved`, `renamed`, `edited`, `priority`,
    /// `label-added`, `label-removed`, `assigned`, `unassigned`, `attached`,
    /// `detached`.
    pub kind: String,
    /// Event-specific detail (destination list, label, assignee, attachment
    /// name, priority value). Empty when the `kind` alone says everything.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub detail: String,
}

/// A file attached to a ticket.
///
/// `path` is always **repo-relative**. Depending on `source` it either points at a
/// file already tracked in the repository (no copy is made) or at a file copied
/// into `.wipe/media/`. This avoids duplicating files that already live in the repo.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
    /// Display file name.
    pub name: String,
    /// Repo-relative path to the file.
    pub path: String,
    /// Where the file lives.
    pub source: AttachmentSource,
    /// File size in bytes.
    pub size: u64,
    /// MIME type (best-effort, from the file extension).
    pub mime: String,
}

/// Where an [`Attachment`]'s bytes live.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AttachmentSource {
    /// Copied into `.wipe/media/`.
    Media,
    /// References a file already tracked in the repository.
    Repo,
}

// ---------------------------------------------------------------------------
// forum/<id>.json  - the project's git-tracked discussion forum
// ---------------------------------------------------------------------------

/// A forum thread: a root [`Post`] plus its nested reply tree. Stored as one file
/// per thread under `.wipe/forum/<id>.json`, so replies to different threads never
/// conflict and deleting a thread is deleting a file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Thread {
    /// On-disk format version.
    pub version: u32,
    /// Thread ID, e.g. `F-1` (also the ID of its root post).
    pub id: String,
    /// Thread title (the headline of the root post).
    pub title: String,
    /// The root post and, nested within it, the whole reply tree.
    pub root: Post,
    /// When the thread was created.
    pub created: DateTime<Utc>,
    /// When anything in the thread last changed.
    pub updated: DateTime<Utc>,
}

/// A single forum post: the root of a thread, or a reply at any depth. IDs are
/// dotted and self-describing (`F-1`, `F-1.1`, `F-1.1.2`), so the tree is legible
/// from the ID alone and a subtree is "every ID under this prefix".
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Post {
    /// Dotted post ID (`F-1`, `F-1.2`, `F-1.2.1`).
    pub id: String,
    /// Author identity (git `Name <email>` or agent ID), same pool as tickets.
    pub author: String,
    /// Message body (Markdown allowed).
    pub body: String,
    /// Labels, drawn from the same board label pool as tickets.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
    /// Attached media/files (same storage as ticket attachments).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<Attachment>,
    /// Free-form references (ticket IDs like `T-3`, other post IDs, or URLs).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub refs: Vec<String>,
    /// When the post was created.
    pub created: DateTime<Utc>,
    /// When the post was last edited, if ever.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edited: Option<DateTime<Utc>>,
    /// Next child index; the next reply gets `<id>.<next_reply>` (never reused).
    #[serde(default = "one")]
    pub next_reply: u64,
    /// Direct replies (each may have its own replies, forming the tree).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub replies: Vec<Post>,
}

impl Post {
    /// Create a fresh post with no replies.
    pub fn new(
        id: impl Into<String>,
        author: impl Into<String>,
        body: impl Into<String>,
        now: DateTime<Utc>,
    ) -> Self {
        Post {
            id: id.into(),
            author: author.into(),
            body: body.into(),
            labels: Vec::new(),
            attachments: Vec::new(),
            refs: Vec::new(),
            created: now,
            edited: None,
            next_reply: 1,
            replies: Vec::new(),
        }
    }

    /// Find a post by ID anywhere in this subtree (including `self`).
    pub fn find(&self, id: &str) -> Option<&Post> {
        if self.id == id {
            return Some(self);
        }
        self.replies.iter().find_map(|r| r.find(id))
    }

    /// Find a post by ID anywhere in this subtree (mutable).
    pub fn find_mut(&mut self, id: &str) -> Option<&mut Post> {
        if self.id == id {
            return Some(self);
        }
        self.replies.iter_mut().find_map(|r| r.find_mut(id))
    }

    /// Remove the direct child with `id` (not recursive). Returns true if removed.
    pub fn remove_child(&mut self, id: &str) -> bool {
        let before = self.replies.len();
        self.replies.retain(|r| r.id != id);
        if self.replies.len() != before {
            return true;
        }
        self.replies.iter_mut().any(|r| r.remove_child(id))
    }

    /// Visit every post in this subtree (pre-order) with its depth (root = 0).
    pub fn walk<'a>(&'a self, depth: usize, f: &mut dyn FnMut(&'a Post, usize)) {
        f(self, depth);
        for r in &self.replies {
            r.walk(depth + 1, f);
        }
    }
}

// ---------------------------------------------------------------------------
// identities.json
// ---------------------------------------------------------------------------

/// A person or agent that can be assigned to tickets and author comments.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Identity {
    /// Stable identity key (e.g. a git email, or an agent slug like `claude`).
    pub id: String,
    /// Editable display name.
    pub display_name: String,
    /// Whether this identity is a human or an agent.
    pub kind: IdentityKind,
}

/// Kind of an [`Identity`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IdentityKind {
    /// A human contributor (typically discovered from git).
    #[default]
    Human,
    /// An AI agent.
    Agent,
}

// ---------------------------------------------------------------------------
// definitions.json
// ---------------------------------------------------------------------------

/// The label color palette. New labels are auto-assigned the first unused entry;
/// colors can also be changed later. Matches the label set in `docs/DESIGN.md`.
pub const LABEL_PALETTE: &[&str] = &[
    "#CC785C", // terracotta
    "#6C7BA8", // indigo
    "#7E9B7A", // sage
    "#61AAF2", // sky
    "#BF4D43", // clay
    "#D4A27F", // kraft
    "#9A7AA0", // plum
    "#3E9C93", // teal
    "#E0A33B", // amber
    "#C77C93", // rose
    "#4F7A55", // forest
    "#9E8FC2", // lavender
    "#B0455A", // ruby
    "#8A9A5B", // olive
    "#7C8AA0", // steel
    "#8C6A54", // cocoa
    "#EBDBBC", // manilla
    "#666663", // slate
];

/// Pick the first palette color not already used by an existing label; if every
/// palette color is in use, cycle deterministically by count.
pub fn next_label_color(existing: &[LabelDef]) -> String {
    let used: std::collections::HashSet<&str> =
        existing.iter().filter_map(|l| l.color.as_deref()).collect();
    for c in LABEL_PALETTE {
        if !used.contains(c) {
            return (*c).to_string();
        }
    }
    LABEL_PALETTE[existing.len() % LABEL_PALETTE.len()].to_string()
}

/// Project-wide registries: labels and priorities. (Tickets are categorized by
/// labels only; there is no separate "type" or "tags" concept.)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Definitions {
    /// On-disk format version.
    pub version: u32,
    /// Defined labels.
    #[serde(default)]
    pub labels: Vec<LabelDef>,
    /// Allowed priorities, ordered from lowest to highest.
    #[serde(default)]
    pub priorities: Vec<String>,
}

impl Definitions {
    /// A sensible default set of definitions for a new board.
    pub fn seed() -> Self {
        Definitions {
            version: FORMAT_VERSION,
            labels: vec![
                LabelDef::new("blocked", Some(LABEL_PALETTE[4])),
                LabelDef::new("needs-review", Some(LABEL_PALETTE[3])),
                LabelDef::new("agent", Some(LABEL_PALETTE[6])),
            ],
            priorities: vec![
                "low".into(),
                "medium".into(),
                "high".into(),
                "urgent".into(),
            ],
        }
    }
}

/// A label definition.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LabelDef {
    /// Label name (unique within the board).
    pub name: String,
    /// Optional UI color.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// Optional description.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
}

impl LabelDef {
    /// Create a label with a name and optional color.
    pub fn new(name: impl Into<String>, color: Option<&str>) -> Self {
        LabelDef {
            name: name.into(),
            color: color.map(|c| c.to_string()),
            description: String::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// settings.json
// ---------------------------------------------------------------------------

/// Project settings, including how the local daemon is exposed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Settings {
    /// On-disk format version.
    pub version: u32,
    /// Local daemon settings.
    #[serde(default)]
    pub daemon: DaemonSettings,
    /// Maximum size, in MB, for a single attachment upload. Defaults to 50 MB to
    /// match git/GitHub's soft warning threshold; larger uploads are rejected.
    #[serde(default = "default_max_attachment_mb")]
    pub max_attachment_mb: u64,
}

fn default_max_attachment_mb() -> u64 {
    50
}

impl Default for Settings {
    fn default() -> Self {
        Settings {
            version: FORMAT_VERSION,
            daemon: DaemonSettings::default(),
            max_attachment_mb: default_max_attachment_mb(),
        }
    }
}

/// Configuration for the local daemon that serves the human UX.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DaemonSettings {
    /// Port to listen on.
    pub port: u16,
    /// How the daemon is exposed beyond localhost.
    #[serde(default)]
    pub expose: Exposure,
    /// When true, the daemon shuts itself down after `idle_timeout_secs` with no
    /// connected UI clients, so it leaves no background overhead when not viewed.
    #[serde(default)]
    pub autoserve: bool,
    /// Idle timeout (seconds) used when auto-serving / `--idle` is active.
    #[serde(default = "default_idle_timeout")]
    pub idle_timeout_secs: u64,
}

fn default_idle_timeout() -> u64 {
    900
}

impl Default for DaemonSettings {
    fn default() -> Self {
        DaemonSettings {
            port: DEFAULT_PORT,
            expose: Exposure::default(),
            autoserve: false,
            idle_timeout_secs: default_idle_timeout(),
        }
    }
}

/// How the local daemon is reachable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Exposure {
    /// Localhost only.
    #[default]
    None,
    /// Advertised over a Tailscale network.
    Tailscale,
    /// Behind a user-provided reverse proxy.
    Proxy,
}

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

    fn fixed() -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 7, 2, 12, 0, 0).unwrap()
    }

    #[test]
    fn board_has_default_lists() {
        let b = Board::new("Demo", fixed());
        assert_eq!(b.lists.len(), 4);
        assert_eq!(b.lists[2].id, "in-progress");
        assert_eq!(b.next_ticket, 1);
    }

    #[test]
    fn ticket_omits_empty_fields_and_has_no_type_or_tags() {
        let t = Ticket::new("T-1", "Hello", fixed());
        let json = serde_json::to_string(&t).unwrap();
        // Empty vecs and empty body are skipped for clean diffs.
        assert!(!json.contains("labels"));
        assert!(!json.contains("assignees"));
        assert!(!json.contains("\"body\""));
        // Type and tags no longer exist.
        assert!(!json.contains("\"type\""));
        assert!(!json.contains("tags"));
    }

    #[test]
    fn label_color_auto_picks_unused() {
        let existing = vec![LabelDef::new("a", Some(LABEL_PALETTE[0]))];
        let picked = next_label_color(&existing);
        assert_eq!(picked, LABEL_PALETTE[1]);
    }

    #[test]
    fn comment_allocation_is_monotonic() {
        let mut t = Ticket::new("T-1", "Hello", fixed());
        let a = t.add_comment("me", "first", fixed());
        let b = t.add_comment("me", "second", fixed());
        assert_eq!(a, "c-1");
        assert_eq!(b, "c-2");
        assert_eq!(t.next_comment, 3);
    }

    #[test]
    fn relation_kind_is_kebab_case() {
        let r = Relation {
            kind: RelationKind::BlockedBy,
            target: "T-2".into(),
        };
        assert_eq!(
            serde_json::to_string(&r).unwrap(),
            r#"{"kind":"blocked-by","target":"T-2"}"#
        );
    }
}