task-track 0.6.1

A JJ workspace-based task and TODO management CLI tool
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
//! Data models for the track CLI application.
//!
//! This module defines the core data structures used throughout the application,
//! including tasks, TODOs, links, scraps, and JJ-related items.

use chrono::{DateTime, Utc};
use serde::Serialize;

mod jj;
mod status;
mod todo_action;
mod vcs_mode;
mod workflow;

pub use jj::{jj_slug, sanitize_jj_slug};
pub use status::{TaskStatus, TodoStatus};
pub use todo_action::TodoAction;
pub use vcs_mode::VcsMode;
pub use workflow::{
    build_git_context, build_jj_context, build_next_action, compute_workflow_phase,
    oldest_pending_todo, workspace_lifecycle, AgentGuardrails, GitAgentContext, JjAgentContext,
    NextAction, TodoAgentView, WorkflowContext, WorkflowPhase, WorkspaceAgentView,
    WorkspaceLifecycle,
};

fn render_markdown_with_links(content: &str) -> String {
    use pulldown_cmark::{html, Event, Parser, Tag, TagEnd};
    use regex::Regex;
    use std::collections::{HashMap, HashSet};

    let url_regex =
        Regex::new(r"(?P<pre>^|[\s\(])(?P<url>https?://[^\s\)<>]+?)(?P<post>[.,;!?]*(?:[\s\)]|$))")
            .unwrap();

    let linkified = url_regex.replace_all(content, |caps: &regex::Captures| {
        let pre = &caps["pre"];
        let url = &caps["url"];
        let post = &caps["post"];

        let cap_start = caps.get(0).unwrap().start();
        if cap_start >= 2 {
            let before = &content[..cap_start];
            if before.ends_with("](") {
                return caps.get(0).unwrap().as_str().to_string();
            }
        }

        format!("{}<{}>{}", pre, url, post)
    });

    let parser = Parser::new(linkified.as_ref());
    let sanitized = parser.map(|event| match event {
        Event::Html(html) | Event::InlineHtml(html) => {
            let escaped = html_escape::encode_safe(&html).into_owned();
            Event::Text(escaped.into())
        }
        _ => event,
    });

    let parser_with_target = sanitized.map(|event| match event {
        Event::Start(Tag::Link {
            link_type: _,
            dest_url,
            title,
            id: _,
        }) => Event::Html(
            format!(
                r#"<a href="{}" target="_blank" rel="noopener noreferrer"{}>"#,
                html_escape::encode_double_quoted_attribute(&dest_url),
                if !title.is_empty() {
                    format!(
                        r#" title="{}""#,
                        html_escape::encode_double_quoted_attribute(&title)
                    )
                } else {
                    String::new()
                }
            )
            .into(),
        ),
        Event::End(TagEnd::Link) => Event::Html("</a>".into()),
        _ => event,
    });

    let mut html_output = String::new();
    html::push_html(&mut html_output, parser_with_target);

    let allowed_tags: HashSet<&'static str> = [
        "a",
        "p",
        "ul",
        "ol",
        "li",
        "strong",
        "em",
        "code",
        "pre",
        "blockquote",
        "br",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
    ]
    .into_iter()
    .collect();
    let allowed_attrs: HashSet<&'static str> = ["href", "title", "target"].into_iter().collect();
    let mut allowed_tag_attrs = HashMap::new();
    allowed_tag_attrs.insert("a", allowed_attrs);

    ammonia::Builder::default()
        .tags(allowed_tags)
        .tag_attributes(allowed_tag_attrs)
        .link_rel(Some("noopener noreferrer"))
        .clean(&html_output)
        .to_string()
}

/// Represents a development task.
///
/// A task is the primary organizational unit in track. Each task can have multiple TODOs,
/// links, scraps, and associated JJ repositories.
#[derive(Debug, Clone, Serialize)]
pub struct Task {
    pub id: i64,
    pub name: String,
    pub description: Option<String>,
    pub status: TaskStatus,
    pub ticket_id: Option<String>,
    pub ticket_url: Option<String>,
    pub alias: Option<String>,
    pub is_today_task: bool,
    pub created_at: DateTime<Utc>,
}

/// Represents a TODO item within a task.
///
/// TODOs are task-scoped action items. Each TODO has a task-specific index
/// and can optionally request a JJ workspace for isolated development.
#[derive(Debug, Clone, Serialize)]
pub struct Todo {
    #[serde(skip)]
    pub id: i64,
    #[serde(skip)]
    #[allow(dead_code)]
    pub task_id: i64,
    /// Task-scoped sequential ID for this TODO
    #[serde(rename = "todo_id")]
    pub task_index: i64,
    pub content: String,
    pub status: TodoStatus,
    #[serde(skip)]
    pub worktree_requested: bool,
    #[serde(skip)]
    #[allow(dead_code)]
    pub created_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
}

impl Todo {
    /// Converts the todo content from markdown to HTML.
    ///
    /// This method uses pulldown-cmark to parse the markdown content
    /// and render it as HTML. Plain URLs are automatically converted to clickable links.
    /// All links open in new tabs with target="_blank".
    /// The output is safe for display in web pages.
    pub fn content_html(&self) -> String {
        render_markdown_with_links(&self.content)
    }
}

/// Represents a link associated with a task.
///
/// Links are URLs with titles that provide context or reference material for a task.
#[derive(Debug, Clone, Serialize)]
pub struct Link {
    #[serde(skip)]
    #[allow(dead_code)]
    pub id: i64,
    #[serde(skip)]
    #[allow(dead_code)]
    pub task_id: i64,
    /// Task-scoped sequential ID for this link
    #[serde(rename = "link_id")]
    pub task_index: i64,
    pub url: String,
    pub title: String,
    #[serde(skip)]
    #[allow(dead_code)]
    pub created_at: DateTime<Utc>,
}

/// Represents a scrap (work note) for a task.
///
/// Scraps are chronological notes that capture progress, decisions, and findings
/// during task execution. They help maintain context and flow of work.
#[derive(Debug, Clone, Serialize)]
pub struct Scrap {
    #[serde(skip)]
    #[allow(dead_code)]
    pub id: i64,
    #[serde(skip)]
    #[allow(dead_code)]
    pub task_id: i64,
    /// Task-scoped sequential ID for this scrap
    pub scrap_id: i64,
    pub content: String,
    pub created_at: DateTime<Utc>,
    /// The task_index of the active (oldest pending) todo when this scrap was created
    pub active_todo_id: Option<i64>,
}

impl Scrap {
    /// Converts the scrap content from markdown to HTML.
    ///
    /// This method uses pulldown-cmark to parse the markdown content
    /// and render it as HTML. Plain URLs are automatically converted to clickable links.
    /// All links open in new tabs with target="_blank".
    /// The output is safe for display in web pages.
    pub fn content_html(&self) -> String {
        render_markdown_with_links(&self.content)
    }
}

/// Represents a JJ workspace associated with a task or TODO.
///
/// Worktrees track both base repositories and TODO-specific workspaces,
/// including their paths, bookmarks, and relationships.
#[derive(Debug, Clone, Serialize)]
pub struct Worktree {
    pub id: i64,
    pub task_id: i64,
    pub path: String,
    pub branch: String,
    pub base_repo: Option<String>,
    #[allow(dead_code)]
    pub status: String,
    #[allow(dead_code)]
    pub created_at: DateTime<Utc>,
    #[allow(dead_code)]
    pub todo_id: Option<i64>,
    #[allow(dead_code)]
    pub is_base: bool,
}

/// Represents a remote repository link for a worktree.
///
/// RepoLinks store URLs to remote repositories (e.g., GitHub, GitLab)
/// and their types (e.g., "origin", "upstream").
#[derive(Debug, Clone, Serialize)]
pub struct RepoLink {
    #[allow(dead_code)]
    pub id: i64,
    #[allow(dead_code)]
    pub worktree_id: i64,
    pub url: String,
    pub kind: String,
    #[allow(dead_code)]
    pub created_at: DateTime<Utc>,
}

/// Represents a repository associated with a task.
///
/// TaskRepos link JJ repositories to tasks, allowing multiple repositories
/// to be managed within a single task context.
#[derive(Debug, Clone, Serialize)]
pub struct TaskRepo {
    #[serde(skip)]
    pub id: i64,
    #[serde(skip)]
    #[allow(dead_code)]
    pub task_id: i64,
    /// Task-scoped sequential ID for this repository
    #[serde(rename = "repo_id")]
    pub task_index: i64,
    pub repo_path: String,
    pub base_branch: Option<String>,
    pub base_commit_hash: Option<String>,
    #[serde(skip)]
    #[allow(dead_code)]
    pub created_at: DateTime<Utc>,
}

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

    #[test]
    fn test_scrap_content_html_plain_text() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "This is a plain text scrap.".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        assert!(html.contains("<p>This is a plain text scrap.</p>"));
    }

    #[test]
    fn test_scrap_content_html_with_markdown() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "# Heading\n\nThis is **bold** and *italic*.".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        assert!(html.contains("<h1>Heading</h1>"));
        assert!(html.contains("<strong>bold</strong>"));
        assert!(html.contains("<em>italic</em>"));
    }

    #[test]
    fn test_scrap_content_html_with_code() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "Inline `code` and:\n\n```rust\nfn main() {}\n```".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        assert!(html.contains("<code>code</code>"));
        assert!(html.contains("<pre><code"));
        assert!(html.contains("fn main() {}"));
    }

    #[test]
    fn test_scrap_content_html_with_list() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "- Item 1\n- Item 2\n- Item 3".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        assert!(html.contains("<ul>"));
        assert!(html.contains("<li>Item 1</li>"));
        assert!(html.contains("<li>Item 2</li>"));
        assert!(html.contains("<li>Item 3</li>"));
        assert!(html.contains("</ul>"));
    }

    #[test]
    fn test_scrap_content_html_with_link() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "[Example](https://example.com)".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        assert!(html.contains("href=\"https://example.com\""));
        assert!(html.contains("target=\"_blank\""));
        assert!(html.contains("rel=\"noopener noreferrer\""));
    }

    #[test]
    fn test_scrap_content_html_sanitizes_html() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "<script>alert('x')</script><b>safe</b>".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        assert!(!html.contains("<script>"));
        assert!(!html.contains("alert('x')"));
        assert!(html.contains("safe"));
    }

    #[test]
    fn test_scrap_content_html_auto_linkify_plain_url() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "Check out https://example.com for more info.".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        assert!(html.contains("target=\"_blank\""));
        assert!(html.contains("https://example.com"));
    }

    #[test]
    fn test_scrap_content_html_auto_linkify_multiple_urls() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "See https://example.com and http://test.org".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        assert!(html.contains("target=\"_blank\""));
        assert!(html.contains("https://example.com"));
        assert!(html.contains("http://test.org"));
    }

    #[test]
    fn test_scrap_content_html_auto_linkify_url_with_punctuation() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "Visit https://example.com/path?query=1, it's great!".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        // The comma should not be part of the link
        assert!(html.contains("target=\"_blank\""));
        assert!(html.contains("https://example.com/path?query=1"));
    }

    #[test]
    fn test_scrap_content_html_preserve_markdown_links() {
        let scrap = Scrap {
            id: 1,
            task_id: 1,
            scrap_id: 1,
            content: "Check [my site](https://example.com) and also https://test.com".to_string(),
            created_at: Utc::now(),
            active_todo_id: None,
        };
        let html = scrap.content_html();
        // Markdown link should work normally
        assert!(html.contains("target=\"_blank\""));
        assert!(html.contains("my site"));
        // Plain URL should be auto-linkified
        assert!(html.contains("https://test.com"));
    }

    #[test]
    fn test_todo_content_html_plain_text() {
        let todo = Todo {
            id: 1,
            task_id: 1,
            task_index: 1,
            content: "This is a plain text todo.".to_string(),
            status: TodoStatus::Pending,
            worktree_requested: false,
            created_at: Utc::now(),
            completed_at: None,
        };
        let html = todo.content_html();
        assert!(html.contains("<p>This is a plain text todo.</p>"));
    }

    #[test]
    fn test_todo_content_html_auto_linkify_url() {
        let todo = Todo {
            id: 1,
            task_id: 1,
            task_index: 1,
            content: "Check https://example.com for details".to_string(),
            status: TodoStatus::Pending,
            worktree_requested: false,
            created_at: Utc::now(),
            completed_at: None,
        };
        let html = todo.content_html();
        assert!(html.contains("target=\"_blank\""));
        assert!(html.contains("https://example.com"));
    }

    #[test]
    fn test_todo_content_html_with_markdown() {
        let todo = Todo {
            id: 1,
            task_id: 1,
            task_index: 1,
            content: "# Heading\n\nThis is **bold** and *italic*.".to_string(),
            status: TodoStatus::Pending,
            created_at: Utc::now(),
            completed_at: None,
            worktree_requested: false,
        };
        let html = todo.content_html();
        assert!(html.contains("<h1>Heading</h1>"));
        assert!(html.contains("<strong>bold</strong>"));
        assert!(html.contains("<em>italic</em>"));
    }

    #[test]
    fn test_todo_content_html_sanitizes_html() {
        let todo = Todo {
            id: 1,
            task_id: 1,
            task_index: 1,
            content: "<img src=x onerror=alert(1)><b>safe</b>".to_string(),
            status: TodoStatus::Pending,
            created_at: Utc::now(),
            completed_at: None,
            worktree_requested: false,
        };
        let html = todo.content_html();
        assert!(!html.contains("<img"));
        assert!(html.contains("safe"));
    }
}