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
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
//! Push resources to Azure

mod agents;
mod collect;
mod credentials;
mod execute;
mod explain;
mod report;

use std::collections::HashMap;

use anyhow::Result;
use colored::Colorize;
use tracing::info;

use rigg_client::AzureSearchClient;
use rigg_core::resources::ResourceKind;
use rigg_core::resources::managed;
use rigg_core::service::ServiceDomain;
use rigg_core::state::Checksums;
use rigg_diff::Change;

use crate::cli::ResourceTypeFlags;
use crate::commands::common::{order_by_dependencies, resolve_resource_selection_from_flags};
use crate::commands::confirm::prompt_yes_no;
use crate::commands::load_config_and_env;

use collect::{build_local_managed_map, collect_push_resource};

pub async fn run(
    flags: &ResourceTypeFlags,
    recursive: bool,
    filter: Option<String>,
    force: bool,
    no_explain: bool,
    env_override: Option<&str>,
) -> Result<()> {
    let (project_root, config, env) = load_config_and_env(env_override)?;
    let files_root = config.files_root(&project_root);

    // AI explanations: on by default when ai: is configured, unless --no-explain
    let use_explain = !no_explain && crate::commands::ai::is_ai_active();

    // Push has no default fallback — user must specify resource types
    let selection = resolve_resource_selection_from_flags(flags, env.sync.include_preview, false);

    if selection.is_empty() {
        println!("No resource types specified. Use --all or specify types (e.g., --indexes)");
        return Ok(());
    }

    let kinds = selection.kinds();

    // Split kinds by service domain
    let search_kinds: Vec<ResourceKind> = kinds
        .iter()
        .filter(|k| k.domain() == ServiceDomain::Search)
        .copied()
        .collect();
    let has_foundry_kinds = kinds.iter().any(|k| k.domain() == ServiceDomain::Foundry);

    let primary_search_svc = env.primary_search_service();
    let server_name = primary_search_svc
        .map(|s| s.name.as_str())
        .unwrap_or("(none)");

    // Load checksums from last pull for conflict detection
    let checksums = Checksums::load_env(&project_root, &env.name).unwrap_or_default();

    // Collect resources to push
    let mut resources_to_push = Vec::new();
    let mut validation_errors = Vec::new();
    let mut recreate_candidates: Vec<(ResourceKind, String)> = Vec::new();
    let mut total_unchanged = 0;
    let mut change_details: HashMap<(ResourceKind, String), Vec<Change>> = HashMap::new();
    let mut remote_values: HashMap<(ResourceKind, String), serde_json::Value> = HashMap::new();
    let mut remote_conflicts: Vec<(ResourceKind, String)> = Vec::new();

    // --- Search resources ---
    if !search_kinds.is_empty() {
        let search_svc = primary_search_svc
            .ok_or_else(|| anyhow::anyhow!("No search service in environment '{}'", env.name))?;
        eprintln!("Comparing local resources against {}...", server_name);
        let client = AzureSearchClient::from_service_config(search_svc)?;

        info!(
            "Connected to {} using {}",
            server_name,
            client.auth_method()
        );

        let service_dir = env.search_service_dir(&files_root, search_svc);

        // Build managed map from local KS files
        let managed_map = build_local_managed_map(&service_dir);

        // Determine which kinds to push, handling --knowledge-sources expansion
        let has_ks = search_kinds.contains(&ResourceKind::KnowledgeSource);

        for kind in &search_kinds {
            // For standalone resource types, read from their standard directories
            // but skip managed resources (they'll be pushed via KS cascade)
            if *kind == ResourceKind::KnowledgeSource {
                // Read KS definitions from their subdirectories
                let ks_base = service_dir.join("agentic-retrieval/knowledge-sources");
                if !ks_base.exists() {
                    continue;
                }
                for entry in std::fs::read_dir(&ks_base)? {
                    let entry = entry?;
                    let path = entry.path();
                    if !path.is_dir() {
                        continue;
                    }
                    let ks_name = match path.file_name().and_then(|n| n.to_str()) {
                        Some(n) => n.to_string(),
                        None => continue,
                    };
                    if let Some(exact_name) = selection.name_filter(*kind) {
                        if ks_name != exact_name {
                            continue;
                        }
                    }
                    if let Some(ref pattern) = filter {
                        if !ks_name.contains(pattern) {
                            continue;
                        }
                    }
                    let ks_file = path.join(format!("{}.json", ks_name));
                    if !ks_file.exists() {
                        continue;
                    }
                    let content = std::fs::read_to_string(&ks_file)?;
                    let local: serde_json::Value = serde_json::from_str(&content)?;

                    let push_count_before = resources_to_push.len();
                    collect_push_resource(
                        &client,
                        *kind,
                        &ks_name,
                        local,
                        &mut resources_to_push,
                        &mut validation_errors,
                        &mut recreate_candidates,
                        &mut total_unchanged,
                        &mut change_details,
                        &mut remote_values,
                        &checksums,
                        &mut remote_conflicts,
                    )
                    .await;

                    // Check if this KS is being created (new) vs updated
                    let ks_is_new = resources_to_push.get(push_count_before).is_some_and(
                        |(k, n, _, exists)| {
                            *k == ResourceKind::KnowledgeSource && n == &ks_name && !exists
                        },
                    );

                    // Only collect managed sub-resources for EXISTING knowledge sources.
                    // When creating a new KS, Azure auto-provisions sub-resources — pushing
                    // them first would cause KS creation to fail ("resources already exist").
                    if has_ks && !ks_is_new {
                        let managed_subs = managed::read_managed_sub_resources(&path, &ks_name);
                        for (sub_kind, sub_name, sub_def) in managed_subs {
                            collect_push_resource(
                                &client,
                                sub_kind,
                                &sub_name,
                                sub_def,
                                &mut resources_to_push,
                                &mut validation_errors,
                                &mut recreate_candidates,
                                &mut total_unchanged,
                                &mut change_details,
                                &mut remote_values,
                                &checksums,
                                &mut remote_conflicts,
                            )
                            .await;
                        }
                    }
                }
                continue;
            }

            // For other resource types, read from standalone directories
            let resource_dir = service_dir.join(kind.directory_name());
            if !resource_dir.exists() {
                continue;
            }

            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"))?;

                // Skip managed resources in standalone dirs — they're pushed via KS cascade
                if let Some(ks_name) = managed::managing_ks(&managed_map, *kind, name) {
                    info!(
                        "Skipping managed {} '{}' (owned by knowledge source '{}') — use --knowledgesources to push",
                        kind.display_name(),
                        name,
                        ks_name
                    );
                    continue;
                }

                if let Some(exact_name) = selection.name_filter(*kind) {
                    if name != exact_name {
                        continue;
                    }
                }
                if let Some(ref pattern) = filter {
                    if !name.contains(pattern) {
                        continue;
                    }
                }

                let content = std::fs::read_to_string(&path)?;
                let local: serde_json::Value = serde_json::from_str(&content)?;

                collect_push_resource(
                    &client,
                    *kind,
                    name,
                    local,
                    &mut resources_to_push,
                    &mut validation_errors,
                    &mut recreate_candidates,
                    &mut total_unchanged,
                    &mut change_details,
                    &mut remote_values,
                    &checksums,
                    &mut remote_conflicts,
                )
                .await;
            }
        }

        // Handle drop-and-recreate for RequiresRecreate violations
        report::handle_recreate_candidates(
            &recreate_candidates,
            &mut resources_to_push,
            &service_dir,
            force,
        )?;
    }

    // --- Foundry agents ---
    if has_foundry_kinds && env.has_foundry() {
        agents::collect_foundry_agents(
            &env,
            &files_root,
            &selection,
            &filter,
            &mut resources_to_push,
            &mut total_unchanged,
            &mut change_details,
            &mut remote_values,
            &checksums,
            &mut remote_conflicts,
        )
        .await?;
    }

    // Recursive expansion: include deps and children
    if recursive && !resources_to_push.is_empty() {
        let initial_names: std::collections::HashSet<(ResourceKind, String)> = resources_to_push
            .iter()
            .map(|(k, n, _, _)| (*k, n.clone()))
            .collect();

        // Load all local resources across all kinds for expansion
        let all_kinds = if env.sync.include_preview {
            ResourceKind::all().to_vec()
        } else {
            ResourceKind::stable().to_vec()
        };

        let mut all_local = Vec::new();
        let recurse_search_svc = env.primary_search_service();
        for k in &all_kinds {
            let dir = if k.domain() == ServiceDomain::Search {
                if let Some(svc) = recurse_search_svc {
                    env.search_service_dir(&files_root, svc)
                        .join(k.directory_name())
                } else {
                    continue;
                }
            } else {
                // For Foundry kinds, skip here — agents are loaded separately
                continue;
            };
            if !dir.exists() {
                continue;
            }
            for entry in std::fs::read_dir(&dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.extension().and_then(|e| e.to_str()) != Some("json") {
                    continue;
                }
                let n = path
                    .file_stem()
                    .and_then(|n| n.to_str())
                    .unwrap_or("")
                    .to_string();
                if let Ok(content) = std::fs::read_to_string(&path) {
                    if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
                        all_local.push((*k, n, val));
                    }
                }
            }
        }

        let selected: Vec<_> = resources_to_push
            .iter()
            .map(|(k, n, v, _)| (*k, n.clone(), v.clone()))
            .collect();

        let expanded = rigg_core::copy::expand_recursive(&selected, &all_local);

        // Add newly discovered resources
        for (k, n, v) in expanded {
            if !initial_names.contains(&(k, n.clone())) {
                println!(
                    "  {} {} '{}' (included by --recursive)",
                    "+".green(),
                    k.display_name(),
                    n
                );
                resources_to_push.push((k, n, v, false));
            }
        }
    }

    // Report validation errors
    if !validation_errors.is_empty() {
        println!("Validation errors:");
        for error in &validation_errors {
            println!("  {}", error);
        }
        println!();
        anyhow::bail!(
            "Push blocked: {} validation error(s). Fix the issues above and try again.",
            validation_errors.len()
        );
    }

    if resources_to_push.is_empty() {
        if total_unchanged > 0 {
            println!(
                "All {} resource(s) match the server, nothing to push.",
                total_unchanged
            );
        } else {
            println!("No local resources found to push.");
        }
        return Ok(());
    }

    // Try AI narrative mode first when AI is enabled
    let used_ai_narrative = if use_explain {
        explain::generate_push_narrative(
            &resources_to_push,
            &change_details,
            &remote_values,
            total_unchanged,
        )
        .await
        .map(|narrative| {
            println!("{}", narrative);
        })
        .is_some()
    } else {
        false
    };

    // Fall back to non-AI output if narrative wasn't used
    if !used_ai_narrative {
        report::print_push_plan(&resources_to_push, &change_details, total_unchanged);
    }
    println!();

    // Show remote conflict warnings
    report::print_conflict_warnings(&remote_conflicts, &resources_to_push);

    // Confirm unless --force
    if !force && !prompt_yes_no("Proceed with push?")? {
        println!("Aborted.");
        return Ok(());
    }

    // Push resources in dependency order
    let ordered = order_by_dependencies(&resources_to_push);

    // Split ordered resources by domain for execution
    let search_resources: Vec<_> = ordered
        .iter()
        .filter(|(k, _, _, _)| k.domain() == ServiceDomain::Search)
        .collect();
    let foundry_resources: Vec<_> = ordered
        .iter()
        .filter(|(k, _, _, _)| k.domain() == ServiceDomain::Foundry)
        .collect();

    let mut success_count = 0;
    let mut error_count = 0;
    let mut pushed_resources: Vec<(ResourceKind, String)> = Vec::new();

    // Cache for discovered storage connection string (avoids repeated ARM calls)
    let mut cached_connection_string: Option<String> = None;

    // Push search resources
    if !search_resources.is_empty() {
        let (s, e, pushed) = execute::push_search_resources(
            &search_resources,
            &recreate_candidates,
            &env,
            &mut cached_connection_string,
        )
        .await?;
        success_count += s;
        error_count += e;
        pushed_resources.extend(pushed);
    }

    // Push Foundry agents
    if !foundry_resources.is_empty() && env.has_foundry() {
        let (s, e, pushed) = execute::push_foundry_agents(&foundry_resources, &env).await?;
        success_count += s;
        error_count += e;
        pushed_resources.extend(pushed);
    }

    // === Pull-back phase: re-fetch pushed resources to sync local files with server canonical form ===
    if !pushed_resources.is_empty() {
        execute::pullback_synced_resources(&pushed_resources, &project_root, &files_root, &env)
            .await?;
    }

    println!();
    println!(
        "Push complete: {} succeeded, {} failed",
        success_count, error_count
    );

    if error_count > 0 {
        std::process::exit(1);
    }

    Ok(())
}