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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// A solution is a conjecture - a tentative attempt to solve a problem.
/// Solutions must face explicit criticism to survive or be withdrawn.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Solution {
    /// Unique solution identifier (e.g., "S-1")
    pub id: String,

    /// Solution title (what is the proposed approach?)
    pub title: String,

    /// Problem this solution attempts to solve (required)
    pub problem_id: String,

    /// Current status
    pub status: SolutionStatus,

    /// Critique IDs - critiques of this solution
    #[serde(default)]
    pub critique_ids: Vec<String>,

    /// Associated jj change IDs implementing this solution
    #[serde(default)]
    pub change_ids: Vec<String>,

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

    /// Force-approved without full sign-off
    #[serde(default, alias = "force_accepted")]
    pub force_approved: bool,

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

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

    /// Approach - how this solution addresses the problem (markdown body)
    #[serde(default)]
    pub approach: String,

    /// ID of the solution this one supersedes (for lineage tracking)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supersedes: Option<String>,

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

    /// GitHub branch name for this solution's PR
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub github_branch: Option<String>,

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

/// Status of a solution (conjecture)
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum SolutionStatus {
    /// Conjecture put forward, not yet submitted for review
    #[default]
    Proposed,

    /// Submitted for review — open for critique
    Submitted,

    /// Critique proved this won't work — withdrawn by author
    Withdrawn,

    /// Survived critique, approved and integrated
    Approved,
}

impl std::fmt::Display for SolutionStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SolutionStatus::Proposed => write!(f, "proposed"),
            SolutionStatus::Submitted => write!(f, "submitted"),
            SolutionStatus::Withdrawn => write!(f, "withdrawn"),
            SolutionStatus::Approved => write!(f, "approved"),
        }
    }
}

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

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "proposed" => Ok(SolutionStatus::Proposed),
            "submitted" => Ok(SolutionStatus::Submitted),
            "withdrawn" => Ok(SolutionStatus::Withdrawn),
            "approved" => Ok(SolutionStatus::Approved),
            _ => Err(format!(
                "Unknown solution status: '{}'. Valid values: proposed, submitted, withdrawn, approved",
                s
            )),
        }
    }
}

impl Solution {
    /// Create a new solution for a problem
    pub fn new(
        id: impl Into<String>,
        title: impl Into<String>,
        problem_id: impl Into<String>,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: id.into(),
            title: title.into(),
            problem_id: problem_id.into(),
            status: SolutionStatus::Proposed,
            critique_ids: Vec::new(),
            change_ids: Vec::new(),
            assignee: None,
            force_approved: false,
            created_at: now,
            updated_at: now,
            approach: String::new(),
            supersedes: None,
            github_pr: None,
            github_branch: None,
            tags: Vec::new(),
        }
    }

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

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

    /// Attach a jj change to this solution
    pub fn attach_change(&mut self, change_id: impl Into<String>) {
        let change_id = change_id.into();
        if !self.change_ids.contains(&change_id) {
            self.change_ids.push(change_id);
            self.updated_at = Utc::now();
        }
    }

    /// Detach a jj change from this solution
    pub fn detach_change(&mut self, change_id: &str) -> bool {
        if let Some(pos) = self.change_ids.iter().position(|id| id == change_id) {
            self.change_ids.remove(pos);
            self.updated_at = Utc::now();
            true
        } else {
            false
        }
    }

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

    /// Validate a status transition and apply it. Returns an error string if invalid.
    pub fn try_set_status(&mut self, status: SolutionStatus) -> 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: &SolutionStatus) -> bool {
        matches!(
            (&self.status, target),
            (SolutionStatus::Proposed, SolutionStatus::Submitted)
                | (SolutionStatus::Proposed, SolutionStatus::Withdrawn)
                | (SolutionStatus::Submitted, SolutionStatus::Approved)
                | (SolutionStatus::Submitted, SolutionStatus::Withdrawn)
                | (SolutionStatus::Submitted, SolutionStatus::Proposed)
                | (SolutionStatus::Withdrawn, SolutionStatus::Proposed)
        )
    }

    /// Check if solution is active (can be worked on)
    pub fn is_active(&self) -> bool {
        matches!(
            self.status,
            SolutionStatus::Proposed | SolutionStatus::Submitted
        )
    }

    /// Check if solution is finalized (approved or withdrawn)
    pub fn is_finalized(&self) -> bool {
        matches!(
            self.status,
            SolutionStatus::Approved | SolutionStatus::Withdrawn
        )
    }

    /// Check if solution is in proposed status
    pub fn is_proposed(&self) -> bool {
        self.status == SolutionStatus::Proposed
    }

    /// Check if solution has been submitted for review
    pub fn is_submitted(&self) -> bool {
        self.status == SolutionStatus::Submitted
    }

    /// Check if solution has been approved
    pub fn is_approved(&self) -> bool {
        self.status == SolutionStatus::Approved
    }

    /// Check if solution has been withdrawn
    pub fn is_withdrawn(&self) -> bool {
        self.status == SolutionStatus::Withdrawn
    }

    /// Submit solution for review. Returns error if transition is invalid.
    pub fn submit(&mut self) -> Result<(), String> {
        self.try_set_status(SolutionStatus::Submitted)
    }

    /// Approve the solution (survived critique). Returns error if transition is invalid.
    pub fn approve(&mut self) -> Result<(), String> {
        self.try_set_status(SolutionStatus::Approved)
    }

    /// Withdraw the solution. Returns error if transition is invalid.
    pub fn withdraw(&mut self) -> Result<(), String> {
        self.try_set_status(SolutionStatus::Withdrawn)
    }
}

/// YAML frontmatter for Solution markdown files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SolutionFrontmatter {
    pub id: String,
    pub title: String,
    pub problem_id: String,
    pub status: SolutionStatus,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub critique_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub change_ids: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
    #[serde(default, alias = "force_accepted")]
    pub force_approved: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supersedes: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub github_pr: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub github_branch: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl From<&Solution> for SolutionFrontmatter {
    fn from(s: &Solution) -> Self {
        Self {
            id: s.id.clone(),
            title: s.title.clone(),
            problem_id: s.problem_id.clone(),
            status: s.status.clone(),
            critique_ids: s.critique_ids.clone(),
            change_ids: s.change_ids.clone(),
            assignee: s.assignee.clone(),
            force_approved: s.force_approved,
            supersedes: s.supersedes.clone(),
            github_pr: s.github_pr,
            github_branch: s.github_branch.clone(),
            tags: s.tags.clone(),
            created_at: s.created_at,
            updated_at: s.updated_at,
        }
    }
}

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

    #[test]
    fn test_create_solution() {
        let solution = Solution::new(
            "S-1".to_string(),
            "Use JWT tokens".to_string(),
            "P-1".to_string(),
        );
        assert_eq!(solution.id, "S-1");
        assert_eq!(solution.title, "Use JWT tokens");
        assert_eq!(solution.problem_id, "P-1");
        assert_eq!(solution.status, SolutionStatus::Proposed);
        assert!(solution.is_active());
        assert!(solution.tags.is_empty());
    }

    #[test]
    fn test_status_transitions() {
        let mut solution = Solution::new("S-1".to_string(), "Test".to_string(), "P-1".to_string());

        assert_eq!(solution.status, SolutionStatus::Proposed);
        assert!(solution.is_active());

        solution.submit().unwrap();
        assert_eq!(solution.status, SolutionStatus::Submitted);
        assert!(solution.is_active());

        solution.approve().unwrap();
        assert_eq!(solution.status, SolutionStatus::Approved);
        assert!(solution.is_finalized());
    }

    #[test]
    fn test_withdrawal() {
        let mut solution = Solution::new("S-1".to_string(), "Test".to_string(), "P-1".to_string());

        solution.submit().unwrap();
        solution.withdraw().unwrap();

        assert_eq!(solution.status, SolutionStatus::Withdrawn);
        assert!(solution.is_finalized());
    }

    #[test]
    fn test_attach_change() {
        let mut solution = Solution::new("S-1".to_string(), "Test".to_string(), "P-1".to_string());

        solution.attach_change("kpqxywon".to_string());
        solution.attach_change("zmxptlnw".to_string());

        assert_eq!(solution.change_ids.len(), 2);
        assert!(solution.change_ids.contains(&"kpqxywon".to_string()));
    }

    #[test]
    fn test_add_critique() {
        let mut solution = Solution::new("S-1".to_string(), "Test".to_string(), "P-1".to_string());

        solution.add_critique("CQ-1".to_string());
        solution.add_critique("CQ-2".to_string());

        assert_eq!(solution.critique_ids.len(), 2);
        assert!(solution.critique_ids.contains(&"CQ-1".to_string()));
    }

    #[test]
    fn test_status_parsing() {
        assert_eq!(
            "proposed".parse::<SolutionStatus>().unwrap(),
            SolutionStatus::Proposed
        );
        assert_eq!(
            "submitted".parse::<SolutionStatus>().unwrap(),
            SolutionStatus::Submitted
        );
        assert_eq!(
            "withdrawn".parse::<SolutionStatus>().unwrap(),
            SolutionStatus::Withdrawn
        );
        assert_eq!(
            "approved".parse::<SolutionStatus>().unwrap(),
            SolutionStatus::Approved
        );
    }

    #[test]
    fn test_solution_supersedes() {
        let s = Solution::new(
            "S-2".to_string(),
            "Better approach".to_string(),
            "P-1".to_string(),
        );
        assert_eq!(s.supersedes, None);

        let mut s2 = s.clone();
        s2.supersedes = Some("S-1".to_string());
        assert_eq!(s2.supersedes.as_deref(), Some("S-1"));
    }

    #[test]
    fn test_solution_tags() {
        let mut s = Solution::new("S-1".to_string(), "Test".to_string(), "P-1".to_string());
        assert!(s.tags.is_empty());

        s.tags = vec!["refactor".to_string(), "backend".to_string()];

        let fm = SolutionFrontmatter::from(&s);
        assert_eq!(fm.tags, vec!["refactor".to_string(), "backend".to_string()]);

        let yaml = serde_yml::to_string(&fm).unwrap();
        assert!(yaml.contains("tags:"));
        assert!(yaml.contains("refactor"));

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