mc 0.1.13

Git-based knowledge management CLI — manage customers, projects, meetings, research and tasks with Markdown + YAML frontmatter
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
use crate::config::{RepoMode, ResolvedConfig};
use crate::data;
use crate::entity::{self, EntityKind};
use crate::error::{McError, McResult};
use crate::frontmatter;
use colored::*;
use regex::Regex;
use serde::Serialize;
use std::path::Path;
use walkdir::WalkDir;

#[derive(Serialize)]
pub struct ValidationIssue {
    pub path: String,
    pub check: String,
    pub message: String,
}

pub fn run(cfg: &ResolvedConfig) -> McResult<()> {
    println!("{} Validating repo...\n", "".blue());

    let issues = validate_programmatic(cfg)?;

    if issues.is_empty() {
        println!("{} All checks passed!", "".green().bold());
        Ok(())
    } else {
        println!("{} {} issue(s) found:\n", "".red().bold(), issues.len());
        for (i, issue) in issues.iter().enumerate() {
            println!(
                "  {}. [{}] {}\n     {}",
                (i + 1).to_string().red(),
                issue.check.yellow(),
                issue.path.dimmed(),
                issue.message
            );
        }
        Err(McError::ValidationFailed(issues.len()))
    }
}

/// Run validation and return structured issues without printing.
pub fn validate_programmatic(cfg: &ResolvedConfig) -> McResult<Vec<ValidationIssue>> {
    let mut issues: Vec<ValidationIssue> = Vec::new();

    if cfg.mode == RepoMode::Standalone {
        validate_entity_dirs(EntityKind::Customer, cfg, &mut issues)?;
        validate_entity_dirs(EntityKind::Project, cfg, &mut issues)?;
        validate_contacts(cfg, &mut issues)?;
    }
    validate_meetings(cfg, &mut issues)?;
    validate_entity_dirs(EntityKind::Research, cfg, &mut issues)?;
    validate_entity_dirs(EntityKind::Sprint, cfg, &mut issues)?;
    validate_proposals(cfg, &mut issues)?;
    validate_tasks(cfg, &mut issues)?;

    Ok(issues)
}

fn validate_entity_dirs(
    kind: EntityKind,
    cfg: &ResolvedConfig,
    issues: &mut Vec<ValidationIssue>,
) -> McResult<()> {
    let base = kind.base_dir(cfg);
    let prefix = kind.prefix(cfg);

    if !base.is_dir() {
        return Ok(());
    }

    // Check folder naming: PREFIX-NNN-slug
    let dir_re = Regex::new(&format!(
        r"^{}-\d{{3}}-[a-z0-9]+(-[a-z0-9]+)*$",
        regex::escape(prefix)
    ))
    .expect("regex with escaped prefix is always valid");

    // Regex to extract entity ID from directory name (e.g. "CUST-001" from "CUST-001-acme")
    let id_re = Regex::new(&format!(r"^({}-\d+)", regex::escape(prefix)))
        .expect("regex with escaped prefix is always valid");

    for entry in std::fs::read_dir(base)? {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let dir_name = entry.file_name().to_string_lossy().to_string();

        // Check 1: folder naming regex
        if !dir_re.is_match(&dir_name) {
            issues.push(ValidationIssue {
                path: dir_name.clone(),
                check: "folder-naming".into(),
                message: format!(
                    "Directory name does not match expected pattern: {}-NNN-slug",
                    prefix
                ),
            });
        }

        // Check for ID-based filename (e.g. CUST-001.md), falling back to legacy names
        let index_file = if let Some(caps) = id_re.captures(&dir_name) {
            let id_file = entry.path().join(format!("{}.md", &caps[1]));
            if id_file.is_file() {
                id_file
            } else {
                // Backward compat: try legacy filenames
                match kind {
                    EntityKind::Project => entry.path().join("overview.md"),
                    _ => entry.path().join("_index.md"),
                }
            }
        } else {
            match kind {
                EntityKind::Project => entry.path().join("overview.md"),
                _ => entry.path().join("_index.md"),
            }
        };

        if !index_file.is_file() {
            issues.push(ValidationIssue {
                path: index_file.display().to_string(),
                check: "missing-index".into(),
                message: "Required index file not found".into(),
            });
            continue;
        }

        // Validate frontmatter
        validate_frontmatter_file(&index_file, kind, prefix, cfg, issues);
    }

    Ok(())
}

fn validate_meetings(cfg: &ResolvedConfig, issues: &mut Vec<ValidationIssue>) -> McResult<()> {
    let base = &cfg.meetings_dir;
    if !base.is_dir() {
        return Ok(());
    }

    let filename_re =
        Regex::new(r"^\d{4}-\d{2}-\d{2}-.+\.md$").expect("static regex pattern is always valid");

    for entry in WalkDir::new(base)
        .max_depth(1)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.is_dir() || path.extension().is_none_or(|e| e != "md") {
            continue;
        }

        let Some(fname) = path.file_name() else {
            continue;
        };
        let filename = fname.to_string_lossy().to_string();

        // Check meeting filename pattern
        if !filename_re.is_match(&filename) {
            issues.push(ValidationIssue {
                path: filename.clone(),
                check: "meeting-filename".into(),
                message: "Meeting filename does not match YYYY-MM-DD-slug.md pattern".into(),
            });
        }

        validate_frontmatter_file(
            path,
            EntityKind::Meeting,
            &cfg.id_prefixes.meeting,
            cfg,
            issues,
        );
    }

    Ok(())
}

fn validate_proposals(cfg: &ResolvedConfig, issues: &mut Vec<ValidationIssue>) -> McResult<()> {
    let base = &cfg.proposals_dir;
    if !base.is_dir() {
        return Ok(());
    }

    let prefix = &cfg.id_prefixes.proposal;
    let filename_re = Regex::new(&format!(
        r"^{}-\d{{3}}-[a-z0-9]+(-[a-z0-9]+)*\.md$",
        regex::escape(prefix)
    ))
    .expect("regex with escaped prefix is always valid");

    for entry in WalkDir::new(base)
        .max_depth(1)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.is_dir() || path.extension().is_none_or(|e| e != "md") {
            continue;
        }

        let Some(fname) = path.file_name() else {
            continue;
        };
        let filename = fname.to_string_lossy().to_string();

        if !filename_re.is_match(&filename) {
            issues.push(ValidationIssue {
                path: filename.clone(),
                check: "proposal-filename".into(),
                message: format!(
                    "Proposal filename does not match {}-NNN-slug.md pattern",
                    prefix
                ),
            });
        }

        validate_frontmatter_file(path, EntityKind::Proposal, prefix, cfg, issues);
    }

    Ok(())
}

/// Validate all task files across all locations.
fn validate_tasks(cfg: &ResolvedConfig, issues: &mut Vec<ValidationIssue>) -> McResult<()> {
    let locations = entity::collect_all_task_dirs(cfg);
    let prefix = &cfg.id_prefixes.task;
    let filename_re = Regex::new(&format!(
        r"^{}-\d{{3}}-[a-z0-9]+(-[a-z0-9]+)*\.md$",
        regex::escape(prefix)
    ))
    .expect("regex with escaped prefix is always valid");

    let active_statuses = ["backlog", "todo", "in-progress", "review"];
    let finished_statuses = ["done", "cancelled"];

    for loc in &locations {
        if !loc.tasks_dir.is_dir() {
            continue;
        }

        // Check that only todo/ and done/ subfolders exist
        if let Ok(entries) = std::fs::read_dir(&loc.tasks_dir) {
            for entry in entries.filter_map(|e| e.ok()) {
                if entry.file_type().is_ok_and(|ft| ft.is_dir()) {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if name != "todo" && name != "done" {
                        issues.push(ValidationIssue {
                            path: entry.path().display().to_string(),
                            check: "task-subfolder".into(),
                            message: format!(
                                "Unexpected subfolder '{}' in tasks directory (expected only 'todo' and 'done')",
                                name
                            ),
                        });
                    }
                }
            }
        }

        for (subfolder, expected_statuses) in &[
            ("todo", active_statuses.as_slice()),
            ("done", finished_statuses.as_slice()),
        ] {
            let dir = loc.tasks_dir.join(subfolder);
            if !dir.is_dir() {
                continue;
            }

            if let Ok(entries) = std::fs::read_dir(&dir) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let path = entry.path();
                    if path.extension().is_none_or(|e| e != "md") {
                        continue;
                    }

                    let Some(fname) = path.file_name() else {
                        continue;
                    };
                    let filename = fname.to_string_lossy().to_string();

                    // Check filename pattern
                    if !filename_re.is_match(&filename) {
                        issues.push(ValidationIssue {
                            path: path.display().to_string(),
                            check: "task-filename".into(),
                            message: format!(
                                "Task filename does not match {}-NNN-slug.md pattern",
                                prefix
                            ),
                        });
                    }

                    // Validate frontmatter
                    validate_task_frontmatter_file(&path, prefix, cfg, expected_statuses, issues);
                }
            }
        }
    }

    Ok(())
}

/// Validate all contact files across customer directories.
fn validate_contacts(cfg: &ResolvedConfig, issues: &mut Vec<ValidationIssue>) -> McResult<()> {
    let locations = entity::collect_all_contact_dirs(cfg);
    let prefix = &cfg.id_prefixes.contact;
    let filename_re = Regex::new(&format!(
        r"^{}-\d{{3}}-[a-z0-9]+(-[a-z0-9]+)*\.md$",
        regex::escape(prefix)
    ))
    .expect("regex with escaped prefix is always valid");

    for loc in &locations {
        if !loc.contacts_dir.is_dir() {
            continue;
        }
        if let Ok(entries) = std::fs::read_dir(&loc.contacts_dir) {
            for entry in entries.filter_map(|e| e.ok()) {
                let path = entry.path();
                if path.extension().is_none_or(|e| e != "md") {
                    continue;
                }

                let Some(fname) = path.file_name() else {
                    continue;
                };
                let filename = fname.to_string_lossy().to_string();

                if !filename_re.is_match(&filename) {
                    issues.push(ValidationIssue {
                        path: path.display().to_string(),
                        check: "contact-filename".into(),
                        message: format!(
                            "Contact filename does not match {}-NNN-slug.md pattern",
                            prefix
                        ),
                    });
                }

                validate_frontmatter_file(&path, EntityKind::Contact, prefix, cfg, issues);
            }
        }
    }

    Ok(())
}

fn validate_task_frontmatter_file(
    path: &Path,
    prefix: &str,
    cfg: &ResolvedConfig,
    expected_statuses: &[&str],
    issues: &mut Vec<ValidationIssue>,
) {
    let path_str = path.display().to_string();

    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(_) => {
            issues.push(ValidationIssue {
                path: path_str,
                check: "read-error".into(),
                message: "Could not read file".into(),
            });
            return;
        }
    };

    let (fm_str, _body) = match frontmatter::split_frontmatter(&content) {
        Some(parts) => parts,
        None => {
            issues.push(ValidationIssue {
                path: path_str,
                check: "frontmatter-presence".into(),
                message: "No YAML frontmatter found".into(),
            });
            return;
        }
    };

    let fm = match frontmatter::parse_raw(&fm_str, path) {
        Ok(v) => v,
        Err(_) => {
            issues.push(ValidationIssue {
                path: path_str,
                check: "yaml-validity".into(),
                message: "Invalid YAML in frontmatter".into(),
            });
            return;
        }
    };

    // Required: id
    let id = match frontmatter::get_str(&fm, "id") {
        Some(id) => id.to_string(),
        None => {
            issues.push(ValidationIssue {
                path: path_str,
                check: "required-fields".into(),
                message: "Missing required 'id' field".into(),
            });
            return;
        }
    };

    if !id.starts_with(&format!("{}-", prefix)) {
        issues.push(ValidationIssue {
            path: path_str.clone(),
            check: "id-consistency".into(),
            message: format!(
                "ID '{}' does not start with expected prefix '{}-'",
                id, prefix
            ),
        });
    }

    // Required: title
    if frontmatter::get_str(&fm, "title").is_none() {
        issues.push(ValidationIssue {
            path: path_str.clone(),
            check: "required-fields".into(),
            message: "Missing required 'title' field".into(),
        });
    }

    // Status validity
    if let Some(status) = frontmatter::get_str(&fm, "status") {
        let valid_statuses = EntityKind::Task.statuses(cfg);
        if !valid_statuses.iter().any(|s| s == status) {
            issues.push(ValidationIssue {
                path: path_str.clone(),
                check: "status-validity".into(),
                message: format!(
                    "Invalid status '{}', expected one of: {}",
                    status,
                    valid_statuses.join(", ")
                ),
            });
        }

        // Folder↔status sync check
        if !expected_statuses.contains(&status) {
            let folder = if expected_statuses.contains(&"backlog") {
                "todo"
            } else {
                "done"
            };
            issues.push(ValidationIssue {
                path: path_str.clone(),
                check: "folder-status-sync".into(),
                message: format!(
                    "Task with status '{}' is in '{}/' folder but should be in '{}'",
                    status,
                    folder,
                    if folder == "todo" { "done/" } else { "todo/" }
                ),
            });
        }
    }

    // Priority validity (1-4)
    if let Some(priority) = data::get_number(&fm, "priority") {
        if !(1..=4).contains(&priority) {
            issues.push(ValidationIssue {
                path: path_str.clone(),
                check: "priority-range".into(),
                message: format!(
                    "Priority {} is out of range (expected 1-4: 1=critical, 2=high, 3=medium, 4=low)",
                    priority
                ),
            });
        }
    }
}

fn validate_frontmatter_file(
    path: &Path,
    kind: EntityKind,
    prefix: &str,
    cfg: &ResolvedConfig,
    issues: &mut Vec<ValidationIssue>,
) {
    let path_str = path.display().to_string();

    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(_) => {
            issues.push(ValidationIssue {
                path: path_str,
                check: "read-error".into(),
                message: "Could not read file".into(),
            });
            return;
        }
    };

    // Check 2: frontmatter presence
    let (fm_str, _body) = match frontmatter::split_frontmatter(&content) {
        Some(parts) => parts,
        None => {
            issues.push(ValidationIssue {
                path: path_str,
                check: "frontmatter-presence".into(),
                message: "No YAML frontmatter found".into(),
            });
            return;
        }
    };

    // Check 3: YAML validity
    let fm = match frontmatter::parse_raw(&fm_str, path) {
        Ok(v) => v,
        Err(_) => {
            issues.push(ValidationIssue {
                path: path_str,
                check: "yaml-validity".into(),
                message: "Invalid YAML in frontmatter".into(),
            });
            return;
        }
    };

    // Check 4: required 'id' field
    let id = match frontmatter::get_str(&fm, "id") {
        Some(id) => id.to_string(),
        None => {
            issues.push(ValidationIssue {
                path: path_str,
                check: "required-fields".into(),
                message: "Missing required 'id' field".into(),
            });
            return;
        }
    };

    // Check 5: ID starts with correct prefix
    if !id.starts_with(&format!("{}-", prefix)) {
        issues.push(ValidationIssue {
            path: path_str.clone(),
            check: "id-consistency".into(),
            message: format!(
                "ID '{}' does not start with expected prefix '{}-'",
                id, prefix
            ),
        });
    }

    // Check 6: required name/title field
    let has_name = match kind {
        EntityKind::Customer | EntityKind::Project | EntityKind::Contact => {
            frontmatter::get_str(&fm, "name").is_some()
        }
        EntityKind::Meeting
        | EntityKind::Research
        | EntityKind::Task
        | EntityKind::Sprint
        | EntityKind::Proposal => frontmatter::get_str(&fm, "title").is_some(),
    };
    if !has_name {
        let field = match kind {
            EntityKind::Customer | EntityKind::Project | EntityKind::Contact => "name",
            _ => "title",
        };
        issues.push(ValidationIssue {
            path: path_str.clone(),
            check: "required-fields".into(),
            message: format!("Missing required '{}' field", field),
        });
    }

    // Check 7: status validity
    if let Some(status) = frontmatter::get_str(&fm, "status") {
        let valid_statuses = kind.statuses(cfg);
        if !valid_statuses.iter().any(|s| s == status) {
            issues.push(ValidationIssue {
                path: path_str.clone(),
                check: "status-validity".into(),
                message: format!(
                    "Invalid status '{}', expected one of: {}",
                    status,
                    valid_statuses.join(", ")
                ),
            });
        }
    }

    // Check 8: slug consistency (for directory-based entities)
    if kind != EntityKind::Meeting
        && kind != EntityKind::Task
        && kind != EntityKind::Sprint
        && kind != EntityKind::Proposal
        && kind != EntityKind::Contact
    {
        if let Some(slug) = frontmatter::get_str(&fm, "slug") {
            // Check that the parent directory contains the slug
            if let Some(parent) = path.parent() {
                let dir_name = parent.file_name().unwrap_or_default().to_string_lossy();
                if !dir_name.contains(slug) {
                    issues.push(ValidationIssue {
                        path: path_str,
                        check: "slug-consistency".into(),
                        message: format!(
                            "Slug '{}' does not match directory name '{}'",
                            slug, dir_name
                        ),
                    });
                }
            }
        }
    }
}