jjj 0.4.1

Distributed project management and code review for Jujutsu
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// A problem represents something that needs to be addressed.
/// Problems are fundamental - all knowledge begins with problems.
/// Problems can be decomposed into sub-problems, forming a DAG.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Problem {
    /// Unique problem identifier (e.g., "P-1")
    pub id: String,

    /// Problem title (what is the problem?)
    pub title: String,

    /// Parent problem ID (for sub-problems)
    pub parent_id: Option<String>,

    /// Current status
    pub status: ProblemStatus,

    /// Priority level
    pub priority: Priority,

    /// Confidence (RAG) indicator
    #[serde(default, skip_serializing_if = "is_confidence_unknown")]
    pub confidence: Confidence,

    /// Solution IDs attempting to address this problem
    #[serde(default)]
    pub solution_ids: Vec<String>,

    /// Child problem IDs (sub-problems - computed from parent_id references)
    #[serde(default)]
    pub child_ids: Vec<String>,

    /// Target milestone (optional)
    pub milestone_id: Option<String>,

    /// Assigned owner
    pub assignee: Option<String>,

    /// Creation timestamp
    pub created_at: DateTime<Utc>,

    /// Last update timestamp
    pub updated_at: DateTime<Utc>,

    /// Description of the problem (markdown body)
    #[serde(default)]
    pub description: String,

    /// Reason the problem was dissolved (if status is Dissolved)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dissolved_reason: Option<String>,

    /// Linked GitHub issue number
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub github_issue: Option<u64>,

    /// Tags for flexible categorization (e.g., "backend", "size:L", "area:auth")
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
}

/// Confidence (RAG) indicator for problem health/progress.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Confidence {
    #[default]
    Unknown,
    Red,
    Amber,
    Green,
}

impl std::fmt::Display for Confidence {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Confidence::Unknown => write!(f, "unknown"),
            Confidence::Red => write!(f, "red"),
            Confidence::Amber => write!(f, "amber"),
            Confidence::Green => write!(f, "green"),
        }
    }
}

impl std::str::FromStr for Confidence {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "unknown" => Ok(Confidence::Unknown),
            "red" => Ok(Confidence::Red),
            "amber" | "yellow" => Ok(Confidence::Amber),
            "green" => Ok(Confidence::Green),
            _ => Err(format!(
                "Invalid confidence: '{}'. Use unknown, red, amber, or green",
                s
            )),
        }
    }
}

impl Confidence {
    /// Cycle to the next confidence value: Unknown → Red → Amber → Green → Unknown
    pub fn next(&self) -> Self {
        match self {
            Confidence::Unknown => Confidence::Red,
            Confidence::Red => Confidence::Amber,
            Confidence::Amber => Confidence::Green,
            Confidence::Green => Confidence::Unknown,
        }
    }
}

fn is_confidence_unknown(c: &Confidence) -> bool {
    matches!(c, Confidence::Unknown)
}

/// Priority level for a problem
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum Priority {
    Low,
    #[default]
    Medium,
    High,
    Critical,
}

impl std::fmt::Display for Priority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Priority::Low => write!(f, "low"),
            Priority::Medium => write!(f, "medium"),
            Priority::High => write!(f, "high"),
            Priority::Critical => write!(f, "critical"),
        }
    }
}

impl std::str::FromStr for Priority {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "critical" => Ok(Priority::Critical),
            "high" => Ok(Priority::High),
            "medium" => Ok(Priority::Medium),
            "low" => Ok(Priority::Low),
            _ => Err(format!(
                "Invalid priority: '{}'. Use critical, high, medium, or low",
                s
            )),
        }
    }
}

/// Status of a problem
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum ProblemStatus {
    /// Problem identified, not yet being addressed
    #[default]
    Open,

    /// Actively working on solutions
    InProgress,

    /// A solution has been approved
    Solved,

    /// Problem was based on false premises or became irrelevant
    Dissolved,
}

impl std::fmt::Display for ProblemStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ProblemStatus::Open => write!(f, "open"),
            ProblemStatus::InProgress => write!(f, "in_progress"),
            ProblemStatus::Solved => write!(f, "solved"),
            ProblemStatus::Dissolved => write!(f, "dissolved"),
        }
    }
}

impl std::str::FromStr for ProblemStatus {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "open" => Ok(ProblemStatus::Open),
            "in_progress" | "inprogress" => Ok(ProblemStatus::InProgress),
            "solved" => Ok(ProblemStatus::Solved),
            "dissolved" => Ok(ProblemStatus::Dissolved),
            _ => Err(format!(
                "Unknown problem status: '{}'. Valid values: open, in_progress, solved, dissolved",
                s
            )),
        }
    }
}

impl Problem {
    /// Create a new problem
    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            id: id.into(),
            title: title.into(),
            parent_id: None,
            status: ProblemStatus::Open,
            priority: Priority::default(),
            confidence: Confidence::default(),
            solution_ids: Vec::new(),
            child_ids: Vec::new(),
            milestone_id: None,
            assignee: None,
            created_at: now,
            updated_at: now,
            description: String::new(),
            dissolved_reason: None,
            github_issue: None,
            tags: Vec::new(),
        }
    }

    /// Set parent problem (making this a sub-problem)
    pub fn set_parent(&mut self, parent_id: Option<String>) {
        self.parent_id = parent_id;
        self.updated_at = Utc::now();
    }

    /// Add a solution to this problem
    pub fn add_solution(&mut self, solution_id: impl Into<String>) {
        let solution_id = solution_id.into();
        if !self.solution_ids.contains(&solution_id) {
            self.solution_ids.push(solution_id);
            self.updated_at = Utc::now();
        }
    }

    /// Remove a solution from this problem
    pub fn remove_solution(&mut self, solution_id: &str) -> bool {
        if let Some(pos) = self.solution_ids.iter().position(|id| id == solution_id) {
            self.solution_ids.remove(pos);
            self.updated_at = Utc::now();
            true
        } else {
            false
        }
    }

    /// Add a child ID to the in-memory list.
    ///
    /// **Note:** `child_ids` is not persisted to disk — it is derived at read
    /// time in [`MetadataStore::list_problems`]. Calling this method has no
    /// lasting effect; use [`MetadataStore::list_subproblems`] to query children.
    pub fn add_child(&mut self, child_id: impl Into<String>) {
        let child_id = child_id.into();
        if !self.child_ids.contains(&child_id) {
            self.child_ids.push(child_id);
            self.updated_at = Utc::now();
        }
    }

    /// Remove a child ID from the in-memory list.
    ///
    /// **Note:** `child_ids` is not persisted to disk — it is derived at read
    /// time in [`MetadataStore::list_problems`]. Calling this method has no
    /// lasting effect; use [`MetadataStore::list_subproblems`] to query children.
    pub fn remove_child(&mut self, child_id: &str) -> bool {
        if let Some(pos) = self.child_ids.iter().position(|id| id == child_id) {
            self.child_ids.remove(pos);
            self.updated_at = Utc::now();
            true
        } else {
            false
        }
    }

    /// Set milestone
    pub fn set_milestone(&mut self, milestone_id: Option<String>) {
        self.milestone_id = milestone_id;
        self.updated_at = Utc::now();
    }

    /// Update status (unchecked). Prefer `try_set_status()` for validated transitions.
    pub(crate) fn set_status(&mut self, status: ProblemStatus) {
        self.status = status;
        self.updated_at = Utc::now();
    }

    /// Validate a status transition and apply it. Returns an error string if the transition is invalid.
    pub fn try_set_status(&mut self, status: ProblemStatus) -> Result<(), String> {
        if !self.can_transition_to(&status) {
            return Err(format!(
                "Invalid status transition: {} -> {}",
                self.status, status
            ));
        }
        self.set_status(status);
        Ok(())
    }

    /// Check if a status transition is valid.
    pub fn can_transition_to(&self, target: &ProblemStatus) -> bool {
        matches!(
            (&self.status, target),
            (ProblemStatus::Open, ProblemStatus::InProgress)
                | (ProblemStatus::Open, ProblemStatus::Solved)
                | (ProblemStatus::Open, ProblemStatus::Dissolved)
                | (ProblemStatus::InProgress, ProblemStatus::Solved)
                | (ProblemStatus::InProgress, ProblemStatus::Open)
                | (ProblemStatus::InProgress, ProblemStatus::Dissolved)
                | (ProblemStatus::Solved, ProblemStatus::Open)
                | (ProblemStatus::Dissolved, ProblemStatus::Open)
        )
    }

    /// Dissolve the problem with a reason
    pub fn dissolve(&mut self, reason: impl Into<String>) {
        self.status = ProblemStatus::Dissolved;
        self.dissolved_reason = Some(reason.into());
        self.updated_at = Utc::now();
    }

    /// Check if problem is open (can be worked on)
    pub fn is_open(&self) -> bool {
        matches!(self.status, ProblemStatus::Open | ProblemStatus::InProgress)
    }

    /// Check if problem is resolved (solved or dissolved)
    pub fn is_resolved(&self) -> bool {
        matches!(
            self.status,
            ProblemStatus::Solved | ProblemStatus::Dissolved
        )
    }

    /// Check if problem is in progress
    pub fn is_in_progress(&self) -> bool {
        self.status == ProblemStatus::InProgress
    }

    /// Check if this is a sub-problem (has a parent)
    pub fn is_subproblem(&self) -> bool {
        self.parent_id.is_some()
    }

    /// Check if this is a root problem (no parent)
    pub fn is_root(&self) -> bool {
        self.parent_id.is_none()
    }
}

/// YAML frontmatter for Problem markdown files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProblemFrontmatter {
    pub id: String,
    pub title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<String>,
    pub status: ProblemStatus,
    pub priority: Priority,
    #[serde(default, skip_serializing_if = "is_confidence_unknown")]
    pub confidence: Confidence,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub solution_ids: Vec<String>,
    #[serde(skip)]
    pub child_ids: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub milestone_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dissolved_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub github_issue: Option<u64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
}

impl From<&Problem> for ProblemFrontmatter {
    fn from(p: &Problem) -> Self {
        Self {
            id: p.id.clone(),
            title: p.title.clone(),
            parent_id: p.parent_id.clone(),
            status: p.status.clone(),
            priority: p.priority.clone(),
            confidence: p.confidence.clone(),
            solution_ids: p.solution_ids.clone(),
            child_ids: p.child_ids.clone(),
            milestone_id: p.milestone_id.clone(),
            assignee: p.assignee.clone(),
            created_at: p.created_at,
            updated_at: p.updated_at,
            dissolved_reason: p.dissolved_reason.clone(),
            github_issue: p.github_issue,
            tags: p.tags.clone(),
        }
    }
}

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

    #[test]
    fn test_create_problem() {
        let problem = Problem::new("P-1".to_string(), "User auth is unreliable".to_string());
        assert_eq!(problem.id, "P-1");
        assert_eq!(problem.title, "User auth is unreliable");
        assert_eq!(problem.status, ProblemStatus::Open);
        assert!(problem.is_root());
        assert!(problem.is_open());
        assert!(problem.tags.is_empty());
    }

    #[test]
    fn test_subproblem() {
        let mut problem = Problem::new("P-2".to_string(), "Token expiry handling".to_string());
        problem.set_parent(Some("P-1".to_string()));

        assert!(problem.is_subproblem());
        assert!(!problem.is_root());
        assert_eq!(problem.parent_id, Some("P-1".to_string()));
    }

    #[test]
    fn test_status_transitions() {
        let mut problem = Problem::new("P-1".to_string(), "Test".to_string());
        assert_eq!(problem.status, ProblemStatus::Open);
        assert!(problem.is_open());

        problem.set_status(ProblemStatus::InProgress);
        assert_eq!(problem.status, ProblemStatus::InProgress);
        assert!(problem.is_open());

        problem.set_status(ProblemStatus::Solved);
        assert_eq!(problem.status, ProblemStatus::Solved);
        assert!(problem.is_resolved());
    }

    #[test]
    fn test_add_solution() {
        let mut problem = Problem::new("P-1".to_string(), "Test".to_string());
        problem.add_solution("S-1".to_string());
        problem.add_solution("S-2".to_string());

        assert_eq!(problem.solution_ids.len(), 2);
        assert!(problem.solution_ids.contains(&"S-1".to_string()));
    }

    #[test]
    fn test_add_child() {
        let mut problem = Problem::new("P-1".to_string(), "Parent".to_string());
        problem.add_child("P-2".to_string());
        problem.add_child("P-3".to_string());

        assert_eq!(problem.child_ids.len(), 2);
        assert!(problem.child_ids.contains(&"P-2".to_string()));
    }

    #[test]
    fn test_status_parsing() {
        assert_eq!(
            "open".parse::<ProblemStatus>().unwrap(),
            ProblemStatus::Open
        );
        assert_eq!(
            "in_progress".parse::<ProblemStatus>().unwrap(),
            ProblemStatus::InProgress
        );
        assert_eq!(
            "solved".parse::<ProblemStatus>().unwrap(),
            ProblemStatus::Solved
        );
        assert_eq!(
            "dissolved".parse::<ProblemStatus>().unwrap(),
            ProblemStatus::Dissolved
        );
    }

    #[test]
    fn test_priority_from_str() {
        assert_eq!("critical".parse::<Priority>().unwrap(), Priority::Critical);
        assert_eq!("Critical".parse::<Priority>().unwrap(), Priority::Critical);
        assert_eq!("high".parse::<Priority>().unwrap(), Priority::High);
        assert_eq!("HIGH".parse::<Priority>().unwrap(), Priority::High);
        assert_eq!("medium".parse::<Priority>().unwrap(), Priority::Medium);
        assert_eq!("low".parse::<Priority>().unwrap(), Priority::Low);
        // Numeric codes are not accepted
        assert!("p0".parse::<Priority>().is_err());
        assert!("p1".parse::<Priority>().is_err());
        assert!("p2".parse::<Priority>().is_err());
        assert!("p3".parse::<Priority>().is_err());
    }

    #[test]
    fn test_priority_display() {
        assert_eq!(format!("{}", Priority::Critical), "critical");
        assert_eq!(format!("{}", Priority::High), "high");
        assert_eq!(format!("{}", Priority::Medium), "medium");
        assert_eq!(format!("{}", Priority::Low), "low");
    }

    #[test]
    fn test_priority_ordering() {
        assert!(Priority::Critical > Priority::High);
        assert!(Priority::High > Priority::Medium);
        assert!(Priority::Medium > Priority::Low);
    }

    #[test]
    fn test_problem_priority_default() {
        let p = Problem::new("P-1".to_string(), "Test".to_string());
        assert_eq!(p.priority, Priority::Medium);
    }

    #[test]
    fn test_dissolved_reason() {
        let mut p = Problem::new("P-1".to_string(), "Test".to_string());
        assert_eq!(p.dissolved_reason, None);
        p.dissolve("The data was correct; our test was wrong".to_string());
        assert_eq!(p.status, ProblemStatus::Dissolved);
        assert_eq!(
            p.dissolved_reason.as_deref(),
            Some("The data was correct; our test was wrong")
        );
    }

    #[test]
    fn test_problem_tags() {
        let mut p = Problem::new("P-1".to_string(), "Test".to_string());
        assert!(p.tags.is_empty());

        p.tags = vec![
            "backend".to_string(),
            "auth".to_string(),
            "size:L".to_string(),
        ];

        // Round-trip through frontmatter
        let fm = ProblemFrontmatter::from(&p);
        assert_eq!(
            fm.tags,
            vec![
                "backend".to_string(),
                "auth".to_string(),
                "size:L".to_string()
            ]
        );

        // Verify serde round-trip
        let yaml = serde_yml::to_string(&fm).unwrap();
        assert!(yaml.contains("tags:"));
        assert!(yaml.contains("backend"));

        let parsed: ProblemFrontmatter = serde_yml::from_str(&yaml).unwrap();
        assert_eq!(parsed.tags, p.tags);
    }

    #[test]
    fn test_problem_tags_serde_default() {
        // YAML without tags field should deserialize with empty vec
        let yaml = "id: P-1\ntitle: Test\nstatus: open\npriority: medium\nsolution_ids: []\ncreated_at: '2025-01-01T00:00:00Z'\nupdated_at: '2025-01-01T00:00:00Z'\n";
        let fm: ProblemFrontmatter = serde_yml::from_str(yaml).unwrap();
        assert!(fm.tags.is_empty());
    }
}