agentstategraph-core 1.4.1

Core types and algorithms for AgentStateGraph — zero I/O dependencies
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Schema system — optional JSON Schema validation with merge hints.
//!
//! Schemas use x-agentstategraph-merge annotations to tell the merge engine
//! how to handle each field. This enables CRDT-inspired auto-resolution
//! of concurrent changes.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A schema definition with merge hints.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Schema {
    /// The raw JSON Schema document.
    pub json_schema: serde_json::Value,
    /// Extracted merge hints per path.
    pub merge_hints: HashMap<String, MergeHint>,
    /// Enforcement mode.
    pub enforcement: EnforcementMode,
}

/// How a field should be merged when both sides change it.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MergeHint {
    /// Most recent commit's value wins.
    LastWriterWins,
    /// Merge arrays of records by a key field.
    UnionById(String),
    /// Union of both sets of values.
    Union,
    /// Add the deltas from both sides.
    Sum,
    /// Take the higher value.
    Max,
    /// Take the lower value.
    Min,
    /// Concatenate (source then target).
    Concat,
    /// Always flag as conflict.
    Manual,
    /// Invoke a named resolution function.
    Custom(String),
}

/// How strictly the schema is enforced.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum EnforcementMode {
    /// No validation. Schema is documentation only.
    #[default]
    None,
    /// Validate on commit, log warnings, but allow.
    Warn,
    /// Reject commits that violate the schema.
    Enforce,
    /// Apply automatic migrations when schema changes.
    Migrate,
}

/// Validation result for a state tree against a schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    pub valid: bool,
    pub errors: Vec<ValidationError>,
    pub warnings: Vec<String>,
}

/// A schema validation error.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    pub path: String,
    pub message: String,
    pub expected: Option<String>,
    pub actual: Option<String>,
}

impl Schema {
    /// Create a new schema from a JSON Schema document.
    /// Extracts x-agentstategraph-merge hints from the schema.
    pub fn from_json_schema(schema: serde_json::Value, enforcement: EnforcementMode) -> Self {
        let merge_hints = extract_merge_hints(&schema, "");
        Self {
            json_schema: schema,
            merge_hints,
            enforcement,
        }
    }

    /// Get the merge hint for a specific path.
    pub fn merge_hint_for(&self, path: &str) -> Option<&MergeHint> {
        self.merge_hints.get(path)
    }

    /// Validate a JSON value against this schema.
    /// Basic validation — checks required fields and types.
    pub fn validate(&self, value: &serde_json::Value) -> ValidationResult {
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        validate_recursive(&self.json_schema, value, "", &mut errors, &mut warnings);

        ValidationResult {
            valid: errors.is_empty(),
            errors,
            warnings,
        }
    }
}

/// Extract x-agentstategraph-merge hints from a JSON Schema document.
fn extract_merge_hints(schema: &serde_json::Value, path: &str) -> HashMap<String, MergeHint> {
    let mut hints = HashMap::new();

    if let Some(hint_str) = schema
        .get("x-agentstategraph-merge")
        .and_then(|v| v.as_str())
    {
        let id_field = schema
            .get("x-agentstategraph-id-field")
            .and_then(|v| v.as_str())
            .unwrap_or("id")
            .to_string();

        let hint = match hint_str {
            "last-writer-wins" => MergeHint::LastWriterWins,
            "union-by-id" => MergeHint::UnionById(id_field),
            "union" => MergeHint::Union,
            "sum" => MergeHint::Sum,
            "max" => MergeHint::Max,
            "min" => MergeHint::Min,
            "concat" => MergeHint::Concat,
            "manual" => MergeHint::Manual,
            other => MergeHint::Custom(other.to_string()),
        };
        hints.insert(path.to_string(), hint);
    }

    // Recurse into properties
    if let Some(props) = schema.get("properties").and_then(|v| v.as_object()) {
        for (key, prop_schema) in props {
            let child_path = if path.is_empty() {
                format!("/{}", key)
            } else {
                format!("{}/{}", path, key)
            };
            hints.extend(extract_merge_hints(prop_schema, &child_path));
        }
    }

    // Recurse into items (for arrays)
    if let Some(items) = schema.get("items") {
        let child_path = format!("{}/*", path);
        hints.extend(extract_merge_hints(items, &child_path));
    }

    hints
}

/// Basic recursive validation against a JSON Schema.
// `warnings` is threaded through so future validation rules can surface
// non-blocking findings (deprecation notices etc.) without restructuring
// call sites. Present but unused today.
#[allow(clippy::only_used_in_recursion)]
fn validate_recursive(
    schema: &serde_json::Value,
    value: &serde_json::Value,
    path: &str,
    errors: &mut Vec<ValidationError>,
    warnings: &mut Vec<String>,
) {
    // Check type
    if let Some(expected_type) = schema.get("type").and_then(|v| v.as_str()) {
        let actual_type = json_type_name(value);
        if expected_type != actual_type {
            errors.push(ValidationError {
                path: path.to_string(),
                message: format!("expected type '{}', found '{}'", expected_type, actual_type),
                expected: Some(expected_type.to_string()),
                actual: Some(actual_type.to_string()),
            });
            return;
        }
    }

    // Check required fields
    if let Some(required) = schema.get("required").and_then(|v| v.as_array())
        && let Some(obj) = value.as_object()
    {
        for req in required {
            if let Some(key) = req.as_str()
                && !obj.contains_key(key)
            {
                errors.push(ValidationError {
                    path: format!("{}/{}", path, key),
                    message: format!("required field '{}' is missing", key),
                    expected: Some("present".to_string()),
                    actual: Some("missing".to_string()),
                });
            }
        }
    }

    // Check enum values
    if let Some(enum_values) = schema.get("enum").and_then(|v| v.as_array())
        && !enum_values.contains(value)
    {
        errors.push(ValidationError {
            path: path.to_string(),
            message: format!("value not in allowed enum: {:?}", value),
            expected: Some(format!("{:?}", enum_values)),
            actual: Some(format!("{:?}", value)),
        });
    }

    // Recurse into properties
    if let Some(props) = schema.get("properties").and_then(|v| v.as_object())
        && let Some(obj) = value.as_object()
    {
        for (key, prop_schema) in props {
            if let Some(prop_value) = obj.get(key) {
                let child_path = format!("{}/{}", path, key);
                validate_recursive(prop_schema, prop_value, &child_path, errors, warnings);
            }
        }
    }

    // Recurse into array items
    if let Some(items_schema) = schema.get("items")
        && let Some(arr) = value.as_array()
    {
        for (i, item) in arr.iter().enumerate() {
            let child_path = format!("{}/{}", path, i);
            validate_recursive(items_schema, item, &child_path, errors, warnings);
        }
    }
}

fn json_type_name(value: &serde_json::Value) -> &'static str {
    match value {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "boolean",
        serde_json::Value::Number(n) => {
            if n.is_i64() || n.is_u64() {
                "integer"
            } else {
                "number"
            }
        }
        serde_json::Value::String(_) => "string",
        serde_json::Value::Array(_) => "array",
        serde_json::Value::Object(_) => "object",
    }
}

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

    #[test]
    fn test_extract_merge_hints() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "nodes": {
                    "type": "array",
                    "x-agentstategraph-merge": "union-by-id",
                    "x-agentstategraph-id-field": "node_id"
                },
                "request_count": {
                    "type": "integer",
                    "x-agentstategraph-merge": "sum"
                },
                "config": {
                    "type": "object",
                    "x-agentstategraph-merge": "last-writer-wins"
                }
            }
        });

        let s = Schema::from_json_schema(schema, EnforcementMode::None);
        assert_eq!(
            s.merge_hint_for("/nodes"),
            Some(&MergeHint::UnionById("node_id".to_string()))
        );
        assert_eq!(s.merge_hint_for("/request_count"), Some(&MergeHint::Sum));
        assert_eq!(
            s.merge_hint_for("/config"),
            Some(&MergeHint::LastWriterWins)
        );
    }

    #[test]
    fn test_validate_type_check() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "count": { "type": "integer" }
            },
            "required": ["name"]
        });

        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);

        // Valid
        let valid = serde_json::json!({"name": "test", "count": 5});
        let result = s.validate(&valid);
        assert!(result.valid, "errors: {:?}", result.errors);

        // Missing required field
        let missing = serde_json::json!({"count": 5});
        let result = s.validate(&missing);
        assert!(!result.valid);
        assert!(result.errors[0].message.contains("required"));

        // Wrong type
        let wrong_type = serde_json::json!({"name": 123, "count": 5});
        let result = s.validate(&wrong_type);
        assert!(!result.valid);
        assert!(result.errors[0].message.contains("expected type"));
    }

    #[test]
    fn test_validate_enum() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "enum": ["healthy", "unhealthy", "draining"]
                }
            }
        });

        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);

        let valid = serde_json::json!({"status": "healthy"});
        assert!(s.validate(&valid).valid);

        let invalid = serde_json::json!({"status": "unknown"});
        assert!(!s.validate(&invalid).valid);
    }

    #[test]
    fn test_validate_nested() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "nodes": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "hostname": { "type": "string" },
                            "status": { "type": "string", "enum": ["healthy", "unhealthy"] }
                        },
                        "required": ["hostname", "status"]
                    }
                }
            }
        });

        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);

        let valid = serde_json::json!({
            "nodes": [
                {"hostname": "node-1", "status": "healthy"},
                {"hostname": "node-2", "status": "unhealthy"}
            ]
        });
        assert!(s.validate(&valid).valid);

        let invalid = serde_json::json!({
            "nodes": [
                {"hostname": "node-1"}  // missing required "status"
            ]
        });
        assert!(!s.validate(&invalid).valid);
    }

    // --- All merge hint variants ---

    #[test]
    fn test_extract_all_merge_hint_variants() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "a": { "x-agentstategraph-merge": "last-writer-wins" },
                "b": { "x-agentstategraph-merge": "union-by-id" }, // default id field
                "c": { "x-agentstategraph-merge": "union" },
                "d": { "x-agentstategraph-merge": "sum" },
                "e": { "x-agentstategraph-merge": "max" },
                "f": { "x-agentstategraph-merge": "min" },
                "g": { "x-agentstategraph-merge": "concat" },
                "h": { "x-agentstategraph-merge": "manual" },
                "i": { "x-agentstategraph-merge": "my-custom-resolver" }
            }
        });

        let s = Schema::from_json_schema(schema, EnforcementMode::None);

        assert_eq!(s.merge_hint_for("/a"), Some(&MergeHint::LastWriterWins));
        // union-by-id without explicit id-field defaults to "id"
        assert_eq!(
            s.merge_hint_for("/b"),
            Some(&MergeHint::UnionById("id".to_string()))
        );
        assert_eq!(s.merge_hint_for("/c"), Some(&MergeHint::Union));
        assert_eq!(s.merge_hint_for("/d"), Some(&MergeHint::Sum));
        assert_eq!(s.merge_hint_for("/e"), Some(&MergeHint::Max));
        assert_eq!(s.merge_hint_for("/f"), Some(&MergeHint::Min));
        assert_eq!(s.merge_hint_for("/g"), Some(&MergeHint::Concat));
        assert_eq!(s.merge_hint_for("/h"), Some(&MergeHint::Manual));
        assert_eq!(
            s.merge_hint_for("/i"),
            Some(&MergeHint::Custom("my-custom-resolver".to_string()))
        );
    }

    #[test]
    fn test_merge_hint_for_unknown_path_returns_none() {
        let schema = serde_json::json!({ "type": "object" });
        let s = Schema::from_json_schema(schema, EnforcementMode::None);
        assert_eq!(s.merge_hint_for("/nonexistent"), None);
        assert_eq!(s.merge_hint_for(""), None);
    }

    #[test]
    fn test_union_by_id_explicit_id_field() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "records": {
                    "x-agentstategraph-merge": "union-by-id",
                    "x-agentstategraph-id-field": "record_id"
                }
            }
        });
        let s = Schema::from_json_schema(schema, EnforcementMode::None);
        assert_eq!(
            s.merge_hint_for("/records"),
            Some(&MergeHint::UnionById("record_id".to_string()))
        );
    }

    // --- items/* path for array schemas ---

    #[test]
    fn test_extract_merge_hints_from_items() {
        let schema = serde_json::json!({
            "type": "array",
            "x-agentstategraph-merge": "concat",
            "items": {
                "x-agentstategraph-merge": "last-writer-wins"
            }
        });
        let s = Schema::from_json_schema(schema, EnforcementMode::None);
        // Root-level hint
        assert_eq!(s.merge_hint_for(""), Some(&MergeHint::Concat));
        // Items hint
        assert_eq!(s.merge_hint_for("/*"), Some(&MergeHint::LastWriterWins));
    }

    // --- EnforcementMode default ---

    #[test]
    fn test_enforcement_mode_default_is_none() {
        assert_eq!(EnforcementMode::default(), EnforcementMode::None);
    }

    // --- json_type_name coverage ---

    #[test]
    fn test_type_mismatch_null() {
        let schema = serde_json::json!({ "type": "string" });
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);
        let result = s.validate(&serde_json::Value::Null);
        assert!(!result.valid);
        let e = &result.errors[0];
        assert_eq!(e.expected.as_deref(), Some("string"));
        assert_eq!(e.actual.as_deref(), Some("null"));
    }

    #[test]
    fn test_type_mismatch_boolean() {
        let schema = serde_json::json!({ "type": "integer" });
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);
        let result = s.validate(&serde_json::json!(true));
        assert!(!result.valid);
        assert_eq!(result.errors[0].actual.as_deref(), Some("boolean"));
    }

    #[test]
    fn test_type_mismatch_array() {
        let schema = serde_json::json!({ "type": "object" });
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);
        let result = s.validate(&serde_json::json!([1, 2, 3]));
        assert!(!result.valid);
        assert_eq!(result.errors[0].actual.as_deref(), Some("array"));
    }

    #[test]
    #[allow(clippy::approx_constant)] // 3.14 here is just arbitrary float test data, not PI
    fn test_type_number_vs_integer() {
        // float is "number", not "integer"
        let schema = serde_json::json!({ "type": "number" });
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);
        let result = s.validate(&serde_json::json!(3.14));
        assert!(result.valid, "3.14 should satisfy type:number");

        let schema = serde_json::json!({ "type": "integer" });
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);
        let result = s.validate(&serde_json::json!(42));
        assert!(result.valid, "42 should satisfy type:integer");
    }

    // --- Validation edge cases ---

    #[test]
    fn test_validate_empty_schema_accepts_anything() {
        let schema = serde_json::json!({});
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);
        assert!(s.validate(&serde_json::json!(42)).valid);
        assert!(s.validate(&serde_json::json!({"a": 1})).valid);
        assert!(s.validate(&serde_json::Value::Null).valid);
    }

    #[test]
    fn test_validate_multiple_required_fields_missing() {
        let schema = serde_json::json!({
            "type": "object",
            "required": ["a", "b", "c"]
        });
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);
        let result = s.validate(&serde_json::json!({"a": 1}));
        assert!(!result.valid);
        assert_eq!(
            result.errors.len(),
            2,
            "b and c should both be reported missing"
        );
        let paths: Vec<_> = result.errors.iter().map(|e| e.path.as_str()).collect();
        assert!(paths.iter().any(|p| p.contains("b")));
        assert!(paths.iter().any(|p| p.contains("c")));
    }

    #[test]
    fn test_validation_error_fields_populated() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "x": { "type": "string" }
            }
        });
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);
        let result = s.validate(&serde_json::json!({"x": 42}));
        assert!(!result.valid);
        let e = &result.errors[0];
        assert!(!e.path.is_empty());
        assert!(!e.message.is_empty());
        assert!(e.expected.is_some());
        assert!(e.actual.is_some());
    }

    #[test]
    fn test_validate_array_items_recursively() {
        let schema = serde_json::json!({
            "type": "array",
            "items": { "type": "integer" }
        });
        let s = Schema::from_json_schema(schema, EnforcementMode::Enforce);

        assert!(s.validate(&serde_json::json!([1, 2, 3])).valid);

        let result = s.validate(&serde_json::json!([1, "bad", 3]));
        assert!(!result.valid);
        assert_eq!(result.errors.len(), 1);
        assert!(result.errors[0].path.contains("1")); // index 1 is "bad"
    }

    // --- Schema serialization ---

    #[test]
    fn test_schema_serializes_and_deserializes() {
        let schema = Schema::from_json_schema(
            serde_json::json!({
                "type": "object",
                "properties": {
                    "count": { "x-agentstategraph-merge": "sum" }
                }
            }),
            EnforcementMode::Warn,
        );

        let json = serde_json::to_string(&schema).unwrap();
        let restored: Schema = serde_json::from_str(&json).unwrap();

        assert_eq!(restored.enforcement, EnforcementMode::Warn);
        assert_eq!(restored.merge_hint_for("/count"), Some(&MergeHint::Sum));
    }

    #[test]
    fn test_merge_hint_serializes_and_deserializes() {
        let hints = vec![
            MergeHint::LastWriterWins,
            MergeHint::UnionById("id".to_string()),
            MergeHint::Union,
            MergeHint::Sum,
            MergeHint::Max,
            MergeHint::Min,
            MergeHint::Concat,
            MergeHint::Manual,
            MergeHint::Custom("custom-fn".to_string()),
        ];
        for hint in hints {
            let json = serde_json::to_string(&hint).unwrap();
            let restored: MergeHint = serde_json::from_str(&json).unwrap();
            assert_eq!(restored, hint, "round-trip failed for {hint:?}");
        }
    }
}