daat-locus 0.4.0

A long-running local agent runtime with memory, workflows, apps, and sleep-time self-improvement.
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
use std::collections::BTreeSet;

use daat_locus_macros::model_schema;
use miette::{Result, miette};
use serde_json::{Map, Value, json};

const ALLOWED_SCHEMA_KEYS: &[&str] = &[
    "type",
    "description",
    "properties",
    "required",
    "additionalProperties",
    "items",
    "enum",
];

const FORBIDDEN_SCHEMA_KEYS: &[&str] = &[
    "$defs",
    "$ref",
    "definitions",
    "allOf",
    "anyOf",
    "oneOf",
    "not",
    "if",
    "then",
    "else",
    "dependentRequired",
    "dependentSchemas",
    "prefixItems",
    "default",
    "minLength",
    "maxLength",
    "pattern",
    "format",
    "minimum",
    "maximum",
    "multipleOf",
    "minItems",
    "maxItems",
    "uniqueItems",
    "contains",
];

const SIMPLE_TYPES: &[&str] = &[
    "string", "integer", "number", "boolean", "object", "array", "null",
];

pub trait ModelSchema {
    fn model_schema() -> Value;
}

pub fn model_schema_for<T: ModelSchema>() -> Value {
    model_schema(T::model_schema())
}

pub fn model_schema(schema: Value) -> Value {
    validate_model_facing_schema(&schema).expect("model-facing schema must be valid");
    schema
}

pub fn validate_model_facing_schema(schema: &Value) -> Result<()> {
    let mut errors = Vec::new();
    validate_schema_at(schema, "$", true, &mut errors);
    if errors.is_empty() {
        Ok(())
    } else {
        Err(miette!(
            "invalid model-facing JSON schema:\n{}",
            errors.join("\n")
        ))
    }
}

pub fn validate_value_against_schema(value: &Value, schema: &Value, label: &str) -> Result<()> {
    let object = schema
        .as_object()
        .ok_or_else(|| miette!("{label} schema must be a JSON object"))?;

    if let Some(enum_values) = object.get("enum") {
        let enum_values = enum_values
            .as_array()
            .ok_or_else(|| miette!("{label}.enum must be an array"))?;
        if !enum_values.iter().any(|candidate| candidate == value) {
            return Err(miette!("{label} must match one of the allowed enum values"));
        }
    }

    let type_names = value_schema_type_names(object, label)?;
    if value.is_null() {
        if type_names.iter().any(|type_name| type_name == "null") {
            return Ok(());
        }
        return Err(miette!("{label} must not be null"));
    }

    let mut matched = false;
    for type_name in &type_names {
        match type_name.as_str() {
            "object" if value.is_object() => {
                validate_object_instance(value, object, label)?;
                matched = true;
            }
            "array" if value.is_array() => {
                validate_array_instance(value, object, label)?;
                matched = true;
            }
            "string" if value.is_string() => matched = true,
            "integer" if value.as_i64().is_some() || value.as_u64().is_some() => matched = true,
            "number" if value.is_number() => matched = true,
            "boolean" if value.is_boolean() => matched = true,
            _ => {}
        }
    }
    if matched {
        Ok(())
    } else if type_names.len() == 1 {
        Err(miette!("{label} must be a {}", type_names[0]))
    } else {
        Err(miette!(
            "{label} must match schema type {}",
            type_names.join(" or ")
        ))
    }
}

fn value_schema_type_names(object: &Map<String, Value>, label: &str) -> Result<Vec<String>> {
    let type_value = object
        .get("type")
        .ok_or_else(|| miette!("{label}.type is required"))?;
    match type_value {
        Value::String(value) => Ok(vec![value.clone()]),
        Value::Array(values) => values
            .iter()
            .enumerate()
            .map(|(index, value)| {
                value
                    .as_str()
                    .map(ToString::to_string)
                    .ok_or_else(|| miette!("{label}.type[{index}] must be a string"))
            })
            .collect(),
        _ => Err(miette!("{label}.type must be a string or string array")),
    }
}

fn validate_object_instance(value: &Value, schema: &Map<String, Value>, label: &str) -> Result<()> {
    let object = value
        .as_object()
        .ok_or_else(|| miette!("{label} must be an object"))?;
    let properties = schema
        .get("properties")
        .and_then(Value::as_object)
        .ok_or_else(|| miette!("{label}.properties must be an object"))?;
    let required = schema
        .get("required")
        .and_then(Value::as_array)
        .ok_or_else(|| miette!("{label}.required must be an array"))?;

    for field in required {
        let field = field
            .as_str()
            .ok_or_else(|| miette!("{label}.required entries must be strings"))?;
        if !object.contains_key(field) {
            return Err(miette!("{label}.{field} is required"));
        }
    }
    for (key, field_value) in object {
        let Some(field_schema) = properties.get(key) else {
            return Err(miette!("{label}.{key} is not allowed"));
        };
        validate_value_against_schema(field_value, field_schema, &format!("{label}.{key}"))?;
    }
    Ok(())
}

fn validate_array_instance(value: &Value, schema: &Map<String, Value>, label: &str) -> Result<()> {
    let items = value
        .as_array()
        .ok_or_else(|| miette!("{label} must be an array"))?;
    let item_schema = schema
        .get("items")
        .ok_or_else(|| miette!("{label}.items is required"))?;
    for (index, item) in items.iter().enumerate() {
        validate_value_against_schema(item, item_schema, &format!("{label}[{index}]"))?;
    }
    Ok(())
}

pub fn string_schema() -> Value {
    json!({ "type": "string" })
}

pub fn integer_schema() -> Value {
    json!({ "type": "integer" })
}

pub fn number_schema() -> Value {
    json!({ "type": "number" })
}

pub fn boolean_schema() -> Value {
    json!({ "type": "boolean" })
}

pub fn array_schema(items: &Value) -> Value {
    json!({
        "type": "array",
        "items": items,
    })
}

pub fn string_enum_schema(values: &[&str]) -> Value {
    json!({
        "type": "string",
        "enum": values,
    })
}

pub fn nullable_schema(mut schema: Value) -> Value {
    let Some(object) = schema.as_object_mut() else {
        return schema;
    };

    let type_value = object
        .remove("type")
        .unwrap_or_else(|| Value::String("object".to_string()));
    let mut types = match type_value {
        Value::String(value) => vec![Value::String(value)],
        Value::Array(values) => values,
        other => vec![other],
    };
    if !types.iter().any(|value| value == "null") {
        types.push(Value::String("null".to_string()));
    }
    object.insert("type".to_string(), Value::Array(types));

    if let Some(Value::Array(values)) = object.get_mut("enum")
        && !values.iter().any(Value::is_null)
    {
        values.push(Value::Null);
    }

    schema
}

#[model_schema]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct StructuredEditArgsSchema {
    pub edits: Vec<StructuredEditSchema>,
}

#[model_schema]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct StructuredEditSchema {
    pub path: String,
    /// Operation kind. Omitted or null defaults to `append` for new files.
    pub op: Option<StructuredEditOpSchema>,
    /// `line#hash` anchor (e.g., `42#ab`), without the `|source_line` portion shown in read output.
    /// Omitted or null defaults to `"1#"` for new files.
    pub start: Option<String>,
    /// `line#hash` end anchor, required for `replace` and ignored for `append`/`prepend`.
    pub end: Option<String>,
    pub content: Option<String>,
}

#[model_schema]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StructuredEditOpSchema {
    Replace,
    Append,
    Prepend,
}

pub fn structured_edit_args_schema() -> Value {
    model_schema_for::<StructuredEditArgsSchema>()
}

fn validate_schema_at(schema: &Value, path: &str, root: bool, errors: &mut Vec<String>) {
    let Some(object) = schema.as_object() else {
        errors.push(format!("{path}: schema must be a JSON object"));
        return;
    };

    for key in object.keys() {
        if FORBIDDEN_SCHEMA_KEYS.contains(&key.as_str()) {
            errors.push(format!("{path}: forbidden schema keyword `{key}`"));
        } else if !ALLOWED_SCHEMA_KEYS.contains(&key.as_str()) {
            errors.push(format!("{path}: unsupported schema keyword `{key}`"));
        }
    }

    let type_names = parse_type_names(object.get("type"), path, errors);
    if root && !type_names.iter().any(|name| name == "object") {
        errors.push(format!("{path}: root schema must be an object schema"));
    }
    validate_type_union(&type_names, path, errors);

    if let Some(description) = object.get("description")
        && !description.is_string()
    {
        errors.push(format!("{path}.description: must be a string"));
    }

    if let Some(enum_values) = object.get("enum") {
        validate_enum(enum_values, &type_names, path, errors);
    }

    if type_names.iter().any(|name| name == "object") || object.contains_key("properties") {
        validate_object_schema(object, path, errors);
    }

    if type_names.iter().any(|name| name == "array") || object.contains_key("items") {
        validate_array_schema(object, path, errors);
    }

    if let Some(additional_properties) = object.get("additionalProperties")
        && additional_properties != &Value::Bool(false)
    {
        errors.push(format!(
            "{path}.additionalProperties: must be exactly false"
        ));
    }
}

fn parse_type_names(
    type_value: Option<&Value>,
    path: &str,
    errors: &mut Vec<String>,
) -> Vec<String> {
    let Some(type_value) = type_value else {
        errors.push(format!("{path}.type: missing type"));
        return Vec::new();
    };
    match type_value {
        Value::String(value) => vec![value.clone()],
        Value::Array(values) => values
            .iter()
            .enumerate()
            .filter_map(|(index, value)| {
                value.as_str().map_or_else(
                    || {
                        errors.push(format!("{path}.type[{index}]: must be a string"));
                        None
                    },
                    |value| Some(value.to_string()),
                )
            })
            .collect(),
        _ => {
            errors.push(format!("{path}.type: must be a string or string array"));
            Vec::new()
        }
    }
}

fn validate_type_union(type_names: &[String], path: &str, errors: &mut Vec<String>) {
    if type_names.is_empty() {
        return;
    }
    let mut seen = BTreeSet::new();
    for type_name in type_names {
        if !SIMPLE_TYPES.contains(&type_name.as_str()) {
            errors.push(format!("{path}.type: unsupported type `{type_name}`"));
        }
        if !seen.insert(type_name.as_str()) {
            errors.push(format!("{path}.type: duplicate type `{type_name}`"));
        }
    }
    if type_names.len() > 2
        || (type_names.len() == 2 && !type_names.iter().any(|name| name == "null"))
    {
        errors.push(format!(
            "{path}.type: only nullable unions with one non-null type are supported"
        ));
    }
}

fn validate_enum(enum_values: &Value, type_names: &[String], path: &str, errors: &mut Vec<String>) {
    let Some(values) = enum_values.as_array() else {
        errors.push(format!("{path}.enum: must be an array"));
        return;
    };
    if values.is_empty() {
        errors.push(format!("{path}.enum: must not be empty"));
    }
    for (index, value) in values.iter().enumerate() {
        match value {
            Value::String(_) => {
                if !type_names.iter().any(|name| name == "string") {
                    errors.push(format!(
                        "{path}.enum[{index}]: string value without string type"
                    ));
                }
            }
            Value::Null => {
                if !type_names.iter().any(|name| name == "null") {
                    errors.push(format!(
                        "{path}.enum[{index}]: null value without null type"
                    ));
                }
            }
            _ => errors.push(format!(
                "{path}.enum[{index}]: only string and null values are supported"
            )),
        }
    }
}

fn validate_object_schema(object: &Map<String, Value>, path: &str, errors: &mut Vec<String>) {
    let Some(properties) = object.get("properties") else {
        errors.push(format!("{path}.properties: missing properties object"));
        return;
    };
    let Some(properties) = properties.as_object() else {
        errors.push(format!("{path}.properties: must be an object"));
        return;
    };

    match object.get("additionalProperties") {
        Some(Value::Bool(false)) => {}
        Some(_) => errors.push(format!(
            "{path}.additionalProperties: must be exactly false"
        )),
        None => errors.push(format!(
            "{path}.additionalProperties: missing additionalProperties=false"
        )),
    }

    let Some(required) = object.get("required") else {
        errors.push(format!("{path}.required: missing required array"));
        return;
    };
    let Some(required) = required.as_array() else {
        errors.push(format!("{path}.required: must be an array"));
        return;
    };
    let mut required_names = BTreeSet::new();
    for (index, item) in required.iter().enumerate() {
        if let Some(name) = item.as_str() {
            required_names.insert(name);
        } else {
            errors.push(format!("{path}.required[{index}]: must be a string"));
        }
    }
    let property_names = properties
        .keys()
        .map(String::as_str)
        .collect::<BTreeSet<_>>();
    if required_names != property_names {
        errors.push(format!(
            "{path}.required: must exactly match properties; required={required_names:?} properties={property_names:?}"
        ));
    }

    for (name, property_schema) in properties {
        validate_schema_at(
            property_schema,
            &format!("{path}.properties.{name}"),
            false,
            errors,
        );
    }
}

fn validate_array_schema(object: &Map<String, Value>, path: &str, errors: &mut Vec<String>) {
    let Some(items) = object.get("items") else {
        errors.push(format!("{path}.items: missing homogeneous item schema"));
        return;
    };
    validate_schema_at(items, &format!("{path}.items"), false, errors);
}

#[cfg(test)]
mod tests {
    use super::{
        boolean_schema, model_schema, nullable_schema, string_schema, structured_edit_args_schema,
        validate_model_facing_schema,
    };
    use serde_json::{Value, json};

    fn contains_key(value: &Value, needle: &str) -> bool {
        match value {
            Value::Object(object) => {
                object.contains_key(needle)
                    || object.values().any(|value| contains_key(value, needle))
            }
            Value::Array(values) => values.iter().any(|value| contains_key(value, needle)),
            _ => false,
        }
    }

    #[test]
    fn object_schema_requires_every_property_and_forbids_extra_properties() {
        let schema = model_schema(json!({
            "type": "object",
            "properties": {
                "text": nullable_schema(string_schema()),
                "enabled": boolean_schema(),
            },
            "required": ["text", "enabled"],
            "additionalProperties": false,
        }));

        assert_eq!(schema["additionalProperties"], json!(false));
        assert_eq!(schema["required"], json!(["text", "enabled"]));
        validate_model_facing_schema(&schema).unwrap();
    }

    #[test]
    fn validator_rejects_provider_normalization_cases() {
        let schema = json!({
            "type": "object",
            "properties": {
                "case": {
                    "$ref": "#/$defs/SearchCase",
                    "default": "smart"
                }
            },
            "required": ["case"],
            "additionalProperties": false,
            "$defs": {
                "SearchCase": {
                    "type": "string",
                    "enum": ["sensitive", "insensitive", "smart"]
                }
            }
        });

        let err = validate_model_facing_schema(&schema)
            .unwrap_err()
            .to_string();

        assert!(err.contains("forbidden schema keyword `$defs`"), "{err}");
        assert!(err.contains("forbidden schema keyword `$ref`"), "{err}");
        assert!(err.contains("forbidden schema keyword `default`"), "{err}");
    }

    #[test]
    fn validator_rejects_optional_properties_by_omission() {
        let schema = json!({
            "type": "object",
            "properties": {
                "required_text": { "type": "string" },
                "optional_text": { "type": ["string", "null"] }
            },
            "required": ["required_text"],
            "additionalProperties": false
        });

        let err = validate_model_facing_schema(&schema)
            .unwrap_err()
            .to_string();

        assert!(err.contains("must exactly match properties"), "{err}");
    }

    #[test]
    fn validator_rejects_validation_keywords() {
        let schema = json!({
            "type": "object",
            "properties": {
                "items": {
                    "type": "array",
                    "minItems": 1,
                    "items": { "type": "string" }
                }
            },
            "required": ["items"],
            "additionalProperties": false
        });

        let err = validate_model_facing_schema(&schema)
            .unwrap_err()
            .to_string();

        assert!(err.contains("forbidden schema keyword `minItems`"), "{err}");
    }

    #[test]
    fn structured_edit_schema_uses_portable_nullable_fields() {
        let schema = structured_edit_args_schema();

        validate_model_facing_schema(&schema).unwrap();
        for key in ["oneOf", "anyOf", "allOf", "minItems"] {
            assert!(!contains_key(&schema, key), "{schema:#}");
        }
        assert_eq!(
            schema["properties"]["edits"]["items"]["properties"]["content"]["type"],
            json!(["string", "null"])
        );
        assert_eq!(
            schema["properties"]["edits"]["items"]["properties"]["end"]["type"],
            json!(["string", "null"])
        );
        assert_eq!(
            schema["properties"]["edits"]["items"]["properties"]["start"]["description"],
            "`line#hash` anchor (e.g., `42#ab`), without the `|source_line` portion shown in read output. Omitted or null defaults to `\"1#\"` for new files."
        );
        assert_eq!(
            schema["properties"]["edits"]["items"]["properties"]["end"]["description"],
            "`line#hash` end anchor, required for `replace` and ignored for `append`/`prepend`."
        );
    }

    #[test]
    fn model_schema_panics_for_invalid_schemas() {
        let result = std::panic::catch_unwind(|| {
            model_schema(json!({
                "type": "object",
                "properties": {},
            }));
        });

        assert!(result.is_err());
    }
}