routa-core 0.19.0

Routa.js core domain — models, stores, protocols, and JSON-RPC (transport-agnostic)
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
use serde::{Deserialize, Serialize};

use super::kanban::KanbanColumnAutomation;

const VALID_STAGES: &[&str] = &["backlog", "todo", "dev", "review", "blocked", "done"];
const VALID_TRANSITION_TYPES: &[&str] = &["entry", "exit", "both"];
const VALID_GATE_MODES: &[&str] = &["blocking", "warning"];
const VALID_ARTIFACTS: &[&str] = &["screenshot", "test_results", "code_diff"];
const VALID_REQUIRED_TASK_FIELDS: &[&str] = &[
    "scope",
    "acceptance_criteria",
    "verification_commands",
    "test_cases",
    "verification_plan",
    "dependencies_declared",
];

/// Top-level YAML config for declarative Kanban setup.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KanbanConfig {
    pub version: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default = "default_workspace_id")]
    pub workspace_id: String,
    pub boards: Vec<KanbanBoardConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KanbanBoardConfig {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub is_default: bool,
    pub columns: Vec<KanbanColumnConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct KanbanColumnConfig {
    pub id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    pub stage: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub automation: Option<KanbanColumnAutomation>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visible: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub width: Option<String>,
}

fn default_workspace_id() -> String {
    "default".to_string()
}

impl KanbanConfig {
    pub fn from_yaml(yaml: &str) -> Result<Self, String> {
        serde_yaml::from_str(yaml).map_err(|e| format!("Failed to parse YAML: {e}"))
    }

    pub fn from_file(path: &str) -> Result<Self, String> {
        let content =
            std::fs::read_to_string(path).map_err(|e| format!("Failed to read '{path}': {e}"))?;
        Self::from_yaml(&content)
    }

    pub fn to_yaml(&self) -> Result<String, String> {
        serde_yaml::to_string(self).map_err(|e| format!("Failed to serialize YAML: {e}"))
    }

    /// Validate the config. Returns a list of all errors found.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.version != 1 {
            errors.push(format!("unsupported version: {}, expected 1", self.version));
        }

        if self.boards.is_empty() {
            errors.push("boards list is empty".to_string());
        }

        let mut seen_board_ids = std::collections::HashSet::new();
        for (bi, board) in self.boards.iter().enumerate() {
            let prefix = format!("boards[{bi}]");

            if board.id.trim().is_empty() {
                errors.push(format!("{prefix}.id is blank"));
            } else if !seen_board_ids.insert(&board.id) {
                errors.push(format!("{prefix}.id '{}' is duplicated", board.id));
            }

            if board.name.trim().is_empty() {
                errors.push(format!("{prefix}.name is blank"));
            }

            if board.columns.is_empty() {
                errors.push(format!("{prefix}.columns is empty"));
            }

            let mut seen_col_ids = std::collections::HashSet::new();
            for (ci, col) in board.columns.iter().enumerate() {
                let col_prefix = format!("{prefix}.columns[{ci}]");

                if col.id.trim().is_empty() {
                    errors.push(format!("{col_prefix}.id is blank"));
                } else if !seen_col_ids.insert(&col.id) {
                    errors.push(format!("{col_prefix}.id '{}' is duplicated", col.id));
                }

                if col.name.trim().is_empty() {
                    errors.push(format!("{col_prefix}.name is blank"));
                }

                if !VALID_STAGES.contains(&col.stage.as_str()) {
                    errors.push(format!(
                        "{col_prefix}.stage '{}' is invalid, expected one of: {}",
                        col.stage,
                        VALID_STAGES.join(", ")
                    ));
                }

                if let Some(auto) = &col.automation {
                    let auto_prefix = format!("{col_prefix}.automation");
                    if let Some(tt) = &auto.transition_type {
                        if !VALID_TRANSITION_TYPES.contains(&tt.as_str()) {
                            errors.push(format!(
                                "{auto_prefix}.transitionType '{}' is invalid, expected one of: {}",
                                tt,
                                VALID_TRANSITION_TYPES.join(", ")
                            ));
                        }
                    }
                    if let Some(mode) = &auto.gate_mode {
                        let mode = match mode {
                            super::kanban::KanbanTransitionGateMode::Blocking => "blocking",
                            super::kanban::KanbanTransitionGateMode::Warning => "warning",
                        };
                        if !VALID_GATE_MODES.contains(&mode) {
                            errors.push(format!(
                                "{auto_prefix}.gateMode '{mode}' is invalid, expected one of: {}",
                                VALID_GATE_MODES.join(", ")
                            ));
                        }
                    }
                    if let Some(artifacts) = &auto.required_artifacts {
                        for art in artifacts {
                            if !VALID_ARTIFACTS.contains(&art.as_str()) {
                                errors.push(format!(
                                    "{auto_prefix}.requiredArtifacts contains invalid value '{}', expected one of: {}",
                                    art,
                                    VALID_ARTIFACTS.join(", ")
                                ));
                            }
                        }
                    }
                    if let Some(required_task_fields) = &auto.required_task_fields {
                        for field in required_task_fields {
                            if !VALID_REQUIRED_TASK_FIELDS.contains(&field.as_str()) {
                                errors.push(format!(
                                    "{auto_prefix}.requiredTaskFields contains invalid value '{}', expected one of: {}",
                                    field,
                                    VALID_REQUIRED_TASK_FIELDS.join(", ")
                                ));
                            }
                        }
                    }
                    if let Some(checklist) = &auto.required_checklist {
                        for item in checklist {
                            if item.trim().is_empty() {
                                errors.push(format!(
                                    "{auto_prefix}.requiredChecklist contains a blank item"
                                ));
                            }
                        }
                    }
                    if let Some(command) = &auto.validator_command {
                        if command.trim().is_empty() {
                            errors.push(format!("{auto_prefix}.validatorCommand is blank"));
                        }
                    }
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

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

    #[test]
    fn parse_minimal_config() {
        let yaml = r#"
version: 1
workspaceId: default
boards:
  - id: main
    name: Main Board
    columns:
      - id: backlog
        name: Backlog
        stage: backlog
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        assert_eq!(config.version, 1);
        assert_eq!(config.boards.len(), 1);
        assert_eq!(config.boards[0].columns.len(), 1);
        assert!(config.validate().is_ok());
    }

    #[test]
    fn parse_full_config_with_automation() {
        let yaml = r#"
version: 1
name: project-kanban
workspaceId: ws-1
boards:
  - id: core
    name: Core Board
    isDefault: true
    columns:
      - id: backlog
        name: Backlog
        color: slate
        stage: backlog
      - id: dev
        name: Dev
        color: amber
        stage: dev
        automation:
          enabled: true
          providerId: routa-native
          role: CRAFTER
          transitionType: entry
          requiredArtifacts:
            - test_results
            - code_diff
          requiredTaskFields:
            - scope
            - verification_plan
          requiredChecklist:
            - browser smoke
          requiredHumanApproval: true
          validatorCommand: npm test
          gateMode: warning
          autoAdvanceOnSuccess: false
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        assert_eq!(config.boards[0].columns.len(), 2);
        let auto = config.boards[0].columns[1].automation.as_ref().unwrap();
        assert!(auto.enabled);
        assert_eq!(auto.provider_id.as_deref(), Some("routa-native"));
        assert_eq!(auto.required_artifacts.as_ref().unwrap().len(), 2);
        assert_eq!(auto.required_task_fields.as_ref().unwrap().len(), 2);
        assert_eq!(
            auto.required_checklist.as_ref().unwrap(),
            &vec!["browser smoke".to_string()]
        );
        assert_eq!(auto.required_human_approval, Some(true));
        assert_eq!(auto.validator_command.as_deref(), Some("npm test"));
        assert_eq!(
            auto.gate_mode,
            Some(super::super::kanban::KanbanTransitionGateMode::Warning)
        );
        assert!(config.validate().is_ok());
    }

    #[test]
    fn validate_rejects_invalid_stage() {
        let yaml = r#"
version: 1
boards:
  - id: b1
    name: Board
    columns:
      - id: c1
        name: Col
        stage: invalid_stage
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        let errs = config.validate().unwrap_err();
        assert!(errs
            .iter()
            .any(|e| e.contains("stage 'invalid_stage' is invalid")));
    }

    #[test]
    fn validate_rejects_duplicate_board_ids() {
        let yaml = r#"
version: 1
boards:
  - id: same
    name: Board A
    columns:
      - id: c1
        name: Col
        stage: backlog
  - id: same
    name: Board B
    columns:
      - id: c1
        name: Col
        stage: backlog
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        let errs = config.validate().unwrap_err();
        assert!(errs.iter().any(|e| e.contains("'same' is duplicated")));
    }

    #[test]
    fn validate_rejects_duplicate_column_ids() {
        let yaml = r#"
version: 1
boards:
  - id: b1
    name: Board
    columns:
      - id: dup
        name: Col A
        stage: backlog
      - id: dup
        name: Col B
        stage: todo
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        let errs = config.validate().unwrap_err();
        assert!(errs.iter().any(|e| e.contains("'dup' is duplicated")));
    }

    #[test]
    fn validate_rejects_invalid_transition_type() {
        let yaml = r#"
version: 1
boards:
  - id: b1
    name: Board
    columns:
      - id: c1
        name: Col
        stage: dev
        automation:
          enabled: true
          transitionType: invalid
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        let errs = config.validate().unwrap_err();
        assert!(errs
            .iter()
            .any(|e| e.contains("transitionType 'invalid' is invalid")));
    }

    #[test]
    fn validate_rejects_invalid_artifacts() {
        let yaml = r#"
version: 1
boards:
  - id: b1
    name: Board
    columns:
      - id: c1
        name: Col
        stage: dev
        automation:
          enabled: true
          requiredArtifacts:
            - bad_artifact
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        let errs = config.validate().unwrap_err();
        assert!(errs.iter().any(|e| e.contains("'bad_artifact'")));
    }

    #[test]
    fn validate_rejects_invalid_required_task_fields() {
        let yaml = r#"
version: 1
boards:
  - id: b1
    name: Board
    columns:
      - id: c1
        name: Col
        stage: dev
        automation:
          enabled: true
          requiredTaskFields:
            - bad_field
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        let errs = config.validate().unwrap_err();
        assert!(errs.iter().any(|e| e.contains("'bad_field'")));
    }

    #[test]
    fn roundtrip_yaml() {
        let yaml = r#"
version: 1
name: roundtrip-test
workspaceId: default
boards:
  - id: core
    name: Core Board
    isDefault: true
    columns:
      - id: backlog
        name: Backlog
        color: slate
        stage: backlog
      - id: dev
        name: Dev
        color: amber
        stage: dev
        automation:
          enabled: true
          transitionType: entry
          requiredArtifacts:
            - test_results
"#;
        let config = KanbanConfig::from_yaml(yaml).unwrap();
        assert!(config.validate().is_ok());

        let serialized = config.to_yaml().unwrap();
        let reparsed = KanbanConfig::from_yaml(&serialized).unwrap();
        assert!(reparsed.validate().is_ok());

        assert_eq!(config.boards.len(), reparsed.boards.len());
        assert_eq!(config.boards[0].id, reparsed.boards[0].id);
        assert_eq!(config.boards[0].columns, reparsed.boards[0].columns);
    }
}