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
use crate::error::{JjjError, Result};
use crate::jj::JjClient;
use crate::models::{Event, ProblemStatus, ProjectConfig, SolutionStatus};
use std::cell::RefCell;
use std::fs;
use std::path::PathBuf;

mod critiques;
mod events;
mod milestones;
mod problems;
mod solutions;

/// Write `content` to `path` atomically by writing to a uniquely-named `.tmp`
/// sibling first, then renaming. The temp name includes the process ID and
/// sub-second nanoseconds so concurrent writers cannot clobber each other's
/// temp file.
pub(super) fn atomic_write(path: &std::path::Path, content: &[u8]) -> std::io::Result<()> {
    use std::time::{SystemTime, UNIX_EPOCH};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    let tmp = path.with_extension(format!("md.{}.{}.tmp", std::process::id(), nanos));
    std::fs::write(&tmp, content)?;
    std::fs::rename(&tmp, path)?;
    Ok(())
}

pub const META_BOOKMARK: &str = "jjj";
pub(super) const CONFIG_FILE: &str = "config.toml";
pub(super) const PROBLEMS_DIR: &str = "problems";
pub(super) const SOLUTIONS_DIR: &str = "solutions";
pub(super) const CRITIQUES_DIR: &str = "critiques";
pub(super) const MILESTONES_DIR: &str = "milestones";

/// The core storage abstraction for jjj metadata.
///
/// Manages reading/writing Problems, Solutions, Critiques, and Milestones as
/// markdown files in `.jj/jjj-meta/`. Events are appended to `events.jsonl`.
///
/// The metadata lives entirely outside the working copy — operations here never
/// touch the user's working changes. Sync (push/fetch) is handled separately
/// and only requires a configured sync backend.
pub struct MetadataStore {
    /// Path to the metadata directory (.jj/jjj-meta/)
    meta_path: PathBuf,

    /// Path to the events log file (.jj/jjj-meta/events.jsonl)
    events_path: PathBuf,

    /// JJ client for interacting with the repository
    pub jj_client: JjClient,

    /// Events to append to events.jsonl on the next flush
    pending_events: RefCell<Vec<Event>>,
}

/// Load the global user config from ~/.config/jjj/config.toml.
fn load_global_config() -> ProjectConfig {
    let config_dir = global_config_dir().join("config.toml");
    if !config_dir.exists() {
        return ProjectConfig::default();
    }
    std::fs::read_to_string(&config_dir)
        .ok()
        .and_then(|s| toml::from_str(&s).ok())
        .unwrap_or_default()
}

/// Get the global jjj config directory (~/.config/jjj/).
fn global_config_dir() -> std::path::PathBuf {
    if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
        return std::path::PathBuf::from(xdg).join("jjj");
    }
    if let Some(home) = std::env::var_os("HOME") {
        return std::path::PathBuf::from(home).join(".config").join("jjj");
    }
    std::path::PathBuf::from(".config").join("jjj")
}

/// Merge project config on top of global config.
fn merge_config(base: &mut ProjectConfig, project: &ProjectConfig) {
    if project.name.is_some() {
        base.name = project.name.clone();
    }
    if !project.default_reviewers.is_empty() {
        base.default_reviewers = project.default_reviewers.clone();
    }
    if !project.settings.is_empty() {
        base.settings.extend(project.settings.clone());
    }
    base.github = project.github.clone();
    if project.sync.fetch.is_some() {
        base.sync.fetch = project.sync.fetch.clone();
    }
    if project.sync.push.is_some() {
        base.sync.push = project.sync.push.clone();
    }
    if project.sync.track.is_some() {
        base.sync.track = project.sync.track.clone();
    }
    if project.sync.workspace.is_some() {
        base.sync.workspace = project.sync.workspace.clone();
    }
    if !project.automation.is_empty() {
        base.automation = project.automation.clone();
    }
}

// =============================================================================
// Markdown Frontmatter Parsing
// =============================================================================

/// Parse YAML frontmatter from markdown content
fn parse_frontmatter<T: serde::de::DeserializeOwned>(content: &str) -> Result<(T, String)> {
    let content = content.trim();

    // Check for frontmatter delimiter
    if !content.starts_with("---") {
        return Err(JjjError::FrontmatterParse {
            entity_type: String::new(),
            entity_id: String::new(),
            message: "File must start with YAML frontmatter (---)".to_string(),
        });
    }

    // Find the closing delimiter
    let rest = &content[3..];
    let end_pos = rest
        .find("\n---")
        .ok_or_else(|| JjjError::FrontmatterParse {
            entity_type: String::new(),
            entity_id: String::new(),
            message: "Missing closing frontmatter delimiter".to_string(),
        })?;

    let yaml_str = &rest[..end_pos].trim();
    let body = rest[end_pos + 4..].trim().to_string();

    let frontmatter: T = serde_yml::from_str(yaml_str).map_err(|e| JjjError::FrontmatterParse {
        entity_type: String::new(),
        entity_id: String::new(),
        message: e.to_string(),
    })?;

    Ok((frontmatter, body))
}

/// Add entity context to a FrontmatterParse error
fn add_frontmatter_context(err: JjjError, entity_type: &str, entity_id: &str) -> JjjError {
    match err {
        JjjError::FrontmatterParse { message, .. } => JjjError::FrontmatterParse {
            entity_type: entity_type.to_string(),
            entity_id: entity_id.to_string(),
            message,
        },
        other => other,
    }
}

/// Serialize entity to markdown with YAML frontmatter
fn to_markdown<T: serde::Serialize>(frontmatter: &T, body: &str) -> Result<String> {
    let yaml = serde_yml::to_string(frontmatter)?;
    Ok(format!("---\n{}---\n\n{}", yaml, body))
}

impl MetadataStore {
    /// Create a new metadata store
    pub fn new(jj_client: JjClient) -> Result<Self> {
        let repo_root = jj_client.repo_root().to_path_buf();
        let meta_path = repo_root.join(".jj").join("jjj-meta");
        let events_path = meta_path.join("events.jsonl");

        let store = Self {
            meta_path,
            events_path,
            jj_client,
            pending_events: RefCell::new(Vec::new()),
        };

        store.maybe_migrate();

        Ok(store)
    }

    /// Get the path to the metadata directory
    pub fn meta_path(&self) -> &std::path::Path {
        &self.meta_path
    }

    /// Migrate events from old commit-based storage to events.jsonl.
    fn maybe_migrate(&self) {
        if self.events_path.exists() {
            return;
        }
        let meta_jj = self.meta_path.join(".jj");
        if !meta_jj.exists() {
            return;
        }
        let meta_client = match JjClient::with_root(self.meta_path.clone()) {
            Ok(c) => c,
            Err(_) => return,
        };
        let descriptions = match meta_client.log_descriptions("::@") {
            Ok(d) => d,
            Err(_) => return,
        };
        let events: Vec<Event> = descriptions
            .iter()
            .flat_map(|d| {
                d.lines()
                    .filter(|l| l.starts_with("jjj: "))
                    .filter_map(|l| serde_json::from_str(&l["jjj: ".len()..]).ok())
            })
            .collect();
        if events.is_empty() {
            return;
        }
        use std::io::Write;
        if let Ok(mut file) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.events_path)
        {
            for event in &events {
                if let Ok(line) = event.to_json_line() {
                    let _ = writeln!(file, "{}", line);
                }
            }
            eprintln!(
                "Migrated {} events from commit history to events.jsonl",
                events.len()
            );
        }
    }

    /// Initialize the metadata store (create directory structure)
    pub fn init(&self) -> Result<()> {
        if self.meta_path.join(CONFIG_FILE).exists() {
            return Err(crate::error::JjjError::Validation(
                "jjj is already initialized".to_string(),
            ));
        }
        self.ensure_meta_dirs()?;
        let default_config = ProjectConfig::default();
        self.save_config(&default_config)?;
        Ok(())
    }

    /// Ensure the metadata directory structure exists.
    pub(super) fn ensure_meta_dirs(&self) -> Result<()> {
        fs::create_dir_all(self.meta_path.join(PROBLEMS_DIR))?;
        fs::create_dir_all(self.meta_path.join(SOLUTIONS_DIR))?;
        fs::create_dir_all(self.meta_path.join(CRITIQUES_DIR))?;
        fs::create_dir_all(self.meta_path.join(MILESTONES_DIR))?;
        Ok(())
    }

    pub(super) fn ensure_meta_checkout(&self) -> Result<()> {
        self.ensure_meta_dirs()
    }

    // =========================================================================
    // Config Operations
    // =========================================================================

    /// Load project configuration, merging with global config.
    ///
    /// Load order (later overrides earlier):
    /// 1. `~/.config/jjj/config.toml` (global user defaults)
    /// 2. `.jj/jjj-meta/config.toml` (project-specific)
    pub fn load_config(&self) -> Result<ProjectConfig> {
        self.ensure_meta_checkout()?;

        let mut config = load_global_config();

        let config_path = self.meta_path.join(CONFIG_FILE);
        if config_path.exists() {
            let content = fs::read_to_string(config_path)?;
            let project: ProjectConfig = toml::from_str(&content)?;
            merge_config(&mut config, &project);
        }

        Ok(config)
    }

    /// Save project configuration
    pub fn save_config(&self, config: &ProjectConfig) -> Result<()> {
        self.ensure_meta_checkout()?;

        let config_path = self.meta_path.join(CONFIG_FILE);
        let content = toml::to_string_pretty(config)?;
        atomic_write(&config_path, content.as_bytes())?;

        Ok(())
    }

    // =========================================================================
    // High-Level Operations
    // =========================================================================

    /// Check whether a problem can transition to `Solved` status.
    ///
    /// A problem is solvable if:
    /// 1. It has at least one `Approved` solution, **or**
    /// 2. All of its direct subproblems are `Solved`.
    ///
    /// Returns `(can_solve, reason)` where `reason` is non-empty when `can_solve`
    /// is `false` (explaining the blocker) or when it is `true` via subproblem path
    /// (confirming all subproblems are solved). Returns an error if the problem
    /// cannot be found.
    pub fn can_solve_problem(&self, problem_id: &str) -> Result<(bool, String)> {
        let problem = self.load_problem(problem_id)?;

        // Check if already solved
        if problem.status == ProblemStatus::Solved {
            return Ok((false, "Problem is already solved".to_string()));
        }

        // Check for approved solutions
        let solutions = self.list_solutions_for_problem(problem_id)?;
        let has_approved = solutions
            .iter()
            .any(|s| s.status == SolutionStatus::Approved);

        if has_approved {
            return Ok((true, String::new()));
        }

        // Check if all subproblems are solved
        let subproblems = self.list_subproblems(problem_id)?;
        if !subproblems.is_empty() {
            let all_solved = subproblems
                .iter()
                .all(|p| p.status == ProblemStatus::Solved);
            if all_solved {
                return Ok((true, "All subproblems are solved".to_string()));
            }
            return Ok((
                false,
                "Not all subproblems are solved and no approved solution exists".to_string(),
            ));
        }

        Ok((false, "No approved solution exists".to_string()))
    }

    /// Determine whether a solution is eligible for `Approved` status.
    ///
    /// A solution can be approved if:
    /// 1. It is not already in a finalized state (`Approved` or `Withdrawn`), **and**
    /// 2. It has no `Valid` critiques (validated critiques block approval).
    ///
    /// Open critiques do not block approval but produce a warning in the returned
    /// message. Returns `(can_approve, message)` where `message` may describe
    /// blockers or warnings.
    pub fn can_approve_solution(&self, solution_id: &str) -> Result<(bool, String)> {
        let solution = self.load_solution(solution_id)?;

        // Check if already finalized
        if solution.is_finalized() {
            return Ok((false, format!("Solution is already {:?}", solution.status)));
        }

        // Check for valid critiques
        if self.has_valid_critiques(solution_id)? {
            return Ok((
                false,
                "Solution has valid critiques that block approval".to_string(),
            ));
        }

        // Check for open critiques (warning but not blocking)
        let open_critiques = self.list_open_critiques_for_solution(solution_id)?;
        if !open_critiques.is_empty() {
            return Ok((
                true,
                format!(
                    "Warning: {} open critique(s) remain unaddressed",
                    open_critiques.len()
                ),
            ));
        }

        Ok((true, String::new()))
    }

    // =========================================================================
    // Commit Operations
    // =========================================================================

    /// Flush pending events to events.jsonl.
    pub fn commit_changes(&self, _message: &str) -> Result<()> {
        use std::io::Write;

        let mut pending = self.pending_events.borrow_mut();
        if pending.is_empty() {
            return Ok(());
        }

        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.events_path)
            .map_err(JjjError::Io)?;

        for event in pending.drain(..) {
            match event.to_json_line() {
                Ok(line) => {
                    if let Err(e) = writeln!(file, "{}", line) {
                        eprintln!("Warning: failed to write event: {}", e);
                    }
                }
                Err(err) => {
                    eprintln!("Warning: failed to serialize event: {}", err);
                }
            }
        }

        Ok(())
    }

    /// Execute an operation on the metadata store and flush events.
    ///
    /// This is the primary mechanism for all metadata writes. The `operation`
    /// closure runs first; if it succeeds, any events queued via
    /// [`set_pending_event`](MetadataStore::set_pending_event) are appended
    /// to `events.jsonl`.
    ///
    /// If `operation` returns an error, no events are flushed.
    pub fn with_metadata<F, R>(&self, message: &str, operation: F) -> Result<R>
    where
        F: FnOnce() -> Result<R>,
    {
        let result = operation()?;
        self.commit_changes(message)?;
        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{Confidence, Priority, ProblemFrontmatter};
    use chrono::Utc;

    #[test]
    fn test_parse_frontmatter() {
        let content = r#"---
id: p1
title: Test Problem
status: open
priority: medium
created_at: 2024-01-15T10:30:00Z
updated_at: 2024-01-15T10:30:00Z
---

## Description

This is a test problem.

## Context

Some context here.
"#;

        let (frontmatter, body): (ProblemFrontmatter, String) = parse_frontmatter(content).unwrap();
        assert_eq!(frontmatter.id, "p1");
        assert_eq!(frontmatter.title, "Test Problem");
        assert!(body.contains("## Description"));
    }

    #[test]
    fn test_to_markdown() {
        let frontmatter = ProblemFrontmatter {
            id: "p1".to_string(),
            title: "Test".to_string(),
            parent_id: None,
            status: ProblemStatus::Open,
            priority: Priority::default(),
            confidence: Confidence::default(),
            solution_ids: vec![],
            child_ids: vec![],
            milestone_id: None,
            assignee: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
            dissolved_reason: None,
            github_issue: None,
            tags: vec![],
        };

        let body = "Test description\n";
        let result = to_markdown(&frontmatter, body).unwrap();

        assert!(result.starts_with("---\n"));
        assert!(result.contains("id: p1"));
        assert!(result.contains("Test description"));
    }

    #[test]
    fn test_critique_frontmatter_with_reviewer() {
        use crate::models::{Critique, CritiqueFrontmatter};

        let mut critique = Critique::new(
            "c1".to_string(),
            "Awaiting review".to_string(),
            "s1".to_string(),
        );
        critique.reviewer = Some("bob".to_string());

        let frontmatter = CritiqueFrontmatter::from(&critique);
        let body = format!("{}\n", critique.argument);

        let markdown = to_markdown(&frontmatter, &body).unwrap();
        assert!(markdown.contains("reviewer: bob"));
    }
}