planspec-core 0.1.0

Core types and validation for PlanSpec declarative work orchestration
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
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
//! Validation for PlanSpec resources.

mod schemas;

use jsonschema::JSONSchema;
use serde_json::Value;

use crate::types::plan::{Graph, GraphError, Plan};
use crate::Resource;

/// Validator for PlanSpec resources.
pub struct Validator {
    goal_schema: JSONSchema,
    plan_schema: JSONSchema,
    capability_schema: JSONSchema,
    binding_schema: JSONSchema,
    execution_schema: JSONSchema,
    gate_schema: JSONSchema,
}

impl Validator {
    /// Create a new validator with embedded schemas.
    pub fn new() -> Result<Self, ValidationError> {
        Ok(Self {
            goal_schema: compile_schema(schemas::GOAL_SCHEMA)?,
            plan_schema: compile_schema(schemas::PLAN_SCHEMA)?,
            capability_schema: compile_schema(schemas::CAPABILITY_SCHEMA)?,
            binding_schema: compile_schema(schemas::BINDING_SCHEMA)?,
            execution_schema: compile_schema(schemas::EXECUTION_SCHEMA)?,
            gate_schema: compile_schema(schemas::GATE_SCHEMA)?,
        })
    }

    /// Validate a resource.
    pub fn validate(&self, resource: &Resource) -> Result<(), Vec<ValidationError>> {
        let value = serde_json::to_value(resource)
            .map_err(|e| vec![ValidationError::SerializationError(e.to_string())])?;

        self.validate_json(&value)?;

        // Additional validation for Plans
        if let Resource::Plan(plan) = resource {
            self.validate_plan_graph(plan)?;
        }

        Ok(())
    }

    /// Validate a JSON value as a resource.
    pub fn validate_json(&self, value: &Value) -> Result<(), Vec<ValidationError>> {
        let kind = value
            .get("kind")
            .and_then(|k| k.as_str())
            .ok_or_else(|| vec![ValidationError::MissingKind])?;

        let schema = match kind {
            "Goal" => &self.goal_schema,
            "Plan" => &self.plan_schema,
            "Capability" => &self.capability_schema,
            "Binding" => &self.binding_schema,
            "Execution" => &self.execution_schema,
            "Gate" => &self.gate_schema,
            _ => return Err(vec![ValidationError::UnknownKind(kind.to_string())]),
        };

        let result = schema.validate(value);

        if let Err(errors) = result {
            let error_list: Vec<ValidationError> = errors
                .map(|e| {
                    let path = e.instance_path.to_string();
                    let path_str = if path.is_empty() {
                        "(root)".to_string()
                    } else {
                        path
                    };
                    ValidationError::SchemaValidation {
                        path: path_str,
                        message: e.to_string(),
                    }
                })
                .collect();

            if error_list.is_empty() {
                Ok(())
            } else {
                Err(error_list)
            }
        } else {
            // Validate naming conventions
            self.validate_naming_conventions(value)?;

            // For Goals, validate labelSelector semantics
            if kind == "Goal" {
                self.validate_label_selector(value)?;
            }

            // For Plans, also check for cycles, node IDs, series/version, and node kinds
            if kind == "Plan" {
                self.validate_plan_graph_json(value)?;
                self.validate_plan_node_ids(value)?;
                self.validate_plan_series_version(value)?;
                self.validate_plan_node_kinds(value)?;
            }
            Ok(())
        }
    }

    /// Validate naming conventions for metadata.name and metadata.namespace.
    fn validate_naming_conventions(&self, value: &Value) -> Result<(), Vec<ValidationError>> {
        let metadata = value.get("metadata");

        if let Some(meta) = metadata {
            // Validate name
            if let Some(name) = meta.get("name").and_then(|n| n.as_str()) {
                if !is_valid_dns_label(name) {
                    return Err(vec![ValidationError::InvalidName {
                        field: "metadata.name".to_string(),
                        value: name.to_string(),
                    }]);
                }
            }

            // Validate namespace
            if let Some(namespace) = meta.get("namespace").and_then(|n| n.as_str()) {
                if !is_valid_dns_label(namespace) {
                    return Err(vec![ValidationError::InvalidName {
                        field: "metadata.namespace".to_string(),
                        value: namespace.to_string(),
                    }]);
                }
            }
        }

        Ok(())
    }

    /// Validate labelSelector semantics (In/NotIn require values, Exists/DoesNotExist forbid values).
    fn validate_label_selector(&self, value: &Value) -> Result<(), Vec<ValidationError>> {
        let expressions = value
            .get("spec")
            .and_then(|s| s.get("planSelector"))
            .and_then(|ps| ps.get("matchExpressions"))
            .and_then(|me| me.as_array());

        if let Some(expressions) = expressions {
            for (i, expr) in expressions.iter().enumerate() {
                let operator = expr.get("operator").and_then(|o| o.as_str()).unwrap_or("");
                let has_values = expr
                    .get("values")
                    .and_then(|v| v.as_array())
                    .map(|arr| !arr.is_empty())
                    .unwrap_or(false);

                match operator {
                    "In" | "NotIn" => {
                        if !has_values {
                            return Err(vec![ValidationError::SchemaValidation {
                                path: format!("/spec/planSelector/matchExpressions/{}", i),
                                message: format!(
                                    "operator '{}' requires non-empty 'values' array",
                                    operator
                                ),
                            }]);
                        }
                    }
                    "Exists" | "DoesNotExist" => {
                        if has_values {
                            return Err(vec![ValidationError::SchemaValidation {
                                path: format!("/spec/planSelector/matchExpressions/{}", i),
                                message: format!(
                                    "operator '{}' must not have 'values' array",
                                    operator
                                ),
                            }]);
                        }
                    }
                    _ => {}
                }
            }
        }

        Ok(())
    }

    /// Validate Plan node IDs follow naming conventions.
    fn validate_plan_node_ids(&self, value: &Value) -> Result<(), Vec<ValidationError>> {
        let nodes = value
            .get("spec")
            .and_then(|s| s.get("graph"))
            .and_then(|g| g.get("nodes"))
            .and_then(|n| n.as_array());

        if let Some(nodes) = nodes {
            for node in nodes {
                if let Some(id) = node.get("id").and_then(|i| i.as_str()) {
                    if !is_valid_node_id(id) {
                        return Err(vec![ValidationError::InvalidName {
                            field: "spec.graph.nodes[].id".to_string(),
                            value: id.to_string(),
                        }]);
                    }
                }
            }
        }

        Ok(())
    }

    /// Validate Plan series/version co-dependency (both must be present or both absent).
    fn validate_plan_series_version(&self, value: &Value) -> Result<(), Vec<ValidationError>> {
        let spec = value.get("spec");
        if let Some(spec) = spec {
            let has_series = spec.get("series").and_then(|s| s.as_str()).is_some();
            let has_version = spec.get("version").and_then(|v| v.as_str()).is_some();

            match (has_series, has_version) {
                (true, false) => {
                    return Err(vec![ValidationError::SchemaValidation {
                        path: "/spec".to_string(),
                        message: "'series' requires 'version' to also be specified".to_string(),
                    }]);
                }
                (false, true) => {
                    return Err(vec![ValidationError::SchemaValidation {
                        path: "/spec".to_string(),
                        message: "'version' requires 'series' to also be specified".to_string(),
                    }]);
                }
                _ => {}
            }
        }
        Ok(())
    }

    /// Validate kind-specific node constraints.
    fn validate_plan_node_kinds(&self, value: &Value) -> Result<(), Vec<ValidationError>> {
        let nodes = value
            .get("spec")
            .and_then(|s| s.get("graph"))
            .and_then(|g| g.get("nodes"))
            .and_then(|n| n.as_array());

        if let Some(nodes) = nodes {
            for (i, node) in nodes.iter().enumerate() {
                let kind = node.get("kind").and_then(|k| k.as_str()).unwrap_or("");
                let default_id = format!("index {}", i);
                let node_id = node
                    .get("id")
                    .and_then(|id| id.as_str())
                    .unwrap_or(&default_id);

                match kind {
                    "Gate" => {
                        // Gate nodes require gateRef
                        if node.get("gateRef").is_none() {
                            return Err(vec![ValidationError::SchemaValidation {
                                path: format!("/spec/graph/nodes/{}", i),
                                message: format!(
                                    "Gate node '{}' requires 'gateRef' field",
                                    node_id
                                ),
                            }]);
                        }
                    }
                    "Group" => {
                        // Group nodes require non-empty children
                        let children = node.get("children").and_then(|c| c.as_array());
                        match children {
                            None => {
                                return Err(vec![ValidationError::SchemaValidation {
                                    path: format!("/spec/graph/nodes/{}", i),
                                    message: format!(
                                        "Group node '{}' requires 'children' field",
                                        node_id
                                    ),
                                }]);
                            }
                            Some(c) if c.is_empty() => {
                                return Err(vec![ValidationError::SchemaValidation {
                                    path: format!("/spec/graph/nodes/{}", i),
                                    message: format!(
                                        "Group node '{}' requires at least one child",
                                        node_id
                                    ),
                                }]);
                            }
                            _ => {}
                        }
                    }
                    "External" => {
                        // External nodes require externalRef
                        if node.get("externalRef").is_none() {
                            return Err(vec![ValidationError::SchemaValidation {
                                path: format!("/spec/graph/nodes/{}", i),
                                message: format!(
                                    "External node '{}' requires 'externalRef' field",
                                    node_id
                                ),
                            }]);
                        }
                    }
                    _ => {} // Task nodes have no required fields beyond id/kind
                }
            }
        }

        Ok(())
    }

    /// Validate a Plan's graph for cycles and other constraints.
    fn validate_plan_graph(&self, plan: &Plan) -> Result<(), Vec<ValidationError>> {
        if let Some(cycle_node) = plan.spec.graph.detect_cycle() {
            return Err(vec![ValidationError::CyclicGraph {
                node_id: cycle_node,
            }]);
        }

        // Validate that edge references exist
        self.validate_edge_references(&plan.spec.graph)?;

        Ok(())
    }

    /// Validate a Plan's graph from JSON.
    fn validate_plan_graph_json(&self, value: &Value) -> Result<(), Vec<ValidationError>> {
        let graph = value.get("spec").and_then(|s| s.get("graph"));

        if let Some(graph_value) = graph {
            let nodes = graph_value
                .get("nodes")
                .and_then(|n| n.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|n| n.get("id").and_then(|id| id.as_str()))
                        .collect::<std::collections::HashSet<_>>()
                })
                .unwrap_or_default();

            let empty_edges = vec![];
            let edges = graph_value
                .get("edges")
                .and_then(|e| e.as_array())
                .unwrap_or(&empty_edges);

            // Check for invalid edge references
            for edge in edges {
                let from = edge.get("from").and_then(|f| f.as_str()).unwrap_or("");
                let to = edge.get("to").and_then(|t| t.as_str()).unwrap_or("");

                if !nodes.contains(from) {
                    return Err(vec![ValidationError::InvalidEdgeReference {
                        edge_field: "from".to_string(),
                        node_id: from.to_string(),
                    }]);
                }
                if !nodes.contains(to) {
                    return Err(vec![ValidationError::InvalidEdgeReference {
                        edge_field: "to".to_string(),
                        node_id: to.to_string(),
                    }]);
                }
            }

            // Check for cycles using DFS
            let mut adj: std::collections::HashMap<&str, Vec<&str>> =
                std::collections::HashMap::new();
            for node_id in &nodes {
                adj.entry(node_id).or_default();
            }
            for edge in edges {
                let from = edge.get("from").and_then(|f| f.as_str()).unwrap_or("");
                let to = edge.get("to").and_then(|t| t.as_str()).unwrap_or("");
                adj.entry(from).or_default().push(to);
            }

            let mut visited = std::collections::HashSet::new();
            let mut rec_stack = std::collections::HashSet::new();

            for node_id in &nodes {
                if let Some(cycle) = detect_cycle_dfs(node_id, &adj, &mut visited, &mut rec_stack) {
                    return Err(vec![ValidationError::CyclicGraph { node_id: cycle }]);
                }
            }
        }

        Ok(())
    }

    /// Validate that all edge references point to existing nodes.
    fn validate_edge_references(&self, graph: &Graph) -> Result<(), Vec<ValidationError>> {
        let node_ids: std::collections::HashSet<&str> =
            graph.nodes.iter().map(|n| n.id.as_str()).collect();

        for edge in &graph.edges {
            if !node_ids.contains(edge.from.as_str()) {
                return Err(vec![ValidationError::InvalidEdgeReference {
                    edge_field: "from".to_string(),
                    node_id: edge.from.clone(),
                }]);
            }
            if !node_ids.contains(edge.to.as_str()) {
                return Err(vec![ValidationError::InvalidEdgeReference {
                    edge_field: "to".to_string(),
                    node_id: edge.to.clone(),
                }]);
            }
        }

        Ok(())
    }
}

fn detect_cycle_dfs<'a>(
    node: &'a str,
    adj: &std::collections::HashMap<&str, Vec<&'a str>>,
    visited: &mut std::collections::HashSet<&'a str>,
    rec_stack: &mut std::collections::HashSet<&'a str>,
) -> Option<String> {
    if rec_stack.contains(node) {
        return Some(node.to_string());
    }
    if visited.contains(node) {
        return None;
    }

    visited.insert(node);
    rec_stack.insert(node);

    if let Some(neighbors) = adj.get(node) {
        for neighbor in neighbors {
            if let Some(cycle) = detect_cycle_dfs(neighbor, adj, visited, rec_stack) {
                return Some(cycle);
            }
        }
    }

    rec_stack.remove(node);
    None
}

fn compile_schema(schema_json: &str) -> Result<JSONSchema, ValidationError> {
    let schema: Value = serde_json::from_str(schema_json).map_err(|e| {
        ValidationError::SchemaCompilationError(format!("Failed to parse schema: {}", e))
    })?;

    JSONSchema::compile(&schema).map_err(|e| {
        ValidationError::SchemaCompilationError(format!("Failed to compile schema: {}", e))
    })
}

/// Check if a string is a valid DNS label (Kubernetes naming convention).
/// Must be lowercase, start with a letter, contain only letters, numbers, and hyphens.
/// Maximum 63 characters.
fn is_valid_dns_label(s: &str) -> bool {
    if s.is_empty() || s.len() > 63 {
        return false;
    }

    let mut chars = s.chars().peekable();

    // Must start with a lowercase letter
    match chars.next() {
        Some(c) if c.is_ascii_lowercase() => {}
        _ => return false,
    }

    // Rest must be lowercase letters, digits, or hyphens
    for c in chars {
        if !c.is_ascii_lowercase() && !c.is_ascii_digit() && c != '-' {
            return false;
        }
    }

    // Must not end with a hyphen
    if s.ends_with('-') {
        return false;
    }

    true
}

/// Check if a string is a valid node ID.
/// Similar to DNS labels but slightly more permissive - allows underscores.
fn is_valid_node_id(s: &str) -> bool {
    if s.is_empty() || s.len() > 63 {
        return false;
    }

    let mut chars = s.chars().peekable();

    // Must start with a lowercase letter
    match chars.next() {
        Some(c) if c.is_ascii_lowercase() => {}
        _ => return false,
    }

    // Rest must be lowercase letters, digits, hyphens, or underscores
    for c in chars {
        if !c.is_ascii_lowercase() && !c.is_ascii_digit() && c != '-' && c != '_' {
            return false;
        }
    }

    true
}

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

    #[test]
    fn test_valid_dns_labels() {
        assert!(is_valid_dns_label("my-goal"));
        assert!(is_valid_dns_label("planspec"));
        assert!(is_valid_dns_label("test-123"));
        assert!(is_valid_dns_label("a"));
        assert!(is_valid_dns_label("abc123"));
    }

    #[test]
    fn test_invalid_dns_labels() {
        assert!(!is_valid_dns_label("")); // empty
        assert!(!is_valid_dns_label("My-Goal")); // uppercase
        assert!(!is_valid_dns_label("123-test")); // starts with number
        assert!(!is_valid_dns_label("-test")); // starts with hyphen
        assert!(!is_valid_dns_label("test-")); // ends with hyphen
        assert!(!is_valid_dns_label("test_name")); // underscore not allowed
        assert!(!is_valid_dns_label("test.name")); // dot not allowed
    }

    #[test]
    fn test_valid_node_ids() {
        assert!(is_valid_node_id("step-1"));
        assert!(is_valid_node_id("my_task"));
        assert!(is_valid_node_id("schema-and-conventions"));
        assert!(is_valid_node_id("v0-ready"));
    }

    #[test]
    fn test_invalid_node_ids() {
        assert!(!is_valid_node_id("")); // empty
        assert!(!is_valid_node_id("Step-1")); // uppercase
        assert!(!is_valid_node_id("1-step")); // starts with number
        assert!(!is_valid_node_id("step.one")); // dot not allowed
    }
}

/// Error during validation.
#[derive(Debug, Clone, thiserror::Error)]
pub enum ValidationError {
    /// Missing kind field.
    #[error("missing 'kind' field")]
    MissingKind,

    /// Unknown resource kind.
    #[error("unknown resource kind: {0}")]
    UnknownKind(String),

    /// Schema validation failed.
    #[error("validation failed at {path}: {message}")]
    SchemaValidation { path: String, message: String },

    /// Schema compilation error.
    #[error("schema compilation error: {0}")]
    SchemaCompilationError(String),

    /// Serialization error.
    #[error("serialization error: {0}")]
    SerializationError(String),

    /// Graph contains a cycle.
    #[error("graph contains a cycle involving node '{node_id}'")]
    CyclicGraph { node_id: String },

    /// Invalid edge reference.
    #[error("edge '{edge_field}' references non-existent node '{node_id}'")]
    InvalidEdgeReference { edge_field: String, node_id: String },

    /// Invalid resource name (must be lowercase, alphanumeric, hyphens only).
    #[error("invalid {field}: '{value}' - must be lowercase, start with letter, contain only letters, numbers, and hyphens")]
    InvalidName { field: String, value: String },
}

impl From<GraphError> for ValidationError {
    fn from(err: GraphError) -> Self {
        match err {
            GraphError::CyclicGraph { node_id } => ValidationError::CyclicGraph { node_id },
            GraphError::NodeNotFound { node_id } => ValidationError::InvalidEdgeReference {
                edge_field: "unknown".to_string(),
                node_id,
            },
        }
    }
}