mc 0.1.11

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
use crate::error::{McError, McResult};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Operating mode for a MissionControl repository.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepoMode {
    /// Standalone repo where the entire directory is managed by mc.
    Standalone,
    /// Embedded `.mc/` folder inside an existing project.
    Embedded,
}

#[derive(Debug, Deserialize)]
pub struct RawConfig {
    pub paths: Option<HashMap<String, String>>,
    pub id_prefixes: Option<HashMap<String, String>>,
    pub statuses: Option<HashMap<String, Vec<String>>>,
    pub brand: Option<BrandConfig>,
}

#[derive(Debug, Deserialize)]
pub struct BrandConfig {
    pub name: Option<String>,
    pub tagline: Option<String>,
    pub fonts_dir: Option<String>,
    pub font_name: Option<String>,
    pub primary_color: Option<Vec<u8>>,
    pub accent_color: Option<Vec<u8>>,
    pub logo: Option<String>,
    pub custom_css: Option<String>,
}

/// Resolved configuration with absolute paths.
#[derive(Debug, Clone)]
pub struct ResolvedConfig {
    pub root: PathBuf,
    pub mode: RepoMode,
    pub customers_dir: PathBuf,
    pub projects_dir: PathBuf,
    pub meetings_dir: PathBuf,
    pub research_dir: PathBuf,
    pub tasks_dir: PathBuf,
    pub sprints_dir: PathBuf,
    pub proposals_dir: PathBuf,
    pub data_dir: PathBuf,
    pub templates_dir: PathBuf,
    pub archive_dir: PathBuf,
    pub id_prefixes: IdPrefixes,
    pub statuses: StatusConfig,
    pub brand: ResolvedBrand,
    /// Entity path keys explicitly set in config (e.g. "tasks", "research").
    /// If empty, all defaults apply (backwards compatible).
    pub configured_entities: std::collections::HashSet<String>,
}

/// Default primary color (blue).
pub const DEFAULT_PRIMARY: [u8; 3] = [0, 82, 155];
/// Default accent color (gray).
pub const DEFAULT_ACCENT: [u8; 3] = [102, 102, 102];

/// Resolved brand configuration with absolute paths and defaults applied.
#[derive(Debug, Clone)]
pub struct ResolvedBrand {
    pub name: String,
    pub tagline: String,
    pub fonts_dir: Option<PathBuf>,
    pub font_name: String,
    pub primary_color: [u8; 3],
    pub accent_color: [u8; 3],
    pub logo: Option<PathBuf>,
    pub custom_css: Option<PathBuf>,
}

#[derive(Debug, Clone)]
pub struct IdPrefixes {
    pub customer: String,
    pub project: String,
    pub meeting: String,
    pub research: String,
    pub task: String,
    pub sprint: String,
    pub proposal: String,
    pub contact: String,
}

#[derive(Debug, Clone)]
pub struct StatusConfig {
    pub customer: Vec<String>,
    pub project: Vec<String>,
    pub meeting: Vec<String>,
    pub research: Vec<String>,
    pub task: Vec<String>,
    pub sprint: Vec<String>,
    pub proposal: Vec<String>,
    pub contact: Vec<String>,
}

impl ResolvedConfig {
    /// Check if an entity kind is available in this config.
    /// In embedded mode, only task/meeting/research/sprint/proposal are available.
    /// In standalone mode, if `paths` is configured, only explicitly listed entity types
    /// are shown (plus their singular/plural variants). If no paths are configured,
    /// all entity types are available (backwards compatible).
    pub fn entity_available(&self, kind: &crate::entity::EntityKind) -> bool {
        use crate::entity::EntityKind;
        // Embedded mode filter
        if self.mode == RepoMode::Embedded {
            return matches!(
                kind,
                EntityKind::Task
                    | EntityKind::Meeting
                    | EntityKind::Research
                    | EntityKind::Sprint
                    | EntityKind::Proposal
            );
        }
        // Standalone: if no paths configured, show all (backwards compatible)
        if self.configured_entities.is_empty() {
            return true;
        }
        // Check if this entity's path key is in the configured set
        // Config uses plural keys (tasks, customers, etc.) or singular (task, customer)
        let plural = kind.label_plural();
        let singular = kind.label();
        if self.configured_entities.contains(plural) || self.configured_entities.contains(singular)
        {
            return true;
        }
        // Contacts are a sub-entity of customers — they don't have their own path key
        // but are available whenever customers are configured.
        if matches!(kind, EntityKind::Contact) {
            return self.configured_entities.contains("customers")
                || self.configured_entities.contains("customer");
        }
        false
    }
}

/// Walk up from `start` looking for a MissionControl config.
/// Checks `.mc/config.yml` (embedded) first, then `config/config.yml` (standalone).
pub fn find_repo_root(start: &Path) -> McResult<(PathBuf, RepoMode)> {
    let mut dir = start.to_path_buf();
    loop {
        if dir.join(".mc").join("config.yml").is_file() {
            return Ok((dir, RepoMode::Embedded));
        }
        if dir.join("config").join("config.yml").is_file() {
            return Ok((dir, RepoMode::Standalone));
        }
        if !dir.pop() {
            return Err(McError::RepoRootNotFound);
        }
    }
}

/// Detect the repo mode for an explicit root path.
pub fn detect_mode(root: &Path) -> RepoMode {
    if root.join(".mc").join("config.yml").is_file() {
        RepoMode::Embedded
    } else {
        RepoMode::Standalone
    }
}

/// Load and resolve configuration.
pub fn load_config(root: &Path, mode: RepoMode) -> McResult<ResolvedConfig> {
    let (config_path, base_dir) = match mode {
        RepoMode::Standalone => (root.join("config").join("config.yml"), root.to_path_buf()),
        RepoMode::Embedded => (root.join(".mc").join("config.yml"), root.join(".mc")),
    };

    if !config_path.is_file() {
        return Err(McError::ConfigNotFound(config_path));
    }

    let content = std::fs::read_to_string(&config_path)?;
    let raw: RawConfig =
        serde_yaml::from_str(&content).map_err(|e| McError::ConfigParse(e.to_string()))?;

    let raw_paths = raw.paths.unwrap_or_default();
    let configured_entities: std::collections::HashSet<String> =
        raw_paths.keys().cloned().collect();
    let paths = raw_paths;
    let prefixes = raw.id_prefixes.unwrap_or_default();
    let statuses = raw.statuses.unwrap_or_default();
    let raw_brand = raw.brand;

    let resolve = |key: &str, default: &str| -> PathBuf {
        base_dir.join(paths.get(key).map(|s| s.as_str()).unwrap_or(default))
    };

    let resolved = ResolvedConfig {
        root: root.to_path_buf(),
        mode,
        customers_dir: resolve("customers", "customers/"),
        projects_dir: resolve("projects", "projects/"),
        meetings_dir: resolve("meetings", "meetings/"),
        research_dir: resolve("research", "research/"),
        tasks_dir: resolve("tasks", "tasks/"),
        sprints_dir: resolve("sprints", "sprints/"),
        proposals_dir: resolve("proposals", "proposals/"),
        data_dir: resolve("data", "data/"),
        templates_dir: resolve("templates", "templates/"),
        archive_dir: resolve("archive", "archive/"),
        id_prefixes: IdPrefixes {
            customer: prefixes
                .get("customer")
                .cloned()
                .unwrap_or_else(|| "CUST".into()),
            project: prefixes
                .get("project")
                .cloned()
                .unwrap_or_else(|| "PROJ".into()),
            meeting: prefixes
                .get("meeting")
                .cloned()
                .unwrap_or_else(|| "MTG".into()),
            research: prefixes
                .get("research")
                .cloned()
                .unwrap_or_else(|| "RES".into()),
            task: prefixes
                .get("task")
                .cloned()
                .unwrap_or_else(|| "TASK".into()),
            sprint: prefixes
                .get("sprint")
                .cloned()
                .unwrap_or_else(|| "SPR".into()),
            proposal: prefixes
                .get("proposal")
                .cloned()
                .unwrap_or_else(|| "PROP".into()),
            contact: prefixes
                .get("contact")
                .cloned()
                .unwrap_or_else(|| "CONT".into()),
        },
        statuses: StatusConfig {
            customer: statuses
                .get("customer")
                .cloned()
                .unwrap_or_else(|| vec!["active".into(), "inactive".into()]),
            project: statuses
                .get("project")
                .cloned()
                .unwrap_or_else(|| vec!["active".into(), "on-hold".into(), "completed".into()]),
            meeting: statuses
                .get("meeting")
                .cloned()
                .unwrap_or_else(|| vec!["scheduled".into(), "completed".into()]),
            research: statuses
                .get("research")
                .cloned()
                .unwrap_or_else(|| vec!["draft".into(), "final".into()]),
            task: statuses.get("task").cloned().unwrap_or_else(|| {
                vec![
                    "backlog".into(),
                    "todo".into(),
                    "in-progress".into(),
                    "review".into(),
                    "done".into(),
                    "cancelled".into(),
                ]
            }),
            sprint: statuses.get("sprint").cloned().unwrap_or_else(|| {
                vec![
                    "planning".into(),
                    "active".into(),
                    "review".into(),
                    "completed".into(),
                    "cancelled".into(),
                ]
            }),
            proposal: statuses.get("proposal").cloned().unwrap_or_else(|| {
                vec![
                    "draft".into(),
                    "proposed".into(),
                    "accepted".into(),
                    "rejected".into(),
                    "superseded".into(),
                    "withdrawn".into(),
                ]
            }),
            contact: statuses
                .get("contact")
                .cloned()
                .unwrap_or_else(|| vec!["active".into(), "inactive".into()]),
        },
        brand: resolve_brand(&base_dir, raw_brand),
        configured_entities,
    };

    validate_status_config(&resolved.statuses)?;

    Ok(resolved)
}

fn validate_status_config(statuses: &StatusConfig) -> McResult<()> {
    let checks = [
        ("customer", &statuses.customer),
        ("project", &statuses.project),
        ("meeting", &statuses.meeting),
        ("research", &statuses.research),
        ("task", &statuses.task),
        ("sprint", &statuses.sprint),
        ("proposal", &statuses.proposal),
        ("contact", &statuses.contact),
    ];
    for (name, list) in checks {
        if list.is_empty() {
            return Err(McError::ConfigParse(format!(
                "statuses.{} must not be empty",
                name
            )));
        }
    }
    Ok(())
}

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

    fn default_statuses() -> StatusConfig {
        StatusConfig {
            customer: vec!["active".into()],
            project: vec!["active".into()],
            meeting: vec!["scheduled".into()],
            research: vec!["draft".into()],
            task: vec!["todo".into()],
            sprint: vec!["planning".into()],
            proposal: vec!["draft".into()],
            contact: vec!["active".into()],
        }
    }

    #[test]
    fn test_valid_statuses_pass() {
        assert!(validate_status_config(&default_statuses()).is_ok());
    }

    #[test]
    fn test_empty_customer_statuses_rejected() {
        let mut s = default_statuses();
        s.customer = vec![];
        let err = validate_status_config(&s).unwrap_err();
        assert!(err
            .to_string()
            .contains("statuses.customer must not be empty"));
    }

    #[test]
    fn test_empty_task_statuses_rejected() {
        let mut s = default_statuses();
        s.task = vec![];
        let err = validate_status_config(&s).unwrap_err();
        assert!(err.to_string().contains("statuses.task must not be empty"));
    }
}

fn resolve_brand(root: &Path, raw: Option<BrandConfig>) -> ResolvedBrand {
    let color_from_vec = |v: &[u8], default: [u8; 3]| -> [u8; 3] {
        if v.len() >= 3 {
            [v[0], v[1], v[2]]
        } else {
            default
        }
    };

    match raw {
        Some(b) => {
            let fonts_dir = b.fonts_dir.map(|p| root.join(p)).filter(|p| p.is_dir());
            let logo = b.logo.map(|p| root.join(p)).filter(|p| p.is_file());
            let custom_css = b.custom_css.map(|p| root.join(p)).filter(|p| p.is_file());
            ResolvedBrand {
                name: b.name.unwrap_or_else(|| "MissionControl".into()),
                tagline: b.tagline.unwrap_or_default(),
                fonts_dir,
                font_name: b.font_name.unwrap_or_else(|| "LiberationSans".into()),
                primary_color: b
                    .primary_color
                    .as_deref()
                    .map(|v| color_from_vec(v, DEFAULT_PRIMARY))
                    .unwrap_or(DEFAULT_PRIMARY),
                accent_color: b
                    .accent_color
                    .as_deref()
                    .map(|v| color_from_vec(v, DEFAULT_ACCENT))
                    .unwrap_or(DEFAULT_ACCENT),
                logo,
                custom_css,
            }
        }
        None => ResolvedBrand {
            name: "MissionControl".into(),
            tagline: String::new(),
            fonts_dir: None,
            font_name: "LiberationSans".into(),
            primary_color: DEFAULT_PRIMARY,
            accent_color: DEFAULT_ACCENT,
            logo: None,
            custom_css: None,
        },
    }
}