lific 2.8.0

Local-first, lightweight issue tracker. Single binary, SQLite-backed, MCP-native.
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
//! Output for the data commands, shared by both backends: the human-readable
//! renderers, plus the result types a command has to invent when there is no
//! model to print.
//!
//! LIF-373: `lific issue list` used to print a formatted table when it ran
//! against the local database and a raw JSON dump when it ran against
//! `--url`, because the SQL executor and the HTTP backend each owned their
//! own output code. Both now call these functions with the same
//! `db::models` types (the HTTP backend deserializes the API response into
//! them), so what you see no longer depends on the transport.
//!
//! Every function returns the exact text to print, trailing newlines
//! included, so callers `print!` it and tests can compare the two backends'
//! output directly.
//!
//! LIF-341 finished the job for the commands LIF-373 did not reach: exports
//! (the HTTP backend now writes the same files to the same paths, unpacking
//! the project archive locally) and deletes (both backends print the
//! [`Deleted`] below).

use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::db::models::{
    Comment, Folder, Issue, Label, Module, Page, Priority, Project, SearchResult, Status,
};

/// What a `delete` prints under `--json`.
///
/// Deleting a module, label, or folder returns no row to serialize, so each
/// backend used to hand-roll its own answer: the SQL executor printed a
/// compact `{"deleted": true, "name": ...}` while the HTTP backend turned a
/// `204 No Content` into a pretty-printed `{"deleted": true}` with no name at
/// all. Both now build this (LIF-341).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Deleted {
    pub deleted: bool,
    pub name: String,
}

impl Deleted {
    #[must_use]
    pub fn named(name: &str) -> Self {
        Self {
            deleted: true,
            name: name.to_owned(),
        }
    }
}

/// `writeln!` into a `String` cannot fail, so the renderers would otherwise
/// be littered with `let _ =`. With no format arguments this writes a bare
/// blank line.
macro_rules! w {
    ($out:expr) => {
        $out.push('\n')
    };
    ($out:expr, $($arg:tt)+) => {{
        let _ = writeln!($out, $($arg)+);
    }};
}

/// Resolves a module id to its display name. The SQL backend reads it from
/// the database; the HTTP backend looks it up in a map fetched from
/// `/api/modules`. `None` (unresolvable module) renders as no module at all,
/// on both sides.
pub type ModuleName<'a> = &'a dyn Fn(i64) -> Option<String>;

/// Format a priority with visual indicator for human output.
pub fn fmt_priority(priority: Priority) -> &'static str {
    match priority {
        Priority::Urgent => "!!!  urgent",
        Priority::High => "!!   high",
        Priority::Medium => "!    medium",
        Priority::Low => "     low",
        Priority::None => "     none",
    }
}

/// Format a status with visual indicator for human output.
pub fn fmt_status(status: Status) -> &'static str {
    match status {
        Status::Backlog => "[ ] backlog",
        Status::Todo => "[.] todo",
        Status::Active => "[~] active",
        Status::Done => "[x] done",
        Status::Cancelled => "[-] cancelled",
    }
}

fn bracketed_labels(labels: &[String]) -> String {
    if labels.is_empty() {
        String::new()
    } else {
        format!(" [{}]", labels.join(", "))
    }
}

fn first_line_suffix(text: &str) -> String {
    if text.is_empty() {
        String::new()
    } else {
        format!(" - {}", text.lines().next().unwrap_or(""))
    }
}

// ── Issue ────────────────────────────────────────────────────

pub fn issue_list(issues: &[Issue], module_name: ModuleName<'_>) -> String {
    let mut out = String::new();
    if issues.is_empty() {
        w!(out, "No issues found.");
        return out;
    }
    w!(out, "{} issue(s):\n", issues.len());
    for issue in issues {
        let module = issue
            .module_id
            .and_then(module_name)
            .map(|name| format!(" ({name})"))
            .unwrap_or_default();
        w!(
            out,
            "  {:<8} {} | {} | {}{}{}",
            issue.identifier,
            fmt_status(issue.status),
            fmt_priority(issue.priority),
            issue.title,
            bracketed_labels(&issue.labels),
            module
        );
    }
    out
}

pub fn issue_detail(issue: &Issue, module_name: ModuleName<'_>) -> String {
    let mut out = String::new();
    w!(out, "{} - {}", issue.identifier, issue.title);
    w!(out, "  Status:   {}", issue.status);
    w!(out, "  Priority: {}", issue.priority);
    if !issue.labels.is_empty() {
        w!(out, "  Labels:   {}", issue.labels.join(", "));
    }
    if let Some(name) = issue.module_id.and_then(module_name) {
        w!(out, "  Module:   {name}");
    }
    if !issue.blocks.is_empty() {
        w!(out, "  Blocks:   {}", issue.blocks.join(", "));
    }
    if !issue.blocked_by.is_empty() {
        w!(out, "  Blocked:  {}", issue.blocked_by.join(", "));
    }
    if !issue.relates_to.is_empty() {
        w!(out, "  Relates:  {}", issue.relates_to.join(", "));
    }
    if !issue.duplicates.is_empty() {
        w!(out, "  Dupes:    {}", issue.duplicates.join(", "));
    }
    if !issue.duplicated_by.is_empty() {
        w!(out, "  DupedBy:  {}", issue.duplicated_by.join(", "));
    }
    if !issue.description.is_empty() {
        w!(out);
        w!(out, "{}", issue.description);
    }
    out
}

pub fn issue_created(issue: &Issue) -> String {
    let mut out = String::new();
    w!(out, "Created {}: {}", issue.identifier, issue.title);
    out
}

pub fn issue_updated(issue: &Issue) -> String {
    let mut out = String::new();
    w!(out, "Updated {}: {}", issue.identifier, issue.title);
    w!(out, "  Status:   {}", issue.status);
    w!(out, "  Priority: {}", issue.priority);
    out
}

// ── Project ──────────────────────────────────────────────────

pub fn project_list(projects: &[Project]) -> String {
    let mut out = String::new();
    if projects.is_empty() {
        w!(out, "No projects.");
        return out;
    }
    w!(out, "{} project(s):\n", projects.len());
    for project in projects {
        w!(
            out,
            "  {:<5} {}{}",
            project.identifier,
            project.name,
            first_line_suffix(&project.description)
        );
    }
    out
}

pub fn project_detail(project: &Project) -> String {
    let mut out = String::new();
    w!(out, "{} - {}", project.identifier, project.name);
    if !project.description.is_empty() {
        w!(out);
        w!(out, "{}", project.description);
    }
    out
}

pub fn project_created(project: &Project) -> String {
    let mut out = String::new();
    w!(
        out,
        "Created project {} ({})",
        project.name,
        project.identifier
    );
    out
}

pub fn project_updated(project: &Project) -> String {
    let mut out = String::new();
    w!(
        out,
        "Updated project {} ({})",
        project.name,
        project.identifier
    );
    out
}

// ── Page ─────────────────────────────────────────────────────

pub fn page_list(pages: &[Page]) -> String {
    let mut out = String::new();
    if pages.is_empty() {
        w!(out, "No pages found.");
        return out;
    }
    w!(out, "{} page(s):\n", pages.len());
    for page in pages {
        let preview = if page.content.is_empty() {
            "(empty)".to_string()
        } else {
            let first_line = page.content.lines().next().unwrap_or("");
            if first_line.len() > 60 {
                format!("{}...", &first_line[..60])
            } else {
                first_line.to_string()
            }
        };
        w!(
            out,
            "  {:<12} {} - {}{}",
            page.identifier,
            page.title,
            preview,
            bracketed_labels(&page.labels)
        );
    }
    out
}

pub fn page_detail(page: &Page) -> String {
    let mut out = String::new();
    w!(out, "{} - {}", page.identifier, page.title);
    if !page.labels.is_empty() {
        w!(out, "  Labels: {}", page.labels.join(", "));
    }
    if !page.content.is_empty() {
        w!(out);
        w!(out, "{}", page.content);
    }
    out
}

pub fn page_created(page: &Page) -> String {
    let mut out = String::new();
    w!(out, "Created page {}: {}", page.identifier, page.title);
    out
}

pub fn page_updated(page: &Page) -> String {
    let mut out = String::new();
    w!(out, "Updated page {}: {}", page.identifier, page.title);
    out
}

// ── Search ───────────────────────────────────────────────────

pub fn search_results(results: &[SearchResult]) -> String {
    let mut out = String::new();
    if results.is_empty() {
        w!(out, "No results found.");
        return out;
    }
    w!(out, "{} result(s):\n", results.len());
    for result in results {
        let identifier = result.identifier.as_deref().unwrap_or("?");
        w!(
            out,
            "  {:<12} [{}] {}",
            identifier,
            result.result_type,
            result.title
        );
        if !result.snippet.is_empty() {
            // Clean up snippet for terminal display
            let snippet = result.snippet.replace("**", "").replace('\n', " ");
            let snippet = if snippet.len() > 80 {
                format!("{}...", &snippet[..80])
            } else {
                snippet
            };
            w!(out, "              {}", snippet);
        }
    }
    out
}

// ── Comment ──────────────────────────────────────────────────

/// What the CLI knows about comments sitting past the page it just printed.
///
/// This is three states, not an `Option`, because "there is no next page" and
/// "I could not find out" are different things to tell a user. Collapsing them
/// meant a failed lookup rendered as a complete thread, which is the one
/// answer a bounded listing must never give by accident.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommentContinuation {
    /// The page reached the end of the thread.
    End,
    /// More comments exist; this offset reads the next page.
    Next(i64),
    /// The page came back full and the check for a row past it failed, so
    /// whether more exist is genuinely unknown. Only the remote backend can
    /// reach this: the direct-SQL page answers `has_more` from an over-fetch
    /// inside its own query, which cannot fail on its own.
    Unknown(i64),
}

/// Render one page of a comment thread.
///
/// Both backends bound `comment list` now, so without the trailing line a
/// truncated thread would be indistinguishable from a complete one, which is
/// the failure mode the bound would otherwise introduce.
pub fn comment_list(
    comments: &[Comment],
    identifier: &str,
    continuation: CommentContinuation,
) -> String {
    let mut out = String::new();
    if comments.is_empty() {
        w!(out, "No comments on {}.", identifier);
        return out;
    }
    w!(out, "{} comment(s) on {}:\n", comments.len(), identifier);
    for comment in comments {
        w!(
            out,
            "  {} ({}) - {}:",
            comment.author_display_name,
            comment.author,
            comment.created_at
        );
        for line in comment.content.lines() {
            w!(out, "    {line}");
        }
        w!(out);
    }
    match continuation {
        CommentContinuation::End => {}
        CommentContinuation::Next(next) => {
            w!(out, "More comments available. Next page: --offset {}", next);
        }
        CommentContinuation::Unknown(next) => {
            w!(
                out,
                "Could not check whether more comments exist. If they do, the next page is --offset {}.",
                next
            );
        }
    }
    out
}

pub fn comment_added(comment: &Comment, identifier: &str) -> String {
    let mut out = String::new();
    w!(
        out,
        "Added comment to {} by {}:",
        identifier,
        comment.author
    );
    w!(out, "  {}", comment.content);
    out
}

// ── Module ───────────────────────────────────────────────────

pub fn module_list(modules: &[Module], project: &str) -> String {
    let mut out = String::new();
    if modules.is_empty() {
        w!(out, "No modules in {}.", project);
        return out;
    }
    w!(out, "{} module(s) in {}:\n", modules.len(), project);
    for module in modules {
        w!(
            out,
            "  {:<20} [{}]{}",
            module.name,
            module.status,
            first_line_suffix(&module.description)
        );
    }
    out
}

pub fn module_created(module: &Module, project: &str) -> String {
    let mut out = String::new();
    w!(
        out,
        "Created module '{}' [{}] in {}",
        module.name,
        module.status,
        project
    );
    out
}

pub fn module_updated(module: &Module) -> String {
    let mut out = String::new();
    w!(out, "Updated module '{}' [{}]", module.name, module.status);
    out
}

pub fn module_deleted(name: &str) -> String {
    let mut out = String::new();
    w!(out, "Deleted module '{}'", name);
    out
}

// ── Label ────────────────────────────────────────────────────

pub fn label_list(labels: &[Label], project: &str) -> String {
    let mut out = String::new();
    if labels.is_empty() {
        w!(out, "No labels in {}.", project);
        return out;
    }
    w!(out, "{} label(s) in {}:\n", labels.len(), project);
    for label in labels {
        w!(out, "  {} ({})", label.name, label.color);
    }
    out
}

pub fn label_created(label: &Label) -> String {
    let mut out = String::new();
    w!(out, "Created label '{}' ({})", label.name, label.color);
    out
}

pub fn label_updated(label: &Label) -> String {
    let mut out = String::new();
    w!(out, "Updated label '{}' ({})", label.name, label.color);
    out
}

pub fn label_deleted(name: &str) -> String {
    let mut out = String::new();
    w!(out, "Deleted label '{}'", name);
    out
}

// ── Folder ───────────────────────────────────────────────────

pub fn folder_list(folders: &[Folder], project: &str) -> String {
    let mut out = String::new();
    if folders.is_empty() {
        w!(out, "No folders in {}.", project);
        return out;
    }
    w!(out, "{} folder(s) in {}:\n", folders.len(), project);
    for folder in folders {
        w!(out, "  {}", folder.name);
    }
    out
}

pub fn folder_created(folder: &Folder) -> String {
    let mut out = String::new();
    w!(out, "Created folder '{}'", folder.name);
    out
}

pub fn folder_updated(previous_name: &str, folder: &Folder) -> String {
    let mut out = String::new();
    w!(
        out,
        "Renamed folder '{}' -> '{}'",
        previous_name,
        folder.name
    );
    out
}

pub fn folder_deleted(name: &str) -> String {
    let mut out = String::new();
    w!(out, "Deleted folder '{}'", name);
    out
}

// ── Export ───────────────────────────────────────────────────

pub fn export_written(written: &[PathBuf], output: &Path) -> String {
    let mut out = String::new();
    w!(
        out,
        "Exported {} file(s) to {}",
        written.len(),
        output.display()
    );
    for path in written {
        w!(out, "  {}", path.display());
    }
    out
}

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

    fn issue(identifier: &str, status: Status, priority: Priority) -> Issue {
        Issue {
            id: 1,
            project_id: 1,
            sequence: 1,
            identifier: identifier.into(),
            title: "Fix the bug".into(),
            description: String::new(),
            status,
            priority,
            module_id: None,
            sort_order: 0.0,
            start_date: None,
            target_date: None,
            created_at: "2026-01-01T00:00:00Z".into(),
            updated_at: "2026-01-01T00:00:00Z".into(),
            seq: 1,
            source: None,
            labels: Vec::new(),
            blocks: Vec::new(),
            blocked_by: Vec::new(),
            relates_to: Vec::new(),
            duplicates: Vec::new(),
            duplicated_by: Vec::new(),
        }
    }

    fn comment(id: i64, content: &str) -> Comment {
        Comment {
            id,
            issue_id: Some(1),
            page_id: None,
            user_id: 1,
            author: "ada".into(),
            author_display_name: "Ada".into(),
            content: content.into(),
            created_at: "2026-01-01 00:00:00".into(),
            updated_at: "2026-01-01 00:00:00".into(),
            seq: 1,
        }
    }

    /// The three continuation states have to read differently. A page that
    /// ends the thread says nothing extra, a page with more says where to go,
    /// and a page whose lookahead failed admits it instead of passing for a
    /// complete thread.
    #[test]
    fn distinguishes_a_finished_thread_from_an_unchecked_one() {
        let page = [comment(1, "hello")];

        let complete = comment_list(&page, "TST-1", CommentContinuation::End);
        assert!(!complete.contains("More comments"), "got: {complete}");
        assert!(!complete.contains("Could not check"), "got: {complete}");

        let more = comment_list(&page, "TST-1", CommentContinuation::Next(50));
        assert!(
            more.contains("More comments available. Next page: --offset 50\n"),
            "got: {more}"
        );

        let unknown = comment_list(&page, "TST-1", CommentContinuation::Unknown(50));
        assert!(
            unknown.contains(
                "Could not check whether more comments exist. \
                 If they do, the next page is --offset 50.\n"
            ),
            "got: {unknown}"
        );
        assert!(
            !unknown.contains("More comments available"),
            "got: {unknown}"
        );
    }

    #[test]
    fn marks_statuses_and_priorities_with_indicators() {
        assert_eq!(fmt_status(Status::Active), "[~] active");
        assert_eq!(fmt_status(Status::Cancelled), "[-] cancelled");
        assert_eq!(fmt_priority(Priority::Urgent), "!!!  urgent");
        assert_eq!(fmt_priority(Priority::None), "     none");
    }

    #[test]
    fn lists_issues_with_labels_and_module_name() {
        let mut one = issue("TST-1", Status::Active, Priority::High);
        one.labels = vec!["bug".into(), "urgent".into()];
        one.module_id = Some(4);

        let rendered = issue_list(std::slice::from_ref(&one), &|id| {
            (id == 4).then(|| "Core".to_owned())
        });

        assert_eq!(
            rendered,
            "1 issue(s):\n\n  TST-1    [~] active | !!   high | Fix the bug [bug, urgent] (Core)\n"
        );
    }

    #[test]
    fn omits_the_module_when_the_name_cannot_be_resolved() {
        let mut one = issue("TST-1", Status::Todo, Priority::Low);
        one.module_id = Some(9);

        let rendered = issue_list(std::slice::from_ref(&one), &|_| None);

        assert_eq!(
            rendered,
            "1 issue(s):\n\n  TST-1    [.] todo |      low | Fix the bug\n"
        );
    }

    #[test]
    fn reports_empty_collections_without_a_count_header() {
        assert_eq!(issue_list(&[], &|_| None), "No issues found.\n");
        assert_eq!(project_list(&[]), "No projects.\n");
        assert_eq!(page_list(&[]), "No pages found.\n");
        assert_eq!(search_results(&[]), "No results found.\n");
        assert_eq!(
            comment_list(&[], "TST-1", CommentContinuation::End),
            "No comments on TST-1.\n"
        );
        assert_eq!(module_list(&[], "TST"), "No modules in TST.\n");
        assert_eq!(label_list(&[], "TST"), "No labels in TST.\n");
        assert_eq!(folder_list(&[], "TST"), "No folders in TST.\n");
    }

    #[test]
    fn details_an_issue_with_its_relations_and_description() {
        let mut one = issue("TST-1", Status::Active, Priority::Urgent);
        one.description = "Details".into();
        one.blocks = vec!["TST-2".into()];
        one.duplicated_by = vec!["TST-3".into()];

        assert_eq!(
            issue_detail(&one, &|_| None),
            "TST-1 - Fix the bug\n  Status:   active\n  Priority: urgent\n  \
             Blocks:   TST-2\n  DupedBy:  TST-3\n\nDetails\n"
        );
    }
}