rigg 2.0.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
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
//! Question protocol: the shared shape guided flows use to ask for input,
//! either interactively ([`InteractiveAsker`], backed by the `interactive`
//! wrappers) or scripted via `--answer` / `--answers-file`
//! ([`ScriptedAsker`]).
//!
//! A command that needs input builds one or more [`Question`]s and asks an
//! [`Asker`] for answers. In a script/agent context, [`ScriptedAsker`]
//! answers from a pre-supplied map and, when something is missing, returns
//! [`NeedsInput`] — a structured error the CLI turns into a `needs-input`
//! JSON document on stdout and exit code 6, so a caller can answer the
//! missing questions and re-run. Interactively, [`InteractiveAsker`] prefers
//! the same pre-supplied answers and only prompts for what's left.
//!
//! The guided flows that build `Question`s beyond the protected-environment
//! gate live in follow-up tasks.

use std::collections::BTreeMap;
use std::path::Path;

use anyhow::{Result, anyhow, bail};
use serde_json::{Value, json};

use super::{CommandError, interactive};

/// Id prefixes every `--answer <id>=<value>` is validated against at
/// startup. Later tasks and workstreams append their own prefixes
/// (`binding.`, `env.`, `promote.`, `auth.`, `new.`, …).
pub const KNOWN_ID_PREFIXES: &[&str] = &[
    "confirm.protected.",
    "binding.",
    "env.",
    "learn.",
    "promote.",
    "auth.",
];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuestionKind {
    Choice,
    Text,
    Confirm,
    ConfirmEnv,
}

impl QuestionKind {
    fn as_str(self) -> &'static str {
        match self {
            QuestionKind::Choice => "choice",
            QuestionKind::Text => "text",
            QuestionKind::Confirm => "confirm",
            QuestionKind::ConfirmEnv => "confirm-env",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
    pub value: String,
    pub label: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Question {
    pub id: String,
    pub kind: QuestionKind,
    pub prompt: String,
    pub candidates: Vec<Candidate>,
    pub allow_other: bool,
    pub default: Option<String>,
}

impl Question {
    pub fn choice(
        id: impl Into<String>,
        prompt: impl Into<String>,
        candidates: Vec<Candidate>,
    ) -> Self {
        Question {
            id: id.into(),
            kind: QuestionKind::Choice,
            prompt: prompt.into(),
            candidates,
            allow_other: false,
            default: None,
        }
    }

    pub fn text(id: impl Into<String>, prompt: impl Into<String>) -> Self {
        Question {
            id: id.into(),
            kind: QuestionKind::Text,
            prompt: prompt.into(),
            candidates: Vec::new(),
            allow_other: false,
            default: None,
        }
    }

    pub fn confirm(id: impl Into<String>, prompt: impl Into<String>, default_yes: bool) -> Self {
        Question {
            id: id.into(),
            kind: QuestionKind::Confirm,
            prompt: prompt.into(),
            candidates: Vec::new(),
            allow_other: false,
            default: Some(if default_yes { "yes" } else { "no" }.to_string()),
        }
    }

    /// A protected-environment confirmation. `id` = `confirm.protected.<env>`;
    /// the answer must equal `env` exactly (see [`coerce`]).
    pub fn confirm_env(env: &str, operation: &str) -> Self {
        Question {
            id: format!("confirm.protected.{env}"),
            kind: QuestionKind::ConfirmEnv,
            prompt: format!(
                "Environment '{env}' is protected. Type its name to confirm {operation}:"
            ),
            candidates: Vec::new(),
            allow_other: false,
            default: None,
        }
    }

    pub fn with_default(mut self, d: impl Into<String>) -> Self {
        self.default = Some(d.into());
        self
    }

    pub fn allow_other(mut self) -> Self {
        self.allow_other = true;
        self
    }

    /// Hand-built serialization for the `needs-input` protocol document:
    /// `candidates` is omitted when empty, `default` when `None`, and
    /// `allow_other` is present only when `true`.
    fn to_value(&self) -> Value {
        let mut obj = serde_json::Map::new();
        obj.insert("id".to_string(), json!(self.id));
        obj.insert("kind".to_string(), json!(self.kind.as_str()));
        obj.insert("prompt".to_string(), json!(self.prompt));
        if !self.candidates.is_empty() {
            obj.insert(
                "candidates".to_string(),
                json!(
                    self.candidates
                        .iter()
                        .map(|c| json!({"value": c.value, "label": c.label}))
                        .collect::<Vec<_>>()
                ),
            );
        }
        if self.allow_other {
            obj.insert("allow_other".to_string(), json!(true));
        }
        if let Some(default) = &self.default {
            obj.insert("default".to_string(), json!(default));
        }
        Value::Object(obj)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Answer {
    Choice(String),
    Text(String),
    Confirm(bool),
}

impl Answer {
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Answer::Choice(s) | Answer::Text(s) => Some(s.as_str()),
            Answer::Confirm(_) => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Answer::Confirm(b) => Some(*b),
            _ => None,
        }
    }
}

pub trait Asker {
    fn ask(&mut self, q: &Question) -> Result<Answer>;
    fn ask_all(&mut self, qs: &[Question]) -> Result<Vec<Answer>>;
}

/// Answers a fixed set of [`Question`]s from a pre-supplied map
/// (`--answer id=value` / `--answers-file`). Anything missing is collected
/// into a single [`NeedsInput`] error rather than failing on the first gap,
/// so a caller sees every outstanding question in one round-trip. A
/// malformed *supplied* answer is collected the same way and reported
/// together with the rest — see [`ScriptedAsker::ask_all`] for the
/// precedence between the two.
pub struct ScriptedAsker {
    answers: BTreeMap<String, String>,
    command: String,
    context: Value,
}

impl ScriptedAsker {
    pub fn new(
        answers: BTreeMap<String, String>,
        command: impl Into<String>,
        context: Value,
    ) -> Self {
        ScriptedAsker {
            answers,
            command: command.into(),
            context,
        }
    }

    fn needs_input(&self, questions: Vec<Question>) -> anyhow::Error {
        anyhow::Error::new(NeedsInput {
            command: self.command.clone(),
            context: self.context.clone(),
            questions,
        })
    }
}

impl Asker for ScriptedAsker {
    fn ask(&mut self, q: &Question) -> Result<Answer> {
        match self.answers.get(&q.id) {
            Some(raw) => coerce(q, raw),
            None => Err(self.needs_input(vec![q.clone()])),
        }
    }

    /// Answers every question it can and accumulates the rest, so one
    /// round-trip reports everything that is wrong at once: questions with
    /// no supplied answer become [`NeedsInput`], answers that fail
    /// [`coerce`] become a usage error.
    ///
    /// Precedence when both happen: the **bad answers win**. A caller that
    /// supplied a wrong value gets `CommandError::Usage` (exit 2) naming
    /// every invalid answer — re-running with the missing answers alone
    /// would fail again on the same bad value, so the usage error is the
    /// actionable one. Only when every supplied answer coerces cleanly and
    /// something is still missing does this return `NeedsInput` (exit 6).
    fn ask_all(&mut self, qs: &[Question]) -> Result<Vec<Answer>> {
        let mut answers = Vec::with_capacity(qs.len());
        let mut missing = Vec::new();
        let mut invalid = Vec::new();
        for q in qs {
            match self.answers.get(&q.id) {
                Some(raw) => match coerce(q, raw) {
                    Ok(answer) => answers.push(answer),
                    Err(e) => invalid.push(format!("{e:#}")),
                },
                None => missing.push(q.clone()),
            }
        }
        if !invalid.is_empty() {
            return Err(anyhow!(CommandError::Usage(format!(
                "invalid answer(s): {}",
                invalid.join("; ")
            ))));
        }
        if !missing.is_empty() {
            return Err(self.needs_input(missing));
        }
        Ok(answers)
    }
}

/// Answers [`Question`]s interactively via the `inquire`-backed wrappers in
/// [`super::interactive`], preferring any pre-supplied answer (`--answer` /
/// `--answers-file`, or `confirm_protected_env`'s `--confirm-env` sugar) so
/// a caller never gets prompted for something it already told us.
pub struct InteractiveAsker {
    answers: BTreeMap<String, String>,
    plain: bool,
}

impl InteractiveAsker {
    pub fn new(answers: BTreeMap<String, String>, plain: bool) -> Self {
        InteractiveAsker { answers, plain }
    }
}

/// Row appended to a `Choice` question's options when it `allow_other`s a
/// free-form value; picking it falls through to a text prompt.
const ENTER_ANOTHER_VALUE: &str = "enter another value";

impl Asker for InteractiveAsker {
    fn ask(&mut self, q: &Question) -> Result<Answer> {
        if let Some(raw) = self.answers.get(&q.id) {
            return coerce(q, raw);
        }
        match q.kind {
            QuestionKind::Choice => {
                // Resolve the pick by index, not by matching the label text
                // back against the candidates: a duplicate label, or a
                // candidate literally labelled like the sentinel row, must
                // not be able to mis-route. The sentinel is recognised by
                // position (always the last row), not by string equality.
                let mut labels: Vec<String> =
                    q.candidates.iter().map(|c| c.label.clone()).collect();
                if q.allow_other {
                    labels.push(ENTER_ANOTHER_VALUE.to_string());
                }
                let index = interactive::select_index(&q.prompt, labels, self.plain)?;
                if q.allow_other && index == q.candidates.len() {
                    Ok(Answer::Choice(interactive::text(&q.prompt, self.plain)?))
                } else {
                    Ok(Answer::Choice(q.candidates[index].value.clone()))
                }
            }
            QuestionKind::Text => {
                let raw = match &q.default {
                    Some(default) => {
                        interactive::text_with_default(&q.prompt, default, self.plain)?
                    }
                    None => interactive::text(&q.prompt, self.plain)?,
                };
                Ok(Answer::Text(raw))
            }
            QuestionKind::Confirm => {
                let default_yes = q.default.as_deref() == Some("yes");
                let answered = if default_yes {
                    interactive::confirm_default_yes(&q.prompt, self.plain)?
                } else {
                    interactive::confirm_default_no(&q.prompt, self.plain)?
                };
                Ok(Answer::Confirm(answered))
            }
            QuestionKind::ConfirmEnv => {
                let env =
                    q.id.strip_prefix("confirm.protected.")
                        .unwrap_or(q.id.as_str());
                let raw = interactive::text(&q.prompt, self.plain)?;
                Ok(Answer::Confirm(raw.trim() == env))
            }
        }
    }

    fn ask_all(&mut self, qs: &[Question]) -> Result<Vec<Answer>> {
        qs.iter().map(|q| self.ask(q)).collect()
    }
}

/// Structured "I need more input" error. The CLI prints [`Self::to_json`]
/// to stdout and maps this to exit code 6.
#[derive(Debug, thiserror::Error)]
pub struct NeedsInput {
    pub command: String,
    pub context: Value,
    pub questions: Vec<Question>,
}

impl std::fmt::Display for NeedsInput {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ids = self
            .questions
            .iter()
            .map(|q| q.id.as_str())
            .collect::<Vec<_>>()
            .join(", ");
        write!(
            f,
            "{} question(s) need an answer: {ids}",
            self.questions.len()
        )
    }
}

impl NeedsInput {
    /// The `needs-input` protocol document printed to stdout.
    pub fn to_json(&self) -> Value {
        json!({
            "status": "needs-input",
            "command": self.command,
            "context": self.context,
            "questions": self.questions.iter().map(Question::to_value).collect::<Vec<_>>(),
        })
    }
}

/// Parse a `--answer id=value` flag.
pub fn parse_answer_flag(s: &str) -> Result<(String, String)> {
    match s.split_once('=') {
        Some((id, value)) if !id.is_empty() => Ok((id.to_string(), value.to_string())),
        _ => bail!("invalid --answer '{s}': expected <id>=<value>"),
    }
}

/// Load answers from an optional JSON file (`{"<id>": "<value>", ...}`)
/// merged with `--answer` flags, which take precedence over the file.
pub fn load_answers(flags: &[String], file: Option<&Path>) -> Result<BTreeMap<String, String>> {
    let mut map = BTreeMap::new();
    if let Some(path) = file {
        let text = std::fs::read_to_string(path)
            .map_err(|e| anyhow::anyhow!("reading answers file '{}': {e}", path.display()))?;
        let parsed: BTreeMap<String, String> = serde_json::from_str(&text)
            .map_err(|e| anyhow::anyhow!("parsing answers file '{}': {e}", path.display()))?;
        map.extend(parsed);
    }
    for flag in flags {
        let (id, value) = parse_answer_flag(flag)?;
        map.insert(id, value);
    }
    Ok(map)
}

/// Coerce a raw string answer into the [`Answer`] variant appropriate for
/// `q.kind`, validating against candidates / confirm semantics / the
/// protected-env name as needed.
pub fn coerce(q: &Question, raw: &str) -> Result<Answer> {
    match q.kind {
        QuestionKind::Choice => {
            if q.candidates.iter().any(|c| c.value == raw) || q.allow_other {
                Ok(Answer::Choice(raw.to_string()))
            } else {
                bail!(
                    "invalid answer for '{}': '{raw}' is not one of the offered candidates",
                    q.id
                )
            }
        }
        QuestionKind::Text => Ok(Answer::Text(raw.to_string())),
        QuestionKind::Confirm => match raw.to_ascii_lowercase().as_str() {
            "yes" | "y" | "true" => Ok(Answer::Confirm(true)),
            "no" | "n" | "false" => Ok(Answer::Confirm(false)),
            _ => bail!("invalid answer for '{}': expected yes/no", q.id),
        },
        QuestionKind::ConfirmEnv => {
            let env =
                q.id.strip_prefix("confirm.protected.")
                    .unwrap_or(q.id.as_str());
            if raw == env {
                Ok(Answer::Confirm(true))
            } else {
                bail!(
                    "invalid answer for '{}': must type the environment name '{env}' exactly",
                    q.id
                )
            }
        }
    }
}

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

    #[test]
    fn scripted_asker_answers_from_map_and_collects_the_rest() {
        let mut asker = ScriptedAsker::new(
            [("binding.prod.docs-storage".to_string(), "same".to_string())]
                .into_iter()
                .collect(),
            "promote",
            json!({"from": "dev", "to": "prod"}),
        );
        let q1 = Question::choice(
            "binding.prod.docs-storage",
            "Which storage?",
            vec![Candidate {
                value: "same".into(),
                label: "same as dev".into(),
            }],
        );
        let q2 = Question::text("binding.prod.enrich-fn", "Function app for prod?");
        assert_eq!(asker.ask(&q1).unwrap().as_str(), Some("same"));
        let err = asker.ask_all(&[q1.clone(), q2.clone()]).unwrap_err();
        let ni = err.downcast_ref::<NeedsInput>().expect("NeedsInput");
        assert_eq!(
            ni.questions
                .iter()
                .map(|q| q.id.as_str())
                .collect::<Vec<_>>(),
            vec!["binding.prod.enrich-fn"]
        );
        let doc = ni.to_json();
        assert_eq!(doc["status"], "needs-input");
        assert_eq!(doc["command"], "promote");
        assert_eq!(doc["questions"][0]["kind"], "text");
        assert!(
            doc["questions"][0].get("candidates").is_none(),
            "omitted when empty"
        );
    }

    #[test]
    fn scripted_ask_all_reports_bad_answers_before_missing_ones() {
        let mut asker = ScriptedAsker::new(
            [("confirm.protected.prod".to_string(), "prd".to_string())]
                .into_iter()
                .collect(),
            "push",
            json!({"env": "prod"}),
        );
        let bad = Question::confirm_env("prod", "push");
        let missing = Question::text("binding.prod.enrich-fn", "Function app for prod?");
        let err = asker.ask_all(&[bad, missing]).unwrap_err();
        assert!(
            err.downcast_ref::<NeedsInput>().is_none(),
            "a bad answer outranks the missing question"
        );
        match err.downcast_ref::<CommandError>() {
            Some(CommandError::Usage(msg)) => {
                assert!(msg.starts_with("invalid answer(s): "), "got: {msg}");
                assert!(msg.contains("confirm.protected.prod"), "got: {msg}");
            }
            other => panic!("expected a usage error, got {other:?}"),
        }
    }

    #[test]
    fn coerce_enforces_candidates_and_confirm_env() {
        let q = Question::choice(
            "q",
            "?",
            vec![Candidate {
                value: "a".into(),
                label: "A".into(),
            }],
        );
        assert!(coerce(&q, "b").is_err());
        assert_eq!(
            coerce(&q.clone().allow_other(), "b").unwrap().as_str(),
            Some("b")
        );
        let c = Question::confirm("c", "?", true);
        assert_eq!(coerce(&c, "no").unwrap().as_bool(), Some(false));
        let e = Question::confirm_env("prod", "push");
        assert_eq!(e.id, "confirm.protected.prod");
        assert!(coerce(&e, "prd").is_err());
        assert_eq!(coerce(&e, "prod").unwrap().as_bool(), Some(true));
    }

    #[test]
    fn interactive_asker_uses_presupplied_answers_without_prompting() {
        // No TTY in tests: a prompt would fail. A pre-supplied answer must
        // short-circuit before any `interactive::*` call is made.
        let mut a = InteractiveAsker::new(
            [("confirm.protected.prod".to_string(), "prod".to_string())]
                .into_iter()
                .collect(),
            true,
        );
        let q = Question::confirm_env("prod", "push");
        assert_eq!(a.ask(&q).unwrap().as_bool(), Some(true));
    }

    #[test]
    fn load_answers_merges_flags_over_file_and_rejects_bad_flags() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("a.json");
        std::fs::write(&f, r#"{"x": "1", "y": "2"}"#).unwrap();
        let m = load_answers(&["y=3".to_string()], Some(&f)).unwrap();
        assert_eq!(m["x"], "1");
        assert_eq!(m["y"], "3");
        assert!(parse_answer_flag("novalue").is_err());
    }
}