rigg 0.17.0

Configuration-as-code CLI for Azure AI Search and Microsoft Foundry
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
//! Validate local configuration

mod field_types;
mod lint;
mod references;

use anyhow::Result;
use serde_json::json;
use std::collections::HashMap;

use rigg_core::resources::ResourceKind;

use crate::cli::OutputFormat;
use crate::commands::load_config_and_env;

use field_types::validate_field_types;
use lint::lint_resources;
use references::validate_references;

pub async fn run(
    strict: bool,
    check_references: bool,
    output: OutputFormat,
    env_override: Option<&str>,
) -> Result<()> {
    let (project_root, config, env) = load_config_and_env(env_override)?;
    let files_root = config.files_root(&project_root);

    if matches!(output, OutputFormat::Text) {
        println!("Validating project at {}", project_root.display());
        println!();
    }

    let mut errors = Vec::new();
    let mut warnings = Vec::new();

    // Collect all resources
    let mut resources: HashMap<ResourceKind, Vec<(String, serde_json::Value)>> = HashMap::new();

    let kinds = if env.sync.include_preview {
        ResourceKind::all()
    } else {
        ResourceKind::stable()
    };

    let primary_search = env.primary_search_service();

    for kind in kinds {
        if kind.domain() == rigg_core::service::ServiceDomain::Foundry {
            continue; // Agent validation is handled below
        }

        let resource_dir = match primary_search {
            Some(svc) => env
                .search_service_dir(&files_root, svc)
                .join(kind.directory_name()),
            None => continue,
        };
        if !resource_dir.exists() {
            continue;
        }

        let mut kind_resources = Vec::new();

        if *kind == ResourceKind::KnowledgeSource {
            // KS are stored as subdirectories: <ks-name>/<ks-name>.json
            for entry in std::fs::read_dir(&resource_dir)? {
                let entry = entry?;
                let path = entry.path();
                if !path.is_dir() {
                    continue;
                }
                let name = match path.file_name().and_then(|n| n.to_str()) {
                    Some(n) => n.to_string(),
                    None => continue,
                };
                let ks_file = path.join(format!("{}.json", name));
                if !ks_file.exists() {
                    errors.push(format!(
                        "{}/{}/{}.json: missing KS definition file",
                        kind.directory_name(),
                        name,
                        name
                    ));
                    continue;
                }
                let content = std::fs::read_to_string(&ks_file)?;
                match serde_json::from_str::<serde_json::Value>(&content) {
                    Ok(value) => {
                        if let Some(json_name) = value.get("name").and_then(|n| n.as_str()) {
                            if json_name != name {
                                errors.push(format!(
                                    "{}/{}/{}.json: name field '{}' doesn't match directory",
                                    kind.directory_name(),
                                    name,
                                    name,
                                    json_name
                                ));
                            }
                        } else {
                            errors.push(format!(
                                "{}/{}/{}.json: missing required 'name' field",
                                kind.directory_name(),
                                name,
                                name
                            ));
                        }
                        kind_resources.push((name, value));
                    }
                    Err(e) => {
                        errors.push(format!(
                            "{}/{}/{}.json: invalid JSON - {}",
                            kind.directory_name(),
                            name,
                            name,
                            e
                        ));
                    }
                }
            }
        } else {
            // Standard flat JSON files
            for entry in std::fs::read_dir(&resource_dir)? {
                let entry = entry?;
                let path = entry.path();

                if path.extension().and_then(|e| e.to_str()) != Some("json") {
                    continue;
                }

                let name = path
                    .file_stem()
                    .and_then(|n| n.to_str())
                    .ok_or_else(|| anyhow::anyhow!("Invalid file name"))?
                    .to_string();

                // Parse JSON
                let content = std::fs::read_to_string(&path)?;
                match serde_json::from_str::<serde_json::Value>(&content) {
                    Ok(value) => {
                        // Validate JSON name matches filename
                        if let Some(json_name) = value.get("name").and_then(|n| n.as_str()) {
                            if json_name != name {
                                errors.push(format!(
                                    "{}/{}.json: name field '{}' doesn't match filename",
                                    kind.directory_name(),
                                    name,
                                    json_name
                                ));
                            }
                        } else {
                            errors.push(format!(
                                "{}/{}.json: missing required 'name' field",
                                kind.directory_name(),
                                name
                            ));
                        }

                        kind_resources.push((name, value));
                    }
                    Err(e) => {
                        errors.push(format!(
                            "{}/{}.json: invalid JSON - {}",
                            kind.directory_name(),
                            name,
                            e
                        ));
                    }
                }
            }
        }

        resources.insert(*kind, kind_resources);
    }

    // Validate Foundry agents
    if env.has_foundry() {
        let mut agent_resources = Vec::new();
        for foundry_config in &env.foundry {
            let agents_dir = env
                .foundry_service_dir(&files_root, foundry_config)
                .join("agents");
            if !agents_dir.exists() {
                continue;
            }
            for entry in std::fs::read_dir(&agents_dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
                    continue;
                }
                let name = match path.file_stem().and_then(|n| n.to_str()) {
                    Some(n) => n.to_string(),
                    None => continue,
                };

                if let Some(resource) =
                    validate_agent_yaml(&path, &name, &mut errors, &mut warnings)
                {
                    agent_resources.push(resource);
                }
            }
        }
        if !agent_resources.is_empty() {
            resources.insert(ResourceKind::Agent, agent_resources);
        }
    }

    // Run lint checks
    lint_resources(&resources, &mut warnings);

    // Validate index field types
    if let Some(indexes) = resources.get(&ResourceKind::Index) {
        for (name, value) in indexes {
            if let Some(fields) = value.get("fields").and_then(|f| f.as_array()) {
                validate_field_types(name, fields, "", &mut errors);
            }
        }
    }

    // Check references if requested
    if check_references {
        validate_references(&resources, &mut errors, &mut warnings);
    }

    // Strict mode: treat warnings as errors
    if strict {
        errors.append(&mut warnings);
    }

    // Report results
    let total_resources: usize = resources.values().map(|v| v.len()).sum();
    let passed = errors.is_empty();

    match output {
        OutputFormat::Json => {
            let result = json!({
                "total_resources": total_resources,
                "errors": errors,
                "error_count": errors.len(),
                "warnings": warnings,
                "warning_count": warnings.len(),
                "passed": passed,
                "include_preview": env.sync.include_preview,
            });
            println!("{}", serde_json::to_string_pretty(&result)?);
            if !passed {
                anyhow::bail!("Validation failed with {} error(s)", errors.len());
            }
        }
        OutputFormat::Text => {
            println!("Scanned {} resources", total_resources);

            if !warnings.is_empty() {
                println!();
                println!("Warnings ({}):", warnings.len());
                for warning in &warnings {
                    println!("  ! {}", warning);
                }
            }

            if !passed {
                println!();
                println!("Errors ({}):", errors.len());
                for error in &errors {
                    println!("  x {}", error);
                }
                println!();
                anyhow::bail!("Validation failed with {} error(s)", errors.len());
            }

            println!();
            println!("Validation passed!");

            if env.sync.include_preview {
                println!("Note: Includes preview resources (knowledge bases, knowledge sources).");
            } else {
                println!();
                println!(
                    "Note: Preview resources (knowledge bases, knowledge sources) not validated."
                );
                println!("      Set sync.include_preview = true to include them.");
            }

            if env.has_foundry() {
                let agent_count = resources
                    .get(&ResourceKind::Agent)
                    .map(|v| v.len())
                    .unwrap_or(0);
                if agent_count > 0 {
                    println!("      Validated {} Foundry agent(s).", agent_count);
                }
            }
        }
    }

    Ok(())
}

/// Validate a single agent YAML file. Returns the parsed value on success,
/// pushing any issues into the errors/warnings vecs.
fn validate_agent_yaml(
    yaml_path: &std::path::Path,
    name: &str,
    errors: &mut Vec<String>,
    warnings: &mut Vec<String>,
) -> Option<(String, serde_json::Value)> {
    let content = match std::fs::read_to_string(yaml_path) {
        Ok(c) => c,
        Err(e) => {
            errors.push(format!("agents/{}.yaml: read error - {}", name, e));
            return None;
        }
    };

    match serde_yaml::from_str::<serde_json::Value>(&content) {
        Ok(value) => {
            // Agent name is derived from filename — no name field to validate

            // Validate model field exists
            if value.get("model").and_then(|m| m.as_str()).is_none() {
                warnings.push(format!("agents/{}.yaml: missing 'model' field", name));
            }

            // Validate instructions field exists (warning, not error)
            let has_instructions = value
                .get("instructions")
                .and_then(|i| i.as_str())
                .is_some_and(|s| !s.is_empty());
            if !has_instructions {
                warnings.push(format!(
                    "agents/{}.yaml: missing or empty 'instructions'",
                    name
                ));
            }

            Some((name.to_string(), value))
        }
        Err(e) => {
            errors.push(format!("agents/{}.yaml: invalid YAML - {}", name, e));
            None
        }
    }
}

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

    #[test]
    fn test_validate_agent_yaml_full() {
        let dir = tempfile::tempdir().unwrap();
        let yaml_path = dir.path().join("my-agent.yaml");

        std::fs::write(
            &yaml_path,
            "kind: prompt\nmodel: gpt-4o\ninstructions: You are a helpful assistant.\n",
        )
        .unwrap();

        let mut errors = Vec::new();
        let mut warnings = Vec::new();
        let result = validate_agent_yaml(&yaml_path, "my-agent", &mut errors, &mut warnings);

        assert!(result.is_some());
        assert!(errors.is_empty(), "Expected no errors, got: {:?}", errors);
        assert!(
            warnings.is_empty(),
            "Expected no warnings, got: {:?}",
            warnings
        );
        assert_eq!(result.unwrap().0, "my-agent");
    }

    #[test]
    fn test_validate_agent_yaml_invalid() {
        let dir = tempfile::tempdir().unwrap();
        let yaml_path = dir.path().join("bad.yaml");
        std::fs::write(&yaml_path, "{{invalid yaml").unwrap();

        let mut errors = Vec::new();
        let mut warnings = Vec::new();
        let result = validate_agent_yaml(&yaml_path, "bad", &mut errors, &mut warnings);

        assert!(result.is_none());
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("invalid YAML"));
    }

    #[test]
    fn test_validate_agent_yaml_missing_model_warning() {
        let dir = tempfile::tempdir().unwrap();
        let yaml_path = dir.path().join("my-agent.yaml");

        std::fs::write(&yaml_path, "kind: prompt\ninstructions: Be helpful.\n").unwrap();

        let mut errors = Vec::new();
        let mut warnings = Vec::new();
        validate_agent_yaml(&yaml_path, "my-agent", &mut errors, &mut warnings);

        assert!(errors.is_empty());
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("missing 'model' field"));
    }

    #[test]
    fn test_validate_agent_yaml_missing_instructions_warning() {
        let dir = tempfile::tempdir().unwrap();
        let yaml_path = dir.path().join("my-agent.yaml");

        std::fs::write(&yaml_path, "kind: prompt\nmodel: gpt-4o\n").unwrap();

        let mut errors = Vec::new();
        let mut warnings = Vec::new();
        validate_agent_yaml(&yaml_path, "my-agent", &mut errors, &mut warnings);

        assert!(errors.is_empty());
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("missing or empty 'instructions'"));
    }

    #[test]
    fn test_validate_agent_yaml_multiple_issues() {
        let dir = tempfile::tempdir().unwrap();
        let yaml_path = dir.path().join("my-agent.yaml");

        // No model + no instructions
        std::fs::write(&yaml_path, "kind: prompt\n").unwrap();

        let mut errors = Vec::new();
        let mut warnings = Vec::new();
        validate_agent_yaml(&yaml_path, "my-agent", &mut errors, &mut warnings);

        assert!(errors.is_empty());
        assert_eq!(warnings.len(), 2); // missing model + missing instructions
    }
}