Skip to main content

gemini_adk_fluent_rs/spec/
authoring.rs

1//! The authoring interface a coding harness uses to build a session spec.
2//!
3//! A harness (a coding agent, an IDE, a CLI wizard) edits `agent.json` on the
4//! user's behalf. These operations tell it what can be written, what is wrong
5//! with the document, and which decisions are still the user's to make:
6//!
7//! - [`catalog`] lists the vocabulary: voices, guard atoms, policies, tool
8//!   bindings, resume policies, question rules and diagnostic codes.
9//! - [`check`] validates a document and reports structured [`Diagnostic`]s.
10//!   Each has a JSON pointer and, where the repair is mechanical, a [`Fix`]
11//!   expressed as JSON-patch operations.
12//! - [`plan`] lists the open decisions as [`Question`]s. Every option carries
13//!   the patch that records it.
14//! - [`answer`] applies chosen options. It plans again before each answer,
15//!   so every patch is computed against the current document.
16//! - [`apply_patch`] applies JSON-patch operations (RFC 6902 `add`,
17//!   `replace`, `remove`) atomically.
18//!
19//! All of them take the document as a JSON value, so a document that does
20//! not deserialize still gets diagnostics.
21//!
22//! Fixes in one [`CheckReport`] are each computed against the checked
23//! document. Apply one, then check again: two fixes from the same report can
24//! touch the same array.
25//!
26//! ```
27//! use gemini_adk_fluent_rs::spec::authoring::{self, Answer, Decisions};
28//! use serde_json::json;
29//!
30//! let doc = json!({ "name": "", "instruction": "Answer questions about opening hours." });
31//! let plan = authoring::plan(&doc, &Decisions::new());
32//! assert_eq!(plan.questions[0].id, "name");
33//!
34//! let answered = authoring::answer(
35//!     &doc,
36//!     &[Answer::with_value("name", json!("hours-line"))],
37//!     &Decisions::new(),
38//! )
39//! .unwrap();
40//! assert_eq!(answered.spec["name"], "hours-line");
41//! ```
42
43use std::collections::{BTreeMap, BTreeSet};
44
45use serde::{Deserialize, Serialize};
46use serde_json::{Value, json};
47
48use super::{MEMORY_TOOL_NAMES, RUNTIME_WRITTEN, SessionSpec};
49use crate::conversation::StageSpec;
50use crate::policy::Policy;
51use gemini_adk_rs::utils::text::levenshtein;
52
53/// Version of the authoring interface. Bumped when an operation's output
54/// changes incompatibly.
55pub const AUTHORING_VERSION: u32 = 1;
56
57/// The placeholder an option's patch uses for the user's value. A string
58/// equal to it is replaced by [`Answer::value`].
59pub const ANSWER_PLACEHOLDER: &str = "$answer";
60
61/// Name of the extractor that question and fix patches add boolean caller
62/// signals to (confirmations, intents).
63pub const SIGNALS_EXTRACTOR: &str = "caller_signals";
64
65// ---------------------------------------------------------------------------
66// JSON patch
67// ---------------------------------------------------------------------------
68
69/// One JSON-patch operation (RFC 6902 subset). `path` is a JSON pointer.
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
71#[serde(tag = "op", rename_all = "snake_case")]
72pub enum PatchOp {
73    /// Insert into an array (`/-` appends) or set an object member.
74    Add {
75        /// Target location.
76        path: String,
77        /// Value to add.
78        value: Value,
79    },
80    /// Replace an existing value.
81    Replace {
82        /// Target location; must exist.
83        path: String,
84        /// Replacement value.
85        value: Value,
86    },
87    /// Remove an existing value.
88    Remove {
89        /// Target location; must exist.
90        path: String,
91    },
92}
93
94impl PatchOp {
95    /// The operation's target pointer.
96    pub fn path(&self) -> &str {
97        match self {
98            PatchOp::Add { path, .. }
99            | PatchOp::Replace { path, .. }
100            | PatchOp::Remove { path } => path,
101        }
102    }
103}
104
105/// Why a patch could not be applied.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct PatchError {
108    /// Index of the failing operation.
109    pub index: usize,
110    /// Its target pointer.
111    pub path: String,
112    /// What went wrong.
113    pub reason: String,
114}
115
116impl std::fmt::Display for PatchError {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        write!(
119            f,
120            "patch operation {} at '{}': {}",
121            self.index, self.path, self.reason
122        )
123    }
124}
125
126impl std::error::Error for PatchError {}
127
128/// Apply `ops` in order to a copy of `doc`. Either every operation applies
129/// or the document is returned unchanged inside the error.
130pub fn apply_patch(doc: &Value, ops: &[PatchOp]) -> Result<Value, PatchError> {
131    let mut out = doc.clone();
132    for (index, op) in ops.iter().enumerate() {
133        apply_op(&mut out, op).map_err(|reason| PatchError {
134            index,
135            path: op.path().to_string(),
136            reason,
137        })?;
138    }
139    Ok(out)
140}
141
142fn apply_op(doc: &mut Value, op: &PatchOp) -> Result<(), String> {
143    let path = op.path();
144    if !path.is_empty() && !path.starts_with('/') {
145        return Err("a JSON pointer must be empty or start with '/'".into());
146    }
147    match op {
148        PatchOp::Replace { value, .. } => {
149            let target = doc
150                .pointer_mut(path)
151                .ok_or_else(|| "no value at this path".to_string())?;
152            *target = value.clone();
153            Ok(())
154        }
155        PatchOp::Add { value, .. } => {
156            if path.is_empty() {
157                *doc = value.clone();
158                return Ok(());
159            }
160            let (parent, last) = split_pointer(path);
161            match doc.pointer_mut(parent) {
162                Some(Value::Object(map)) => {
163                    map.insert(last, value.clone());
164                    Ok(())
165                }
166                Some(Value::Array(items)) => {
167                    if last == "-" {
168                        items.push(value.clone());
169                        return Ok(());
170                    }
171                    let index = array_index(&last)?;
172                    if index > items.len() {
173                        return Err(format!("index {index} is past the end of the array"));
174                    }
175                    items.insert(index, value.clone());
176                    Ok(())
177                }
178                Some(_) => Err("the parent is not an object or array".into()),
179                None => Err("the parent does not exist".into()),
180            }
181        }
182        PatchOp::Remove { .. } => {
183            if path.is_empty() {
184                return Err("cannot remove the whole document".into());
185            }
186            let (parent, last) = split_pointer(path);
187            match doc.pointer_mut(parent) {
188                Some(Value::Object(map)) => map
189                    .remove(&last)
190                    .map(|_| ())
191                    .ok_or_else(|| "no value at this path".to_string()),
192                Some(Value::Array(items)) => {
193                    let index = array_index(&last)?;
194                    if index >= items.len() {
195                        return Err("no value at this path".into());
196                    }
197                    items.remove(index);
198                    Ok(())
199                }
200                _ => Err("no value at this path".into()),
201            }
202        }
203    }
204}
205
206/// Split a non-empty pointer into its (still escaped) parent and its
207/// unescaped last token.
208fn split_pointer(path: &str) -> (&str, String) {
209    let cut = path.rfind('/').unwrap_or(0);
210    let last = path[cut + 1..].replace("~1", "/").replace("~0", "~");
211    (&path[..cut], last)
212}
213
214fn array_index(token: &str) -> Result<usize, String> {
215    if token.len() > 1 && token.starts_with('0') {
216        return Err(format!("'{token}' is not a valid array index"));
217    }
218    token
219        .parse()
220        .map_err(|_| format!("'{token}' is not a valid array index"))
221}
222
223/// Escape one reference token for a JSON pointer.
224fn escape(token: &str) -> String {
225    token.replace('~', "~0").replace('/', "~1")
226}
227
228/// An `add` that appends `value` to the array at `array`, creating the array
229/// when it does not exist yet.
230fn append(doc: &Value, array: &str, value: Value) -> PatchOp {
231    if doc.pointer(array).is_some_and(Value::is_array) {
232        PatchOp::Add {
233            path: format!("{array}/-"),
234            value,
235        }
236    } else {
237        PatchOp::Add {
238            path: array.to_string(),
239            value: json!([value]),
240        }
241    }
242}
243
244fn add(path: impl Into<String>, value: Value) -> PatchOp {
245    PatchOp::Add {
246        path: path.into(),
247        value,
248    }
249}
250
251// ---------------------------------------------------------------------------
252// Catalog
253// ---------------------------------------------------------------------------
254
255/// One authorable item: its name, what it means and an example.
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
257pub struct CatalogEntry {
258    /// Name as written in the spec (or the id pattern, for questions).
259    pub name: String,
260    /// What it does.
261    pub meaning: String,
262    /// A valid example, when one applies.
263    #[serde(default, skip_serializing_if = "Value::is_null")]
264    pub example: Value,
265}
266
267/// The vocabulary a harness may write. The full document shape is the spec's
268/// JSON Schema (`SessionSpec::json_schema`, `adk spec schema`).
269#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
270pub struct Catalog {
271    /// [`AUTHORING_VERSION`].
272    pub version: u32,
273    /// Output modalities.
274    pub modalities: Vec<String>,
275    /// Prebuilt voice names. Other names are passed through to the provider.
276    pub voices: Vec<String>,
277    /// Guard atoms and combinators.
278    pub guards: Vec<CatalogEntry>,
279    /// Conversation policies.
280    pub policies: Vec<CatalogEntry>,
281    /// Ways to implement a declared tool.
282    pub tool_bindings: Vec<CatalogEntry>,
283    /// What happens when a digression closes.
284    pub resume: Vec<CatalogEntry>,
285    /// Question rules [`plan`] can raise, by id pattern.
286    pub questions: Vec<CatalogEntry>,
287    /// Diagnostic codes [`check`] can report.
288    pub diagnostics: Vec<CatalogEntry>,
289}
290
291fn entry(name: &str, meaning: &str, example: Value) -> CatalogEntry {
292    CatalogEntry {
293        name: name.into(),
294        meaning: meaning.into(),
295        example,
296    }
297}
298
299const VOICES: [&str; 5] = ["Aoede", "Charon", "Fenrir", "Kore", "Puck"];
300
301/// The authoring vocabulary.
302pub fn catalog() -> Catalog {
303    Catalog {
304        version: AUTHORING_VERSION,
305        modalities: vec!["text".into(), "audio".into()],
306        voices: VOICES.iter().map(|v| (*v).to_string()).collect(),
307        guards: vec![
308            entry(
309                "always",
310                "Always holds. Rejected as a commit guard.",
311                json!("always"),
312            ),
313            entry(
314                "is_true",
315                "The state key is exactly true.",
316                json!({ "is_true": "user_confirmed" }),
317            ),
318            entry(
319                "is_set",
320                "The state key has a value.",
321                json!({ "is_set": "party_size" }),
322            ),
323            entry(
324                "eq",
325                "The state key equals the value.",
326                json!({ "eq": ["tier", "gold"] }),
327            ),
328            entry(
329                "captured",
330                "Every listed state key has a value.",
331                json!({ "captured": ["party_size", "slot"] }),
332            ),
333            entry(
334                "called_ok",
335                "The tool has run successfully.",
336                json!({ "called_ok": "book_table" }),
337            ),
338            entry(
339                "done",
340                "The stage is complete.",
341                json!({ "done": "collect" }),
342            ),
343            entry(
344                "decided",
345                "A decision model's answer to a question in `decisions`, about the \
346                 caller's latest words: a question id (yes, picked, or scored), or \
347                 {question: true | false | option | {\"at_least\": n} | {\"at_most\": n}}. \
348                 Asked by the runtime when the flow can act on it; an earlier answer \
349                 does not count.",
350                json!({ "decided": { "next_step": "book" } }),
351            ),
352            entry(
353                "all",
354                "Every guard holds.",
355                json!({ "all": [{ "is_set": "slot" }, { "is_true": "user_confirmed" }] }),
356            ),
357            entry(
358                "any",
359                "At least one guard holds.",
360                json!({ "any": [{ "is_true": "intent:cancel" }, { "is_true": "intent:human_agent" }] }),
361            ),
362            entry(
363                "not",
364                "The guard does not hold.",
365                json!({ "not": { "is_true": "large_party" } }),
366            ),
367        ],
368        policies: vec![
369            entry(
370                "redact",
371                "Redact these state keys in the journal, persistence snapshots and \
372                 extraction events. Transcript text is not covered.",
373                json!({ "kind": "redact", "keys": ["card_number"] }),
374            ),
375            entry(
376                "safety_handoff",
377                "End the conversation when any `intent:{name}` flag becomes true. \
378                 Something must write the flag, such as a signal extractor. Its \
379                 digression restricts no tools on the turn it is entered; a handoff \
380                 digression whose stage admits only a transfer tool does not have that gap.",
381                json!({ "kind": "safety_handoff", "intents": ["human_agent"] }),
382            ),
383            entry(
384                "commit",
385                "Idempotency and compensation for a committing tool.",
386                json!({
387                    "kind": "commit",
388                    "tool": "book_table",
389                    "idempotency_key": "{booking_ref}",
390                    "compensate_with": "cancel_booking"
391                }),
392            ),
393        ],
394        tool_bindings: vec![
395            entry(
396                "stub",
397                "No binding. Codegen writes a typed stub that you implement.",
398                json!({
399                    "name": "check_availability",
400                    "description": "Check table availability for a date and time.",
401                    "parameters": {
402                        "type": "object",
403                        "properties": { "datetime": { "type": "string" } },
404                        "required": ["datetime"]
405                    }
406                }),
407            ),
408            entry(
409                "mock",
410                "A canned response and state writes, for offline runs and demos.",
411                json!({
412                    "name": "check_availability",
413                    "response": { "available": true },
414                    "set_state": { "availability_checked": true }
415                }),
416            ),
417            entry(
418                "http",
419                "Call an HTTP endpoint with the arguments.",
420                json!({
421                    "name": "book_table",
422                    "http": { "method": "POST", "url": "https://bookings.example.com/v1/book" }
423                }),
424            ),
425            entry(
426                "mcp",
427                "Call the tool of the same name on an MCP server (a command line or an \
428                 http(s) URL).",
429                json!({ "name": "book_table", "mcp": "python tools/server.py" }),
430            ),
431        ],
432        resume: vec![
433            entry(
434                "previous",
435                "The layer beneath continues where it was suspended (default).",
436                json!("previous"),
437            ),
438            entry(
439                "restart",
440                "The layer beneath restarts its stages. Filled slots stay filled.",
441                json!("restart"),
442            ),
443            entry(
444                "terminate",
445                "The conversation ends and `flow:terminated` becomes true.",
446                json!("terminate"),
447            ),
448        ],
449        questions: QUESTION_RULES
450            .iter()
451            .map(|(name, meaning)| entry(name, meaning, Value::Null))
452            .collect(),
453        diagnostics: DIAGNOSTIC_CODES
454            .iter()
455            .map(|(name, meaning)| entry(name, meaning, Value::Null))
456            .collect(),
457    }
458}
459
460const QUESTION_RULES: [(&str, &str); 10] = [
461    ("name", "The app has no name."),
462    ("instruction", "The app has no base instruction."),
463    (
464        "tool_description:<tool>",
465        "A declared tool has no description, so the model cannot tell when to call it.",
466    ),
467    (
468        "commit_gate:<tool>",
469        "A conversation allows a tool that looks like it changes something, and no stage \
470         commits it behind a guard.",
471    ),
472    (
473        "redact:<slot>",
474        "A collected slot looks sensitive and no redact policy covers it.",
475    ),
476    ("voice", "An audio app has no voice."),
477    (
478        "greeting",
479        "An audio app has no greeting, so it waits for the caller to speak first.",
480    ),
481    (
482        "escalation",
483        "The conversation has no way out: no digression, safety handoff or repair escalation.",
484    ),
485    (
486        "disclosure",
487        "An audio conversation reads no fixed text, such as a recording or AI disclosure.",
488    ),
489    (
490        "tool_binding:<tool>",
491        "A declared tool has no implementation: no HTTP or MCP binding and no canned response.",
492    ),
493];
494
495const DIAGNOSTIC_CODES: [(&str, &str); 8] = [
496    ("invalid_json", "The text is not JSON."),
497    ("not_an_object", "The document is not a JSON object."),
498    (
499        "invalid_spec",
500        "The document does not deserialize as a session spec.",
501    ),
502    (
503        "unknown_field",
504        "A field is not part of the spec and is ignored. Usually a misspelling.",
505    ),
506    (
507        "unknown_tool",
508        "The conversation references a tool that is not declared.",
509    ),
510    (
511        "unwritten_key",
512        "A guard reads a state key that nothing writes, so it can never become true.",
513    ),
514    (
515        "unpinned_extraction_model",
516        "Extraction names no model, so it runs on the host default, a rolling alias whose model and latency change; every turn waits for it.",
517    ),
518    (
519        "validation",
520        "A problem reported by spec validation, passed through as text.",
521    ),
522];
523
524// ---------------------------------------------------------------------------
525// Check
526// ---------------------------------------------------------------------------
527
528/// How serious a diagnostic is.
529#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
530#[serde(rename_all = "snake_case")]
531pub enum Severity {
532    /// The spec cannot run as written.
533    Error,
534    /// The spec runs but probably not as intended.
535    Warning,
536}
537
538/// A mechanical repair for a diagnostic.
539#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
540pub struct Fix {
541    /// What the patch does.
542    pub description: String,
543    /// The patch, computed against the checked document.
544    pub patch: Vec<PatchOp>,
545}
546
547/// One problem found by [`check`].
548#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
549pub struct Diagnostic {
550    /// Severity.
551    pub severity: Severity,
552    /// Stable code; see [`Catalog::diagnostics`].
553    pub code: String,
554    /// JSON pointer to the offending value, when known.
555    #[serde(default, skip_serializing_if = "Option::is_none")]
556    pub path: Option<String>,
557    /// What is wrong.
558    pub message: String,
559    /// A mechanical repair, when one exists.
560    #[serde(default, skip_serializing_if = "Option::is_none")]
561    pub fix: Option<Fix>,
562}
563
564/// The result of [`check`].
565#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
566pub struct CheckReport {
567    /// No error-severity diagnostics.
568    pub valid: bool,
569    /// Errors first, then warnings.
570    pub diagnostics: Vec<Diagnostic>,
571}
572
573impl CheckReport {
574    fn new(mut diagnostics: Vec<Diagnostic>) -> Self {
575        diagnostics.sort_by_key(|d| d.severity != Severity::Error);
576        let valid = diagnostics.iter().all(|d| d.severity != Severity::Error);
577        Self { valid, diagnostics }
578    }
579}
580
581fn diagnostic(
582    severity: Severity,
583    code: &str,
584    path: Option<String>,
585    message: impl Into<String>,
586    fix: Option<Fix>,
587) -> Diagnostic {
588    Diagnostic {
589        severity,
590        code: code.into(),
591        path,
592        message: message.into(),
593        fix,
594    }
595}
596
597/// Validate `doc` and report structured diagnostics.
598///
599/// Conversation specs get pointer-level diagnostics for unknown tools and
600/// unwritten guard keys, including digression triggers and safety-handoff
601/// intents. Everything else that [`SessionSpec::validate`] reports is passed
602/// through with code `validation`.
603pub fn check(doc: &Value) -> CheckReport {
604    let Some(object) = doc.as_object() else {
605        return CheckReport::new(vec![diagnostic(
606            Severity::Error,
607            "not_an_object",
608            Some(String::new()),
609            "a spec must be a JSON object",
610            None,
611        )]);
612    };
613    let bare_flow = !object.contains_key("flow") && object.contains_key("steps");
614    let mut diagnostics = Vec::new();
615    if !bare_flow {
616        unknown_fields(doc, &mut diagnostics);
617    }
618    let spec = match SessionSpec::from_value(doc.clone()) {
619        Ok(spec) => spec,
620        Err(message) => {
621            diagnostics.push(diagnostic(
622                Severity::Error,
623                "invalid_spec",
624                None,
625                message,
626                None,
627            ));
628            return CheckReport::new(diagnostics);
629        }
630    };
631
632    // Messages the structured checks already report with a path.
633    let mut covered = Vec::new();
634    unpinned_extraction_model(doc, &spec, &mut diagnostics, &mut covered);
635    if spec.conversation.is_some() {
636        unknown_tools(doc, &spec, &mut diagnostics, &mut covered);
637        unwritten_keys(doc, &spec, &mut diagnostics, &mut covered);
638    }
639    let validation = spec.validate();
640    let passes = |message: &String| !covered.iter().any(|c| message.contains(c.as_str()));
641    for message in validation.errors.into_iter().filter(passes) {
642        diagnostics.push(diagnostic(
643            Severity::Error,
644            "validation",
645            None,
646            message,
647            None,
648        ));
649    }
650    for message in validation.warnings.into_iter().filter(passes) {
651        diagnostics.push(diagnostic(
652            Severity::Warning,
653            "validation",
654            None,
655            message,
656            None,
657        ));
658    }
659    CheckReport::new(diagnostics)
660}
661
662/// Extraction that names no model runs on the host's rolling default; the
663/// fix pins `models.extraction`.
664fn unpinned_extraction_model(
665    doc: &Value,
666    spec: &SessionSpec,
667    out: &mut Vec<Diagnostic>,
668    covered: &mut Vec<String>,
669) {
670    if !spec.uses_default_extraction_model() {
671        return;
672    }
673    let patch = pin_extraction_model(doc);
674    out.push(diagnostic(
675        Severity::Warning,
676        "unpinned_extraction_model",
677        Some("/models/extraction".into()),
678        "extraction names no model, so it runs on the host default (gemini-flash-latest, a \
679         rolling alias whose model and latency change under you, unless GEMINI_TEXT_MODEL is \
680         set); every turn waits for it",
681        Some(Fix {
682            description: format!("Run extraction on {}", super::RECOMMENDED_EXTRACTION_MODEL),
683            patch,
684        }),
685    ));
686    covered.push("extraction names no model".into());
687}
688
689/// Ops that pin the recommended extraction model and its thinking budget,
690/// keeping whatever `models` already sets.
691fn pin_extraction_model(doc: &Value) -> Vec<PatchOp> {
692    let model = json!(super::RECOMMENDED_EXTRACTION_MODEL);
693    let budget = json!(super::RECOMMENDED_EXTRACTION_THINKING_BUDGET);
694    if !doc.get("models").is_some_and(Value::is_object) {
695        return vec![add(
696            "/models",
697            json!({ "extraction": model, "extraction_thinking_budget": budget }),
698        )];
699    }
700    let mut ops = Vec::new();
701    if doc.pointer("/models/extraction").is_none() {
702        ops.push(add("/models/extraction", model));
703        if doc.pointer("/models/extraction_thinking_budget").is_none() {
704            ops.push(add("/models/extraction_thinking_budget", budget));
705        }
706    }
707    ops
708}
709
710/// [`check`] the text of a spec file. Text that is not JSON gets an
711/// `invalid_json` diagnostic with its line and column.
712pub fn check_str(text: &str) -> CheckReport {
713    match serde_json::from_str::<Value>(text) {
714        Ok(doc) => check(&doc),
715        Err(e) => CheckReport::new(vec![diagnostic(
716            Severity::Error,
717            "invalid_json",
718            None,
719            e.to_string(),
720            None,
721        )]),
722    }
723}
724
725/// Field names of a definition in the spec's JSON Schema.
726fn schema_fields(schema: &Value, definition: Option<&str>) -> BTreeSet<String> {
727    let node = match definition {
728        Some(name) => &schema["definitions"][name],
729        None => schema,
730    };
731    node["properties"]
732        .as_object()
733        .map(|props| props.keys().cloned().collect())
734        .unwrap_or_default()
735}
736
737fn unknown_fields(doc: &Value, out: &mut Vec<Diagnostic>) {
738    let schema = SessionSpec::json_schema();
739    let top = schema_fields(&schema, None);
740    let mut stage = schema_fields(&schema, Some("StageSpec"));
741    // `say` also deserializes from `instruction`.
742    stage.insert("instruction".into());
743    let conversation = schema_fields(&schema, Some("ConversationSpec"));
744    let overlay = schema_fields(&schema, Some("OverlaySpec"));
745    let tool = schema_fields(&schema, Some("ToolSpec"));
746
747    unknown_in(doc, "", &top, out);
748    for (i, t) in array(doc, "/tools") {
749        unknown_in(t, &format!("/tools/{i}"), &tool, out);
750    }
751    let mut decision = schema_fields(&schema, Some("DecisionSpec"));
752    // The question type's own fields are flattened in.
753    decision.extend(["type", "instructions", "criteria"].map(String::from));
754    for (id, d) in doc
755        .get("decisions")
756        .and_then(Value::as_object)
757        .into_iter()
758        .flatten()
759    {
760        unknown_in(d, &format!("/decisions/{}", escape(id)), &decision, out);
761    }
762    if let Some(code) = doc.get("code").filter(|c| c.is_object()) {
763        unknown_in(
764            code,
765            "/code",
766            &schema_fields(&schema, Some("CodeSpec")),
767            out,
768        );
769        if let Some(limits) = code.get("limits").filter(|l| l.is_object()) {
770            let fields = schema_fields(&schema, Some("CodeLimitsSpec"));
771            unknown_in(limits, "/code/limits", &fields, out);
772        }
773    }
774    let Some(conv) = doc.get("conversation").filter(|c| c.is_object()) else {
775        return;
776    };
777    unknown_in(conv, "/conversation", &conversation, out);
778    for (i, s) in array(doc, "/conversation/stages") {
779        unknown_in(s, &format!("/conversation/stages/{i}"), &stage, out);
780    }
781    for (o, ov) in array(doc, "/conversation/overlays") {
782        let base = format!("/conversation/overlays/{o}");
783        unknown_in(ov, &base, &overlay, out);
784        for (i, s) in array(ov, "/stages") {
785            unknown_in(s, &format!("{base}/stages/{i}"), &stage, out);
786        }
787    }
788}
789
790fn array<'a>(doc: &'a Value, pointer: &str) -> impl Iterator<Item = (usize, &'a Value)> {
791    doc.pointer(pointer)
792        .and_then(Value::as_array)
793        .into_iter()
794        .flatten()
795        .enumerate()
796}
797
798fn unknown_in(value: &Value, base: &str, known: &BTreeSet<String>, out: &mut Vec<Diagnostic>) {
799    let Some(object) = value.as_object() else {
800        return;
801    };
802    for (key, field) in object {
803        // `$schema` and similar editor keys are allowed.
804        if known.contains(key) || key.starts_with('$') {
805            continue;
806        }
807        let path = format!("{base}/{}", escape(key));
808        let suggestion = closest(key, known.iter().map(String::as_str));
809        let message = match suggestion {
810            Some(s) => format!("'{key}' is not a field here and is ignored — did you mean '{s}'?"),
811            None => format!("'{key}' is not a field here and is ignored"),
812        };
813        let fix = suggestion
814            .filter(|s| !object.contains_key(*s))
815            .map(|s| Fix {
816                description: format!("rename '{key}' to '{s}'"),
817                patch: vec![
818                    PatchOp::Remove { path: path.clone() },
819                    add(format!("{base}/{}", escape(s)), field.clone()),
820                ],
821            });
822        out.push(diagnostic(
823            Severity::Warning,
824            "unknown_field",
825            Some(path),
826            message,
827            fix,
828        ));
829    }
830}
831
832/// The unique closest candidate within edit distance 2.
833fn closest<'a>(word: &str, candidates: impl Iterator<Item = &'a str>) -> Option<&'a str> {
834    let mut best: Option<(usize, &str)> = None;
835    let mut tied = false;
836    for candidate in candidates {
837        let distance = levenshtein(word, candidate);
838        if distance == 0 || distance > 2 {
839            continue;
840        }
841        match best {
842            Some((d, _)) if distance > d => {}
843            Some((d, _)) if distance == d => tied = true,
844            _ => {
845                best = Some((distance, candidate));
846                tied = false;
847            }
848        }
849    }
850    best.filter(|_| !tied).map(|(_, c)| c)
851}
852
853/// A stage and the pointer to it, main flow first, then digressions.
854fn stage_pointers(spec: &SessionSpec) -> Vec<(String, &StageSpec)> {
855    let Some(conv) = &spec.conversation else {
856        return Vec::new();
857    };
858    let main = conv
859        .stages
860        .iter()
861        .enumerate()
862        .map(|(i, s)| (format!("/conversation/stages/{i}"), s));
863    let overlays = conv.overlays.iter().enumerate().flat_map(|(o, ov)| {
864        ov.stages
865            .iter()
866            .enumerate()
867            .map(move |(i, s)| (format!("/conversation/overlays/{o}/stages/{i}"), s))
868    });
869    main.chain(overlays).collect()
870}
871
872/// Where a guard sits, for describing what its keys mean.
873#[derive(Debug, Clone)]
874enum Site {
875    Commit(String),
876    Trigger,
877    Other,
878}
879
880/// A guard atom that reads a name: its kind, the name, and the pointer to the
881/// string holding it.
882struct Atom {
883    kind: &'static str,
884    name: String,
885    path: String,
886}
887
888fn guard_atoms(guard: &Value, path: &str, out: &mut Vec<Atom>) {
889    let Some(object) = guard.as_object() else {
890        return;
891    };
892    for (kind, inner) in object {
893        let here = format!("{path}/{}", escape(kind));
894        match kind.as_str() {
895            "is_true" | "is_set" | "called_ok" | "done" => {
896                if let Some(name) = inner.as_str() {
897                    out.push(Atom {
898                        kind: atom_kind(kind),
899                        name: name.to_string(),
900                        path: here,
901                    });
902                }
903            }
904            "eq" => {
905                if let Some(name) = inner.get(0).and_then(Value::as_str) {
906                    out.push(Atom {
907                        kind: "eq",
908                        name: name.to_string(),
909                        path: format!("{here}/0"),
910                    });
911                }
912            }
913            "captured" => {
914                for (i, name) in inner.as_array().into_iter().flatten().enumerate() {
915                    if let Some(name) = name.as_str() {
916                        out.push(Atom {
917                            kind: "captured",
918                            name: name.to_string(),
919                            path: format!("{here}/{i}"),
920                        });
921                    }
922                }
923            }
924            "all" | "any" => {
925                for (i, g) in inner.as_array().into_iter().flatten().enumerate() {
926                    guard_atoms(g, &format!("{here}/{i}"), out);
927                }
928            }
929            "not" => guard_atoms(inner, &here, out),
930            _ => {}
931        }
932    }
933}
934
935fn atom_kind(kind: &str) -> &'static str {
936    match kind {
937        "is_true" => "is_true",
938        "is_set" => "is_set",
939        "called_ok" => "called_ok",
940        _ => "done",
941    }
942}
943
944/// Every guard in the conversation, with its pointer and site.
945fn conversation_guards(doc: &Value, spec: &SessionSpec) -> Vec<(String, Site)> {
946    let mut guards = Vec::new();
947    for (base, stage) in stage_pointers(spec) {
948        if stage.done.is_some() {
949            guards.push((format!("{base}/done"), Site::Other));
950        }
951        if let Some(commit) = &stage.commit {
952            guards.push((
953                format!("{base}/commit/when"),
954                Site::Commit(commit.tool.clone()),
955            ));
956        }
957        for j in 0..stage.next.len() {
958            guards.push((format!("{base}/next/{j}/when"), Site::Other));
959        }
960    }
961    for (o, _) in array(doc, "/conversation/overlays") {
962        guards.push((format!("/conversation/overlays/{o}/trigger"), Site::Trigger));
963    }
964    guards
965}
966
967fn unknown_tools(
968    doc: &Value,
969    spec: &SessionSpec,
970    out: &mut Vec<Diagnostic>,
971    covered: &mut Vec<String>,
972) {
973    // MCP toolsets and skills resolve their tool names elsewhere.
974    if !spec.mcp.is_empty() || !spec.skills.is_empty() {
975        return;
976    }
977    let mut known: BTreeSet<&str> = spec.tools.iter().map(|t| t.name.as_str()).collect();
978    if spec.memory.is_some() {
979        known.extend(MEMORY_TOOL_NAMES);
980    }
981    // Validation only checks names against a non-empty registry.
982    let severity = if spec.tools.is_empty() {
983        Severity::Warning
984    } else {
985        Severity::Error
986    };
987
988    let mut refs: Vec<(String, String)> = Vec::new();
989    for (base, stage) in stage_pointers(spec) {
990        for (k, tool) in stage.allow.iter().enumerate() {
991            refs.push((tool.clone(), format!("{base}/allow/{k}")));
992        }
993        if let Some(commit) = &stage.commit {
994            refs.push((commit.tool.clone(), format!("{base}/commit/tool")));
995        }
996    }
997    for (path, _) in conversation_guards(doc, spec) {
998        let mut atoms = Vec::new();
999        if let Some(guard) = doc.pointer(&path) {
1000            guard_atoms(guard, &path, &mut atoms);
1001        }
1002        refs.extend(
1003            atoms
1004                .into_iter()
1005                .filter(|a| a.kind == "called_ok")
1006                .map(|a| (a.name, a.path)),
1007        );
1008    }
1009    if let Some(conv) = &spec.conversation {
1010        for (p, policy) in conv.policies.iter().enumerate() {
1011            if let Policy::Commit {
1012                tool,
1013                compensate_with,
1014                ..
1015            } = policy
1016            {
1017                let base = format!("/conversation/policies/{p}");
1018                refs.push((tool.clone(), format!("{base}/tool")));
1019                if let Some(c) = compensate_with {
1020                    refs.push((c.clone(), format!("{base}/compensate_with")));
1021                }
1022            }
1023        }
1024    }
1025
1026    for (name, path) in refs {
1027        if known.contains(name.as_str()) {
1028            continue;
1029        }
1030        covered.push(format!(
1031            "tool '{name}' which is not in the provided tool registry"
1032        ));
1033        let suggestion = closest(&name, known.iter().copied());
1034        let (message, fix) = match suggestion {
1035            Some(s) => (
1036                format!("tool '{name}' is not declared — did you mean '{s}'?"),
1037                Fix {
1038                    description: format!("replace '{name}' with '{s}'"),
1039                    patch: vec![PatchOp::Replace {
1040                        path: path.clone(),
1041                        value: json!(s),
1042                    }],
1043                },
1044            ),
1045            None => (
1046                format!("tool '{name}' is not declared"),
1047                Fix {
1048                    description: format!(
1049                        "declare '{name}' with no binding (codegen writes a stub for it)"
1050                    ),
1051                    patch: vec![append(doc, "/tools", json!({ "name": name }))],
1052                },
1053            ),
1054        };
1055        out.push(diagnostic(
1056            severity,
1057            "unknown_tool",
1058            Some(path),
1059            message,
1060            Some(fix),
1061        ));
1062    }
1063}
1064
1065/// Every key the spec writes, plus the prefixes and suffixes the runtime
1066/// writes on its own.
1067fn is_written(key: &str, written: &BTreeSet<String>) -> bool {
1068    written.contains(key)
1069        || RUNTIME_WRITTEN.iter().any(|p| key.starts_with(p))
1070        || key.ends_with(":result")
1071}
1072
1073/// One guard read of a state key.
1074struct KeyRead {
1075    kind: &'static str,
1076    path: String,
1077    /// A safety-handoff intent name: the key without its `intent:` prefix.
1078    intent_name: bool,
1079}
1080
1081fn unwritten_keys(
1082    doc: &Value,
1083    spec: &SessionSpec,
1084    out: &mut Vec<Diagnostic>,
1085    covered: &mut Vec<String>,
1086) {
1087    let written = spec.state_keys_written();
1088    // Each key's most specific site (a commit or trigger beats any other
1089    // guard) and every read of it.
1090    let mut reads: BTreeMap<String, (Site, Vec<KeyRead>)> = BTreeMap::new();
1091    for (path, site) in conversation_guards(doc, spec) {
1092        let mut atoms = Vec::new();
1093        if let Some(guard) = doc.pointer(&path) {
1094            guard_atoms(guard, &path, &mut atoms);
1095        }
1096        for atom in atoms {
1097            if matches!(atom.kind, "called_ok" | "done") {
1098                continue;
1099            }
1100            let read = reads
1101                .entry(atom.name)
1102                .or_insert_with(|| (site.clone(), Vec::new()));
1103            if matches!(read.0, Site::Other) {
1104                read.0 = site.clone();
1105            }
1106            read.1.push(KeyRead {
1107                kind: atom.kind,
1108                path: atom.path,
1109                intent_name: false,
1110            });
1111        }
1112    }
1113    if let Some(conv) = &spec.conversation {
1114        for (p, policy) in conv.policies.iter().enumerate() {
1115            if let Policy::SafetyHandoff { intents } = policy {
1116                for (k, intent) in intents.iter().enumerate() {
1117                    let read = reads
1118                        .entry(format!("intent:{intent}"))
1119                        .or_insert_with(|| (Site::Trigger, Vec::new()));
1120                    read.0 = Site::Trigger;
1121                    read.1.push(KeyRead {
1122                        kind: "is_true",
1123                        path: format!("/conversation/policies/{p}/intents/{k}"),
1124                        intent_name: true,
1125                    });
1126                }
1127            }
1128        }
1129    }
1130
1131    for (key, (site, reads)) in reads {
1132        if is_written(&key, &written) {
1133            continue;
1134        }
1135        covered.push(format!("state key '{key}'"));
1136        let path = reads[0].path.clone();
1137        // A handoff policy names the intent without its prefix, so only an
1138        // intent flag can replace it.
1139        let intent_only = reads.iter().any(|r| r.intent_name);
1140        let suggestion = closest(
1141            &key,
1142            written
1143                .iter()
1144                .map(String::as_str)
1145                .filter(|w| !intent_only || w.starts_with("intent:")),
1146        );
1147        let mut message = format!(
1148            "a guard reads state key '{key}' but nothing writes it, so it can never become true"
1149        );
1150        let fix = if let Some(s) = suggestion {
1151            message.push_str(&format!(" — did you mean '{s}'?"));
1152            let patch = reads
1153                .iter()
1154                .map(|r| {
1155                    let value = if r.intent_name {
1156                        s.strip_prefix("intent:").unwrap_or(s)
1157                    } else {
1158                        s
1159                    };
1160                    PatchOp::Replace {
1161                        path: r.path.clone(),
1162                        value: json!(value),
1163                    }
1164                })
1165                .collect();
1166            Some(Fix {
1167                description: format!("read '{s}' instead"),
1168                patch,
1169            })
1170        } else if reads.iter().all(|r| r.kind == "is_true") {
1171            Some(Fix {
1172                description: format!(
1173                    "add a '{SIGNALS_EXTRACTOR}' extractor field that sets '{key}' when the \
1174                     caller says so (needs an extraction model at run time)"
1175                ),
1176                patch: signal_ops(doc, &key, &signal_description(&key, &site)),
1177            })
1178        } else {
1179            None
1180        };
1181        out.push(diagnostic(
1182            Severity::Warning,
1183            "unwritten_key",
1184            Some(path),
1185            message,
1186            fix,
1187        ));
1188    }
1189}
1190
1191fn humanize(key: &str) -> String {
1192    key.replace(['_', '-', ':'], " ")
1193}
1194
1195fn signal_description(key: &str, site: &Site) -> String {
1196    match (site, key.strip_prefix("intent:")) {
1197        (_, Some(intent)) => format!("What the caller said matches the intent '{intent}'."),
1198        (Site::Commit(tool), None) => format!(
1199            "The caller explicitly agreed to go ahead with {} after hearing the details.",
1200            humanize(tool)
1201        ),
1202        _ => format!("The conversation shows that '{key}' is true."),
1203    }
1204}
1205
1206/// The JSON field a signal extractor fills for `key`.
1207fn signal_field(key: &str) -> String {
1208    key.chars()
1209        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
1210        .collect()
1211}
1212
1213/// Ops that make the signal extractor write `key` as a boolean.
1214fn signal_ops(doc: &Value, key: &str, description: &str) -> Vec<PatchOp> {
1215    let field = signal_field(key);
1216    let promote = if field == key {
1217        json!({ "field": field, "policy": "true_only" })
1218    } else {
1219        json!({ "field": field, "to": key, "policy": "true_only" })
1220    };
1221    let property = json!({ "type": "boolean", "description": description });
1222    let existing = array(doc, "/extract").find(|(_, e)| e["name"] == SIGNALS_EXTRACTOR);
1223    match existing {
1224        Some((i, extractor)) => {
1225            let base = format!("/extract/{i}");
1226            let schema_op = if extractor["schema"]["properties"].is_object() {
1227                add(
1228                    format!("{base}/schema/properties/{}", escape(&field)),
1229                    property,
1230                )
1231            } else {
1232                add(
1233                    format!("{base}/schema"),
1234                    json!({ "type": "object", "properties": { field.clone(): property } }),
1235                )
1236            };
1237            vec![schema_op, append(doc, &format!("{base}/promote"), promote)]
1238        }
1239        None => {
1240            let mut ops = vec![append(
1241                doc,
1242                "/extract",
1243                json!({
1244                    "name": SIGNALS_EXTRACTOR,
1245                    "instruction": "Read the latest turns of the conversation. Set a field to true \
1246                                    only when the caller clearly said so in their own words. \
1247                                    Otherwise leave it out.",
1248                    "schema": { "type": "object", "properties": { field: property } },
1249                    "promote": [promote]
1250                }),
1251            )];
1252            // New extraction names its model.
1253            ops.extend(pin_extraction_model(doc));
1254            ops
1255        }
1256    }
1257}
1258
1259// ---------------------------------------------------------------------------
1260// Plan
1261// ---------------------------------------------------------------------------
1262
1263/// Answered question ids, mapped to the chosen option value. A harness
1264/// stores this next to the spec and passes it back so answered questions
1265/// are not asked again.
1266pub type Decisions = BTreeMap<String, String>;
1267
1268/// How a question is answered.
1269#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
1270#[serde(rename_all = "snake_case")]
1271pub enum QuestionKind {
1272    /// Pick one option.
1273    Choice,
1274    /// Supply text; the question has one option, which needs a value.
1275    Text,
1276}
1277
1278/// One way to answer a question.
1279#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1280pub struct AnswerOption {
1281    /// The value to send in [`Answer::choice`].
1282    pub value: String,
1283    /// What choosing it means.
1284    pub label: String,
1285    /// The patch that records it. Empty when the choice changes nothing in
1286    /// the spec and is only recorded in [`Decisions`].
1287    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1288    pub patch: Vec<PatchOp>,
1289    /// The option needs [`Answer::value`]; it replaces the
1290    /// [`ANSWER_PLACEHOLDER`] strings in `patch`.
1291    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1292    pub needs_value: bool,
1293}
1294
1295/// A decision the document leaves open.
1296#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1297pub struct Question {
1298    /// Stable id; see [`Catalog::questions`].
1299    pub id: String,
1300    /// The question, phrased for the user.
1301    pub ask: String,
1302    /// Why it matters.
1303    pub why: String,
1304    /// Choice or text.
1305    pub kind: QuestionKind,
1306    /// The ways to answer.
1307    pub options: Vec<AnswerOption>,
1308    /// The option to take when the user has no preference. Never one that
1309    /// needs a value.
1310    #[serde(default, skip_serializing_if = "Option::is_none")]
1311    pub default: Option<String>,
1312    /// The app should not be generated until this is answered.
1313    pub blocking: bool,
1314    /// Pointers the options write.
1315    pub affects: Vec<String>,
1316}
1317
1318/// The result of [`plan`].
1319#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1320pub struct Plan {
1321    /// No blocking questions and no error diagnostics: generate now.
1322    pub ready: bool,
1323    /// Number of blocking questions.
1324    pub blocking: usize,
1325    /// Open questions, blocking first.
1326    pub questions: Vec<Question>,
1327}
1328
1329/// The open decisions in `doc`, skipping question ids in `decisions`.
1330///
1331/// Rules apply to full specs. A bare flow or a document that does not
1332/// deserialize has no questions; [`check`] reports why it does not parse.
1333pub fn plan(doc: &Value, decisions: &Decisions) -> Plan {
1334    let questions = questions(doc, decisions);
1335    let blocking = questions.iter().filter(|q| q.blocking).count();
1336    Plan {
1337        ready: blocking == 0 && check(doc).valid,
1338        blocking,
1339        questions,
1340    }
1341}
1342
1343fn questions(doc: &Value, decisions: &Decisions) -> Vec<Question> {
1344    let bare_flow = doc.get("flow").is_none() && doc.get("steps").is_some();
1345    if bare_flow {
1346        return Vec::new();
1347    }
1348    let Ok(spec) = SessionSpec::from_value(doc.clone()) else {
1349        return Vec::new();
1350    };
1351    let mut out = Vec::new();
1352    ask_name_and_instruction(&spec, &mut out);
1353    ask_tool_descriptions(&spec, &mut out);
1354    ask_commit_gates(doc, &spec, &mut out);
1355    ask_redactions(doc, &spec, &mut out);
1356    ask_voice(&spec, &mut out);
1357    ask_greeting(&spec, &mut out);
1358    ask_escalation(doc, &spec, &mut out);
1359    ask_disclosure(&spec, &mut out);
1360    ask_tool_bindings(&spec, &mut out);
1361    out.retain(|q| !decisions.contains_key(&q.id));
1362    out.sort_by_key(|q| !q.blocking);
1363    out
1364}
1365
1366fn text_question(id: String, ask: String, why: &str, path: String, blocking: bool) -> Question {
1367    Question {
1368        id,
1369        ask,
1370        why: why.into(),
1371        kind: QuestionKind::Text,
1372        options: vec![AnswerOption {
1373            value: "text".into(),
1374            label: "Your answer".into(),
1375            patch: vec![add(path.clone(), json!(ANSWER_PLACEHOLDER))],
1376            needs_value: true,
1377        }],
1378        default: None,
1379        blocking,
1380        affects: vec![path],
1381    }
1382}
1383
1384fn option(value: &str, label: impl Into<String>, patch: Vec<PatchOp>) -> AnswerOption {
1385    AnswerOption {
1386        value: value.into(),
1387        label: label.into(),
1388        patch,
1389        needs_value: false,
1390    }
1391}
1392
1393fn ask_name_and_instruction(spec: &SessionSpec, out: &mut Vec<Question>) {
1394    if spec.name.trim().is_empty() {
1395        out.push(text_question(
1396            "name".into(),
1397            "What is the app called? Use a short slug, such as `trattoria-booking`.".into(),
1398            "The name identifies the app in bundles, traces and generated projects.",
1399            "/name".into(),
1400            true,
1401        ));
1402    }
1403    if spec.instruction.trim().is_empty() {
1404        out.push(text_question(
1405            "instruction".into(),
1406            "What should the agent do, and for whom? One or two sentences.".into(),
1407            "The base instruction is the model's standing brief for every turn.",
1408            "/instruction".into(),
1409            true,
1410        ));
1411    }
1412}
1413
1414fn ask_tool_descriptions(spec: &SessionSpec, out: &mut Vec<Question>) {
1415    for (i, tool) in spec.tools.iter().enumerate() {
1416        if tool.description.trim().is_empty() {
1417            out.push(text_question(
1418                format!("tool_description:{}", tool.name),
1419                format!("What does the tool `{}` do?", tool.name),
1420                "The model reads the description to decide when to call the tool.",
1421                format!("/tools/{i}/description"),
1422                true,
1423            ));
1424        }
1425    }
1426}
1427
1428/// Verbs that suggest a tool changes something outside the conversation.
1429const COMMITTING_VERBS: [&str; 30] = [
1430    "add",
1431    "apply",
1432    "approve",
1433    "book",
1434    "buy",
1435    "cancel",
1436    "charge",
1437    "close",
1438    "create",
1439    "delete",
1440    "deposit",
1441    "enroll",
1442    "issue",
1443    "order",
1444    "pay",
1445    "place",
1446    "purchase",
1447    "refund",
1448    "register",
1449    "remove",
1450    "reschedule",
1451    "reserve",
1452    "schedule",
1453    "send",
1454    "sign",
1455    "submit",
1456    "transfer",
1457    "update",
1458    "withdraw",
1459    "write",
1460];
1461
1462/// Lowercase words of a snake, kebab or camel case name.
1463fn name_parts(name: &str) -> Vec<String> {
1464    let mut parts = vec![String::new()];
1465    let mut previous_lower = false;
1466    for c in name.chars() {
1467        if !c.is_ascii_alphanumeric() {
1468            parts.push(String::new());
1469            previous_lower = false;
1470            continue;
1471        }
1472        if c.is_ascii_uppercase() && previous_lower {
1473            parts.push(String::new());
1474        }
1475        previous_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
1476        if let Some(part) = parts.last_mut() {
1477            part.push(c.to_ascii_lowercase());
1478        }
1479    }
1480    parts.retain(|p| !p.is_empty());
1481    parts
1482}
1483
1484fn looks_committing(spec: &SessionSpec, tool: &str) -> bool {
1485    let verb = name_parts(tool).into_iter().next().unwrap_or_default();
1486    let mutating_http = spec
1487        .tools
1488        .iter()
1489        .find(|t| t.name == tool)
1490        .and_then(|t| t.http.as_ref())
1491        .is_some_and(|h| !h.method.eq_ignore_ascii_case("GET"));
1492    COMMITTING_VERBS.contains(&verb.as_str()) || mutating_http
1493}
1494
1495fn ask_commit_gates(doc: &Value, spec: &SessionSpec, out: &mut Vec<Question>) {
1496    if spec.conversation.is_none() {
1497        return;
1498    }
1499    let stages = stage_pointers(spec);
1500    let committed: BTreeSet<&str> = stages
1501        .iter()
1502        .filter_map(|(_, s)| s.commit.as_ref().map(|c| c.tool.as_str()))
1503        .collect();
1504    let written = spec.state_keys_written();
1505    let mut seen = BTreeSet::new();
1506    for (_, stage) in &stages {
1507        for tool in &stage.allow {
1508            if committed.contains(tool.as_str())
1509                || !seen.insert(tool.as_str())
1510                || !looks_committing(spec, tool)
1511            {
1512                continue;
1513            }
1514            // The first stage allowing the tool that has no commit yet.
1515            let Some((base, _)) = stages
1516                .iter()
1517                .find(|(_, s)| s.commit.is_none() && s.allow.contains(tool))
1518            else {
1519                continue;
1520            };
1521            let key = format!("{tool}_confirmed");
1522            let mut patch = vec![add(
1523                format!("{base}/commit"),
1524                json!({ "tool": tool, "when": { "is_true": key } }),
1525            )];
1526            if !is_written(&key, &written) {
1527                patch.extend(signal_ops(
1528                    doc,
1529                    &key,
1530                    &signal_description(&key, &Site::Commit(tool.clone())),
1531                ));
1532            }
1533            out.push(Question {
1534                id: format!("commit_gate:{tool}"),
1535                ask: format!(
1536                    "Should `{tool}` run only after the caller confirms the details read back \
1537                     to them?"
1538                ),
1539                why: "A stage that allows a tool without a commit guard lets the model call it \
1540                      as soon as the stage is active, before the caller has agreed."
1541                    .into(),
1542                kind: QuestionKind::Choice,
1543                options: vec![
1544                    option(
1545                        "confirm",
1546                        format!(
1547                            "Gate it on '{key}', which an extractor sets when the caller \
1548                             agrees"
1549                        ),
1550                        patch,
1551                    ),
1552                    option(
1553                        "no_confirmation",
1554                        "It changes nothing the caller has to approve",
1555                        Vec::new(),
1556                    ),
1557                ],
1558                default: Some("confirm".into()),
1559                blocking: true,
1560                affects: vec![format!("{base}/commit"), "/extract".into()],
1561            });
1562        }
1563    }
1564}
1565
1566/// Name parts that suggest a slot holds personal or payment data.
1567const SENSITIVE_PARTS: [&str; 19] = [
1568    "account",
1569    "birth",
1570    "card",
1571    "cvc",
1572    "cvv",
1573    "diagnosis",
1574    "dob",
1575    "iban",
1576    "insurance",
1577    "licence",
1578    "license",
1579    "medical",
1580    "passcode",
1581    "passport",
1582    "password",
1583    "pin",
1584    "routing",
1585    "ssn",
1586    "tax",
1587];
1588
1589fn looks_sensitive(slot: &str) -> bool {
1590    name_parts(slot)
1591        .iter()
1592        .any(|part| SENSITIVE_PARTS.contains(&part.as_str()))
1593}
1594
1595fn ask_redactions(doc: &Value, spec: &SessionSpec, out: &mut Vec<Question>) {
1596    let Some(conv) = &spec.conversation else {
1597        return;
1598    };
1599    let mut redacted = BTreeSet::new();
1600    let mut redact_policy = None;
1601    for (p, policy) in conv.policies.iter().enumerate() {
1602        if let Policy::Redact { keys } = policy {
1603            redacted.extend(keys.iter().map(String::as_str));
1604            redact_policy.get_or_insert(p);
1605        }
1606    }
1607    let mut slots = BTreeSet::new();
1608    for (_, stage) in stage_pointers(spec) {
1609        slots.extend(stage.collect.iter().map(String::as_str));
1610        slots.extend(stage.resolve.iter().map(|r| r.slot.as_str()));
1611    }
1612    for slot in slots {
1613        if redacted.contains(slot) || !looks_sensitive(slot) {
1614            continue;
1615        }
1616        let patch = match redact_policy {
1617            Some(p) => vec![add(
1618                format!("/conversation/policies/{p}/keys/-"),
1619                json!(slot),
1620            )],
1621            None => vec![append(
1622                doc,
1623                "/conversation/policies",
1624                json!({ "kind": "redact", "keys": [slot] }),
1625            )],
1626        };
1627        out.push(Question {
1628            id: format!("redact:{slot}"),
1629            ask: format!("`{slot}` looks sensitive. Should it be redacted?"),
1630            why: "A redacted key is written as `[redacted]` to the journal, persistence \
1631                  snapshots and extraction events. In-process reads still see the value, and \
1632                  transcript text is not covered: see the hardening guide."
1633                .into(),
1634            kind: QuestionKind::Choice,
1635            options: vec![
1636                option("redact", "Redact it", patch),
1637                option(
1638                    "keep",
1639                    "Keep it in the clear (it is not sensitive, or a later system needs it)",
1640                    Vec::new(),
1641                ),
1642            ],
1643            default: Some("redact".into()),
1644            blocking: true,
1645            affects: vec!["/conversation/policies".into()],
1646        });
1647    }
1648}
1649
1650fn ask_voice(spec: &SessionSpec, out: &mut Vec<Question>) {
1651    if spec.modality != super::SpecModality::Audio || spec.voice.is_some() {
1652        return;
1653    }
1654    out.push(Question {
1655        id: "voice".into(),
1656        ask: "Which voice should the agent speak with?".into(),
1657        why: "Without one the provider default (Puck) is used.".into(),
1658        kind: QuestionKind::Choice,
1659        options: VOICES
1660            .iter()
1661            .map(|v| option(v, *v, vec![add("/voice", json!(v))]))
1662            .collect(),
1663        default: Some("Puck".into()),
1664        blocking: false,
1665        affects: vec!["/voice".into()],
1666    });
1667}
1668
1669fn ask_greeting(spec: &SessionSpec, out: &mut Vec<Question>) {
1670    if spec.modality != super::SpecModality::Audio || spec.greeting.is_some() {
1671        return;
1672    }
1673    let greeting = if spec.name.trim().is_empty() {
1674        "Greet the caller and ask how you can help.".to_string()
1675    } else {
1676        format!(
1677            "Greet the caller as the assistant for {} and ask how you can help.",
1678            spec.name
1679        )
1680    };
1681    out.push(Question {
1682        id: "greeting".into(),
1683        ask: "Should the agent speak first when the call connects?".into(),
1684        why: "On a phone call the caller usually expects to hear the agent first. Without a \
1685              greeting the agent waits for the caller."
1686            .into(),
1687        kind: QuestionKind::Choice,
1688        options: vec![
1689            option(
1690                "speak_first",
1691                format!("Speak first: \"{greeting}\""),
1692                vec![add("/greeting", json!(greeting))],
1693            ),
1694            AnswerOption {
1695                value: "custom".into(),
1696                label: "Speak first, with your own greeting instruction".into(),
1697                patch: vec![add("/greeting", json!(ANSWER_PLACEHOLDER))],
1698                needs_value: true,
1699            },
1700            option("wait", "Wait for the caller to speak", Vec::new()),
1701        ],
1702        default: Some("speak_first".into()),
1703        blocking: false,
1704        affects: vec!["/greeting".into()],
1705    });
1706}
1707
1708fn ask_escalation(doc: &Value, spec: &SessionSpec, out: &mut Vec<Question>) {
1709    let Some(conv) = &spec.conversation else {
1710        return;
1711    };
1712    let handoff = conv
1713        .policies
1714        .iter()
1715        .any(|p| matches!(p, Policy::SafetyHandoff { .. }));
1716    let escalates = conv
1717        .stages
1718        .iter()
1719        .any(|s| s.repair.as_ref().is_some_and(|r| r.escalate_to.is_some()));
1720    if handoff || escalates || !conv.overlays.is_empty() {
1721        return;
1722    }
1723    // A digression whose stage admits only the transfer tool and waits for
1724    // it. A terminal digression stage, which `safety_handoff` lowers to,
1725    // restricts no tools on the turn it is entered.
1726    let key = "intent:human_agent";
1727    let transfer = "handoff_to_staff";
1728    let mut patch = Vec::new();
1729    if !spec.tools.iter().any(|t| t.name == transfer) {
1730        patch.push(append(
1731            doc,
1732            "/tools",
1733            json!({
1734                "name": transfer,
1735                "description": "Transfer the caller to a member of staff."
1736            }),
1737        ));
1738    }
1739    patch.push(append(
1740        doc,
1741        "/conversation/overlays",
1742        json!({
1743            "name": "handoff",
1744            "trigger": { "is_true": key },
1745            "stages": [{
1746                "id": "transfer",
1747                "say": "Tell the caller you are passing them to a member of staff, then call handoff_to_staff.",
1748                "allow": [transfer],
1749                "done": { "called_ok": transfer }
1750            }],
1751            "resume": "terminate"
1752        }),
1753    ));
1754    if !spec.state_keys_written().contains(key) {
1755        patch.extend(signal_ops(
1756            doc,
1757            key,
1758            "The caller asked to speak to a person instead of the assistant.",
1759        ));
1760    }
1761    out.push(Question {
1762        id: "escalation".into(),
1763        ask: "What should happen when the caller asks for a person?".into(),
1764        why: "The conversation has no digression, safety handoff or repair escalation, so a \
1765              caller who wants out has no path."
1766            .into(),
1767        kind: QuestionKind::Choice,
1768        options: vec![
1769            option(
1770                "handoff",
1771                "Hand off through a `handoff_to_staff` tool your app implements; the \
1772                 conversation then ends and `flow:terminated` becomes true",
1773                patch,
1774            ),
1775            option("none", "Keep the agent in the conversation", Vec::new()),
1776        ],
1777        default: Some("handoff".into()),
1778        blocking: false,
1779        affects: vec![
1780            "/tools".into(),
1781            "/conversation/overlays".into(),
1782            "/extract".into(),
1783        ],
1784    });
1785}
1786
1787fn ask_disclosure(spec: &SessionSpec, out: &mut Vec<Question>) {
1788    let Some(conv) = &spec.conversation else {
1789        return;
1790    };
1791    if spec.modality != super::SpecModality::Audio
1792        || conv.stages.is_empty()
1793        || conv.stages.iter().any(|s| s.verbatim.is_some())
1794    {
1795        return;
1796    }
1797    let path = "/conversation/stages/0/verbatim".to_string();
1798    out.push(Question {
1799        id: "disclosure".into(),
1800        ask: format!(
1801            "Should the agent read a fixed disclosure in the `{}` stage, such as a \
1802             recording or AI notice?",
1803            conv.stages[0].id
1804        ),
1805        why: "Text that must be said word for word belongs in a verbatim stage, which does \
1806              not complete until it has been said."
1807            .into(),
1808        kind: QuestionKind::Choice,
1809        options: vec![
1810            AnswerOption {
1811                value: "read".into(),
1812                label: "Read this text word for word".into(),
1813                patch: vec![add(path.clone(), json!(ANSWER_PLACEHOLDER))],
1814                needs_value: true,
1815            },
1816            option("none", "No fixed text", Vec::new()),
1817        ],
1818        default: Some("none".into()),
1819        blocking: false,
1820        affects: vec![path],
1821    });
1822}
1823
1824fn ask_tool_bindings(spec: &SessionSpec, out: &mut Vec<Question>) {
1825    for (i, tool) in spec.tools.iter().enumerate() {
1826        if tool.http.is_some() || tool.mcp.is_some() || tool.response.is_some() {
1827            continue;
1828        }
1829        let method = if looks_committing(spec, &tool.name) {
1830            "POST"
1831        } else {
1832            "GET"
1833        };
1834        out.push(Question {
1835            id: format!("tool_binding:{}", tool.name),
1836            ask: format!("How is `{}` implemented?", tool.name),
1837            why: "A tool with no binding returns `{\"ok\": true}` until it is implemented.".into(),
1838            kind: QuestionKind::Choice,
1839            options: vec![
1840                option(
1841                    "stub",
1842                    "In the generated project: codegen writes a typed stub to fill in",
1843                    Vec::new(),
1844                ),
1845                AnswerOption {
1846                    value: "http".into(),
1847                    label: format!("An HTTP endpoint ({method}); give its URL"),
1848                    patch: vec![add(
1849                        format!("/tools/{i}/http"),
1850                        json!({ "method": method, "url": ANSWER_PLACEHOLDER }),
1851                    )],
1852                    needs_value: true,
1853                },
1854                AnswerOption {
1855                    value: "mcp".into(),
1856                    label: "An MCP server; give its command line or http(s) URL".into(),
1857                    patch: vec![add(format!("/tools/{i}/mcp"), json!(ANSWER_PLACEHOLDER))],
1858                    needs_value: true,
1859                },
1860            ],
1861            default: Some("stub".into()),
1862            blocking: false,
1863            affects: vec![format!("/tools/{i}")],
1864        });
1865    }
1866}
1867
1868// ---------------------------------------------------------------------------
1869// Answer
1870// ---------------------------------------------------------------------------
1871
1872/// One answer to a [`Question`].
1873#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1874pub struct Answer {
1875    /// The question id.
1876    pub id: String,
1877    /// The chosen option. Omitted: the only option of a text question, or
1878    /// the question's default.
1879    #[serde(default, skip_serializing_if = "Option::is_none")]
1880    pub choice: Option<String>,
1881    /// The value for an option that needs one.
1882    #[serde(default, skip_serializing_if = "Option::is_none")]
1883    pub value: Option<Value>,
1884}
1885
1886impl Answer {
1887    /// Choose an option.
1888    pub fn choose(id: impl Into<String>, choice: impl Into<String>) -> Self {
1889        Self {
1890            id: id.into(),
1891            choice: Some(choice.into()),
1892            value: None,
1893        }
1894    }
1895
1896    /// Answer a text question.
1897    pub fn with_value(id: impl Into<String>, value: Value) -> Self {
1898        Self {
1899            id: id.into(),
1900            choice: None,
1901            value: Some(value),
1902        }
1903    }
1904}
1905
1906/// The result of [`answer`].
1907#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1908pub struct Answered {
1909    /// The updated document.
1910    pub spec: Value,
1911    /// Question ids applied, in order.
1912    pub applied: Vec<String>,
1913    /// The input decisions plus the new ones.
1914    pub decisions: Decisions,
1915}
1916
1917/// Why answers could not be applied. Nothing is applied when any answer
1918/// fails.
1919#[derive(Debug, Clone, PartialEq)]
1920pub enum AnswerError {
1921    /// The question is not open: answered already, decided, or no longer
1922    /// applies after earlier answers.
1923    NotOpen(String),
1924    /// No choice was given and the question has no default.
1925    MissingChoice(String),
1926    /// The choice is not one of the question's options.
1927    UnknownChoice {
1928        /// Question id.
1929        id: String,
1930        /// The choice given.
1931        choice: String,
1932        /// The valid option values.
1933        options: Vec<String>,
1934    },
1935    /// The option needs a non-empty value.
1936    MissingValue {
1937        /// Question id.
1938        id: String,
1939        /// The option chosen.
1940        choice: String,
1941    },
1942    /// The option's patch did not apply.
1943    Patch {
1944        /// Question id.
1945        id: String,
1946        /// The patch failure.
1947        error: PatchError,
1948    },
1949    /// The answer left a document that no longer deserializes.
1950    Invalid {
1951        /// Question id.
1952        id: String,
1953        /// The deserialization error.
1954        message: String,
1955    },
1956}
1957
1958impl std::fmt::Display for AnswerError {
1959    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1960        match self {
1961            AnswerError::NotOpen(id) => write!(
1962                f,
1963                "question '{id}' is not open: no such question, already decided, or it no \
1964                 longer applies"
1965            ),
1966            AnswerError::MissingChoice(id) => {
1967                write!(f, "question '{id}' needs a choice: it has no default")
1968            }
1969            AnswerError::UnknownChoice {
1970                id,
1971                choice,
1972                options,
1973            } => write!(
1974                f,
1975                "question '{id}' has no option '{choice}' (options: {})",
1976                options.join(", ")
1977            ),
1978            AnswerError::MissingValue { id, choice } => {
1979                write!(f, "question '{id}', option '{choice}' needs a value")
1980            }
1981            AnswerError::Patch { id, error } => write!(f, "question '{id}': {error}"),
1982            AnswerError::Invalid { id, message } => {
1983                write!(f, "question '{id}' left an invalid spec: {message}")
1984            }
1985        }
1986    }
1987}
1988
1989impl std::error::Error for AnswerError {}
1990
1991/// Apply `answers` in order. Before each one the document is planned again,
1992/// so a patch never comes from a stale plan.
1993pub fn answer(
1994    doc: &Value,
1995    answers: &[Answer],
1996    decisions: &Decisions,
1997) -> Result<Answered, AnswerError> {
1998    let mut spec = doc.clone();
1999    let mut decisions = decisions.clone();
2000    let mut applied = Vec::new();
2001    for a in answers {
2002        let question = questions(&spec, &decisions)
2003            .into_iter()
2004            .find(|q| q.id == a.id)
2005            .ok_or_else(|| AnswerError::NotOpen(a.id.clone()))?;
2006        let choice = match (&a.choice, question.options.as_slice()) {
2007            (Some(choice), _) => choice.clone(),
2008            (None, [only]) => only.value.clone(),
2009            (None, _) => question
2010                .default
2011                .clone()
2012                .ok_or_else(|| AnswerError::MissingChoice(a.id.clone()))?,
2013        };
2014        let chosen = question
2015            .options
2016            .iter()
2017            .find(|o| o.value == choice)
2018            .ok_or_else(|| AnswerError::UnknownChoice {
2019                id: a.id.clone(),
2020                choice: choice.clone(),
2021                options: question.options.iter().map(|o| o.value.clone()).collect(),
2022            })?;
2023        let patch = if chosen.needs_value {
2024            let value = a
2025                .value
2026                .clone()
2027                .filter(|v| v.as_str().is_none_or(|s| !s.trim().is_empty()) && !v.is_null())
2028                .ok_or_else(|| AnswerError::MissingValue {
2029                    id: a.id.clone(),
2030                    choice: choice.clone(),
2031                })?;
2032            chosen
2033                .patch
2034                .iter()
2035                .map(|op| substitute(op, &value))
2036                .collect()
2037        } else {
2038            chosen.patch.clone()
2039        };
2040        spec = apply_patch(&spec, &patch).map_err(|error| AnswerError::Patch {
2041            id: a.id.clone(),
2042            error,
2043        })?;
2044        SessionSpec::from_value(spec.clone()).map_err(|message| AnswerError::Invalid {
2045            id: a.id.clone(),
2046            message,
2047        })?;
2048        decisions.insert(question.id.clone(), choice);
2049        applied.push(question.id);
2050    }
2051    Ok(Answered {
2052        spec,
2053        applied,
2054        decisions,
2055    })
2056}
2057
2058fn substitute(op: &PatchOp, answer: &Value) -> PatchOp {
2059    fn fill(value: &Value, answer: &Value) -> Value {
2060        match value {
2061            Value::String(s) if s == ANSWER_PLACEHOLDER => answer.clone(),
2062            Value::Array(items) => Value::Array(items.iter().map(|v| fill(v, answer)).collect()),
2063            Value::Object(map) => Value::Object(
2064                map.iter()
2065                    .map(|(k, v)| (k.clone(), fill(v, answer)))
2066                    .collect(),
2067            ),
2068            other => other.clone(),
2069        }
2070    }
2071    match op {
2072        PatchOp::Add { path, value } => PatchOp::Add {
2073            path: path.clone(),
2074            value: fill(value, answer),
2075        },
2076        PatchOp::Replace { path, value } => PatchOp::Replace {
2077            path: path.clone(),
2078            value: fill(value, answer),
2079        },
2080        PatchOp::Remove { path } => PatchOp::Remove { path: path.clone() },
2081    }
2082}
2083
2084#[cfg(test)]
2085mod tests {
2086    use super::*;
2087
2088    fn booking() -> Value {
2089        json!({
2090            "name": "trattoria",
2091            "instruction": "Book tables for Trattoria Rustica.",
2092            "modality": "audio",
2093            "voice": "Charon",
2094            "greeting": "Welcome the caller.",
2095            "tools": [
2096                { "name": "check_availability", "description": "Check a time.", "response": { "available": true } },
2097                { "name": "book_table", "description": "Book the table.", "response": { "booked": true } }
2098            ],
2099            "conversation": {
2100                "name": "booking",
2101                "stages": [
2102                    {
2103                        "id": "collect",
2104                        "say": "Find out the party size and time.",
2105                        "verbatim": "This call may be recorded.",
2106                        "collect": ["party_size", "slot"],
2107                        "allow": ["check_availability"],
2108                        "next": [{ "to": "confirm", "when": { "captured": ["party_size", "slot"] } }]
2109                    },
2110                    {
2111                        "id": "confirm",
2112                        "say": "Read the booking back and book it once the caller agrees.",
2113                        "allow": ["book_table"],
2114                        "next": [{ "to": "done", "when": { "called_ok": "book_table" } }]
2115                    },
2116                    { "id": "done", "terminal": true }
2117                ],
2118                "require": ["done"],
2119                "policies": [{ "kind": "safety_handoff", "intents": ["human_agent"] }]
2120            },
2121            "models": { "extraction": "gemini-3.5-flash-lite", "extraction_thinking_budget": 64 },
2122            "extract": [{
2123                "name": "caller_signals",
2124                "instruction": "Signals.",
2125                "schema": { "type": "object", "properties": { "intent_human_agent": { "type": "boolean" } } },
2126                "promote": [{ "field": "intent_human_agent", "to": "intent:human_agent", "policy": "true_only" }]
2127            }]
2128        })
2129    }
2130
2131    fn codes(report: &CheckReport) -> Vec<&str> {
2132        report.diagnostics.iter().map(|d| d.code.as_str()).collect()
2133    }
2134
2135    fn fix(report: &CheckReport, code: &str) -> Vec<PatchOp> {
2136        report
2137            .diagnostics
2138            .iter()
2139            .find(|d| d.code == code)
2140            .and_then(|d| d.fix.clone())
2141            .unwrap_or_else(|| panic!("no fix for {code}: {report:#?}"))
2142            .patch
2143    }
2144
2145    #[test]
2146    fn patch_add_replace_remove() {
2147        let doc = json!({ "a": [1, 3], "b": { "c": 1 } });
2148        let out = apply_patch(
2149            &doc,
2150            &[
2151                add("/a/1", json!(2)),
2152                add("/a/-", json!(4)),
2153                PatchOp::Replace {
2154                    path: "/b/c".into(),
2155                    value: json!(2),
2156                },
2157                add("/b/d~1e", json!(true)),
2158                PatchOp::Remove {
2159                    path: "/a/0".into(),
2160                },
2161            ],
2162        )
2163        .unwrap();
2164        assert_eq!(out, json!({ "a": [2, 3, 4], "b": { "c": 2, "d/e": true } }));
2165    }
2166
2167    #[test]
2168    fn patch_is_atomic_and_reports_the_failing_op() {
2169        let doc = json!({ "a": 1 });
2170        let err = apply_patch(
2171            &doc,
2172            &[
2173                add("/b", json!(2)),
2174                PatchOp::Replace {
2175                    path: "/missing".into(),
2176                    value: json!(0),
2177                },
2178            ],
2179        )
2180        .unwrap_err();
2181        assert_eq!(err.index, 1);
2182        assert_eq!(err.path, "/missing");
2183        assert!(apply_patch(&doc, &[add("/x/y", json!(1))]).is_err());
2184        assert!(apply_patch(&json!([1]), &[add("/01", json!(1))]).is_err());
2185        assert!(apply_patch(&json!([1]), &[add("/2", json!(1))]).is_err());
2186        assert!(apply_patch(&doc, &[PatchOp::Remove { path: "".into() }]).is_err());
2187    }
2188
2189    #[test]
2190    fn patch_ops_use_rfc6902_json() {
2191        let op: PatchOp =
2192            serde_json::from_value(json!({ "op": "add", "path": "/a", "value": 1 })).unwrap();
2193        assert_eq!(op, add("/a", json!(1)));
2194        assert_eq!(
2195            serde_json::to_value(PatchOp::Remove { path: "/a".into() }).unwrap(),
2196            json!({ "op": "remove", "path": "/a" })
2197        );
2198    }
2199
2200    #[test]
2201    fn catalog_examples_deserialize() {
2202        let catalog = catalog();
2203        for g in &catalog.guards {
2204            serde_json::from_value::<gemini_adk_rs::flow::Guard>(g.example.clone())
2205                .unwrap_or_else(|e| panic!("guard {}: {e}", g.name));
2206        }
2207        for p in &catalog.policies {
2208            let policy: Policy = serde_json::from_value(p.example.clone())
2209                .unwrap_or_else(|e| panic!("policy {}: {e}", p.name));
2210            assert_eq!(serde_json::to_value(&policy).unwrap()["kind"], p.name);
2211        }
2212        for b in &catalog.tool_bindings {
2213            serde_json::from_value::<super::super::ToolSpec>(b.example.clone())
2214                .unwrap_or_else(|e| panic!("binding {}: {e}", b.name));
2215        }
2216        for r in &catalog.resume {
2217            serde_json::from_value::<crate::conversation::Resume>(r.example.clone())
2218                .unwrap_or_else(|e| panic!("resume {}: {e}", r.name));
2219        }
2220        for m in &catalog.modalities {
2221            serde_json::from_value::<super::super::SpecModality>(json!(m)).unwrap();
2222        }
2223        for v in &catalog.voices {
2224            let voice: gemini_genai_rs::prelude::Voice = serde_json::from_value(json!(v)).unwrap();
2225            assert_eq!(&voice.to_string(), v);
2226            assert!(!matches!(voice, gemini_genai_rs::prelude::Voice::Custom(_)));
2227        }
2228    }
2229
2230    #[test]
2231    fn catalog_lists_every_question_rule() {
2232        // Every question id the rules can produce has a catalog entry.
2233        let doc = json!({
2234            "modality": "audio",
2235            "tools": [{ "name": "book_table" }],
2236            "conversation": {
2237                "name": "c",
2238                "stages": [
2239                    { "id": "collect", "say": "s", "collect": ["card_number"], "allow": ["book_table"],
2240                      "next": [{ "to": "done", "when": { "called_ok": "book_table" } }] },
2241                    { "id": "done", "terminal": true }
2242                ]
2243            }
2244        });
2245        let ids: BTreeSet<String> = plan(&doc, &Decisions::new())
2246            .questions
2247            .into_iter()
2248            .map(|q| q.id.split(':').next().unwrap().to_string())
2249            .collect();
2250        let catalog: BTreeSet<String> = catalog()
2251            .questions
2252            .into_iter()
2253            .map(|q| q.name.split(':').next().unwrap().to_string())
2254            .collect();
2255        assert_eq!(ids, catalog);
2256    }
2257
2258    #[test]
2259    fn a_complete_spec_checks_clean_and_has_one_question() {
2260        let doc = booking();
2261        let report = check(&doc);
2262        assert!(report.valid, "{report:#?}");
2263        assert!(report.diagnostics.is_empty(), "{report:#?}");
2264        let plan = plan(&doc, &Decisions::new());
2265        let ids: Vec<&str> = plan.questions.iter().map(|q| q.id.as_str()).collect();
2266        assert_eq!(ids, ["commit_gate:book_table"]);
2267        assert!(!plan.ready);
2268    }
2269
2270    #[test]
2271    fn misspelled_fields_are_reported_with_a_rename() {
2272        let mut doc = booking();
2273        let instruction = doc["instruction"].take();
2274        doc.as_object_mut().unwrap().remove("instruction");
2275        doc["instructions"] = instruction;
2276        doc["conversation"]["stages"][0]["colect"] = json!(["x"]);
2277        doc["$schema"] = json!("ignored");
2278        let report = check(&doc);
2279        let unknown: Vec<_> = report
2280            .diagnostics
2281            .iter()
2282            .filter(|d| d.code == "unknown_field")
2283            .map(|d| d.path.clone().unwrap())
2284            .collect();
2285        assert_eq!(unknown, ["/instructions", "/conversation/stages/0/colect"]);
2286        let fixed = apply_patch(&doc, &fix(&report, "unknown_field")).unwrap();
2287        assert_eq!(fixed["instruction"], "Book tables for Trattoria Rustica.");
2288        assert!(fixed.get("instructions").is_none());
2289    }
2290
2291    #[test]
2292    fn a_misspelled_code_field_is_reported_with_a_rename() {
2293        let mut doc = booking();
2294        doc["code"] = json!({ "fucntions": [], "limits": { "call": 5 } });
2295        let report = check(&doc);
2296        let unknown: Vec<_> = report
2297            .diagnostics
2298            .iter()
2299            .filter(|d| d.code == "unknown_field")
2300            .map(|d| d.path.clone().unwrap())
2301            .collect();
2302        assert_eq!(unknown, ["/code/fucntions", "/code/limits/call"]);
2303        let renames: Vec<_> = report
2304            .diagnostics
2305            .iter()
2306            .filter_map(|d| d.fix.as_ref().map(|f| f.description.clone()))
2307            .collect();
2308        assert!(renames.contains(&"rename 'fucntions' to 'functions'".to_string()));
2309        assert!(renames.contains(&"rename 'call' to 'calls'".to_string()));
2310    }
2311
2312    #[test]
2313    fn unknown_tools_get_a_path_and_a_fix() {
2314        let mut doc = booking();
2315        doc["conversation"]["stages"][1]["allow"] = json!(["book_tabel"]);
2316        let report = check(&doc);
2317        assert!(!report.valid);
2318        let d = &report.diagnostics[0];
2319        assert_eq!(d.code, "unknown_tool");
2320        assert_eq!(d.path.as_deref(), Some("/conversation/stages/1/allow/0"));
2321        // The validator's own message is not repeated.
2322        assert!(!codes(&report).contains(&"validation"), "{report:#?}");
2323        let fixed = apply_patch(&doc, &fix(&report, "unknown_tool")).unwrap();
2324        assert!(check(&fixed).valid);
2325
2326        // No close match: declare it.
2327        let mut doc = booking();
2328        doc["conversation"]["stages"][1]["allow"] = json!(["refund"]);
2329        let report = check(&doc);
2330        let fixed = apply_patch(&doc, &fix(&report, "unknown_tool")).unwrap();
2331        assert_eq!(fixed["tools"][2], json!({ "name": "refund" }));
2332        assert!(check(&fixed).valid, "{:#?}", check(&fixed));
2333    }
2334
2335    #[test]
2336    fn unwritten_commit_key_gets_a_signal_extractor() {
2337        let mut doc = booking();
2338        doc["conversation"]["stages"][1]["commit"] =
2339            json!({ "tool": "book_table", "when": { "is_true": "user_confirmed" } });
2340        let report = check(&doc);
2341        assert_eq!(codes(&report), ["unwritten_key"], "{report:#?}");
2342        assert_eq!(
2343            report.diagnostics[0].path.as_deref(),
2344            Some("/conversation/stages/1/commit/when/is_true")
2345        );
2346        let fixed = apply_patch(&doc, &fix(&report, "unwritten_key")).unwrap();
2347        let signals = &fixed["extract"][0];
2348        assert_eq!(
2349            signals["schema"]["properties"]["user_confirmed"]["type"],
2350            "boolean"
2351        );
2352        assert_eq!(
2353            signals["promote"][1],
2354            json!({ "field": "user_confirmed", "policy": "true_only" })
2355        );
2356        assert!(check(&fixed).diagnostics.is_empty());
2357    }
2358
2359    #[test]
2360    fn unwritten_key_prefers_a_close_written_key() {
2361        let mut doc = booking();
2362        doc["conversation"]["stages"][0]["next"][0]["when"] =
2363            json!({ "all": [{ "captured": ["party_sise"] }, { "is_set": "slot" }] });
2364        let report = check(&doc);
2365        let d = report
2366            .diagnostics
2367            .iter()
2368            .find(|d| d.code == "unwritten_key")
2369            .unwrap();
2370        assert_eq!(
2371            d.path.as_deref(),
2372            Some("/conversation/stages/0/next/0/when/all/0/captured/0")
2373        );
2374        let fixed = apply_patch(&doc, &fix(&report, "unwritten_key")).unwrap();
2375        assert!(check(&fixed).diagnostics.is_empty());
2376    }
2377
2378    #[test]
2379    fn digression_triggers_and_handoff_intents_need_a_writer() {
2380        // Validation does not see digression triggers; check does.
2381        let mut doc = booking();
2382        doc.as_object_mut().unwrap().remove("extract");
2383        doc["conversation"]["overlays"] = json!([{
2384            "name": "cancel",
2385            "trigger": { "is_true": "intent:cancel" },
2386            "stages": [{ "id": "bye", "say": "Say goodbye.", "terminal": true }],
2387            "resume": "terminate"
2388        }]);
2389        let report = check(&doc);
2390        let paths: Vec<_> = report
2391            .diagnostics
2392            .iter()
2393            .filter(|d| d.code == "unwritten_key")
2394            .map(|d| d.path.clone().unwrap())
2395            .collect();
2396        assert_eq!(
2397            paths,
2398            [
2399                "/conversation/overlays/0/trigger/is_true",
2400                "/conversation/policies/0/intents/0"
2401            ]
2402        );
2403        // One fix at a time, checking again in between.
2404        for _ in 0..2 {
2405            let report = check(&doc);
2406            doc = apply_patch(&doc, &fix(&report, "unwritten_key")).unwrap();
2407        }
2408        assert!(check(&doc).diagnostics.is_empty(), "{:#?}", check(&doc));
2409        let promote = &doc["extract"][0]["promote"];
2410        assert_eq!(promote[0]["to"], "intent:cancel");
2411        assert_eq!(promote[1]["to"], "intent:human_agent");
2412    }
2413
2414    #[test]
2415    fn invalid_documents_are_reported_not_planned() {
2416        let report = check_str("{\"name\": ");
2417        assert_eq!(codes(&report), ["invalid_json"]);
2418        assert!(report.diagnostics[0].message.contains("line 1"));
2419        assert_eq!(codes(&check(&json!([]))), ["not_an_object"]);
2420        let doc = json!({ "name": 3 });
2421        assert_eq!(codes(&check(&doc)), ["invalid_spec"]);
2422        let plan = plan(&doc, &Decisions::new());
2423        assert!(plan.questions.is_empty() && !plan.ready);
2424    }
2425
2426    #[test]
2427    fn validation_messages_pass_through() {
2428        let mut doc = booking();
2429        doc["conversation"]["stages"][1]["commit"] =
2430            json!({ "tool": "book_table", "when": "always" });
2431        let report = check(&doc);
2432        assert!(!report.valid);
2433        assert!(
2434            report
2435                .diagnostics
2436                .iter()
2437                .any(|d| d.code == "validation" && d.message.contains("always-true"))
2438        );
2439    }
2440
2441    #[test]
2442    fn plan_asks_the_open_questions_blocking_first() {
2443        let doc = json!({
2444            "modality": "audio",
2445            "tools": [{ "name": "book_table" }],
2446            "conversation": {
2447                "name": "booking",
2448                "stages": [
2449                    { "id": "collect", "say": "s", "collect": ["party_size", "card_number"],
2450                      "next": [{ "to": "confirm", "when": { "captured": ["party_size"] } }] },
2451                    { "id": "confirm", "say": "c", "allow": ["book_table"],
2452                      "next": [{ "to": "done", "when": { "called_ok": "book_table" } }] },
2453                    { "id": "done", "terminal": true }
2454                ]
2455            }
2456        });
2457        let plan = plan(&doc, &Decisions::new());
2458        let ids: Vec<&str> = plan.questions.iter().map(|q| q.id.as_str()).collect();
2459        assert_eq!(
2460            ids,
2461            [
2462                "name",
2463                "instruction",
2464                "tool_description:book_table",
2465                "commit_gate:book_table",
2466                "redact:card_number",
2467                "voice",
2468                "greeting",
2469                "escalation",
2470                "disclosure",
2471                "tool_binding:book_table",
2472            ]
2473        );
2474        assert_eq!(plan.blocking, 5);
2475        // A committing tool is bound with POST.
2476        let binding = plan.questions.last().unwrap();
2477        let http = binding.options.iter().find(|o| o.value == "http").unwrap();
2478        assert_eq!(
2479            http.patch,
2480            [add(
2481                "/tools/0/http",
2482                json!({ "method": "POST", "url": ANSWER_PLACEHOLDER })
2483            )]
2484        );
2485        assert!(!plan.ready);
2486        for q in &plan.questions {
2487            if let Some(default) = &q.default {
2488                let option = q.options.iter().find(|o| &o.value == default).unwrap();
2489                assert!(!option.needs_value, "{} default needs a value", q.id);
2490            }
2491        }
2492    }
2493
2494    #[test]
2495    fn answering_everything_makes_the_spec_ready() {
2496        let doc = json!({
2497            "modality": "audio",
2498            "tools": [{ "name": "book_table" }],
2499            "conversation": {
2500                "name": "booking",
2501                "stages": [
2502                    { "id": "collect", "say": "s", "collect": ["party_size", "card_number"],
2503                      "next": [{ "to": "confirm", "when": { "captured": ["party_size"] } }] },
2504                    { "id": "confirm", "say": "c", "allow": ["book_table"],
2505                      "next": [{ "to": "done", "when": { "called_ok": "book_table" } }] },
2506                    { "id": "done", "terminal": true }
2507                ],
2508                "require": ["done"]
2509            }
2510        });
2511        let answers = [
2512            Answer::with_value("name", json!("trattoria")),
2513            Answer::with_value("instruction", json!("Book tables.")),
2514            Answer::with_value("tool_description:book_table", json!("Book a table.")),
2515            Answer::choose("commit_gate:book_table", "confirm"),
2516            Answer::choose("redact:card_number", "redact"),
2517            Answer::choose("voice", "Kore"),
2518            Answer {
2519                id: "greeting".into(),
2520                choice: None,
2521                value: None,
2522            },
2523            Answer::choose("escalation", "handoff"),
2524            Answer {
2525                id: "disclosure".into(),
2526                choice: Some("read".into()),
2527                value: Some(json!("This call is with an automated assistant.")),
2528            },
2529            Answer {
2530                id: "tool_binding:book_table".into(),
2531                choice: Some("mcp".into()),
2532                value: Some(json!("python tools/server.py")),
2533            },
2534        ];
2535        let mut answers = answers.to_vec();
2536        // Answering `escalation` declares the transfer tool, which then has
2537        // its own binding question.
2538        answers.push(Answer::choose("tool_binding:handoff_to_staff", "stub"));
2539        let out = answer(&doc, &answers, &Decisions::new()).unwrap();
2540        assert_eq!(out.applied.len(), answers.len());
2541        assert_eq!(out.decisions["greeting"], "speak_first");
2542        let spec = &out.spec;
2543        assert_eq!(spec["voice"], "Kore");
2544        assert_eq!(
2545            spec["conversation"]["stages"][1]["commit"],
2546            json!({ "tool": "book_table", "when": { "is_true": "book_table_confirmed" } })
2547        );
2548        assert_eq!(
2549            spec["conversation"]["policies"],
2550            json!([{ "kind": "redact", "keys": ["card_number"] }])
2551        );
2552        assert_eq!(spec["conversation"]["overlays"][0]["name"], "handoff");
2553        assert_eq!(spec["tools"][1]["name"], "handoff_to_staff");
2554        // Both signals share one extractor.
2555        assert_eq!(spec["extract"].as_array().unwrap().len(), 1);
2556        assert_eq!(spec["extract"][0]["promote"].as_array().unwrap().len(), 2);
2557        assert_eq!(spec["tools"][0]["mcp"], "python tools/server.py");
2558
2559        let report = check(spec);
2560        assert!(report.diagnostics.is_empty(), "{report:#?}");
2561        let plan = plan(spec, &out.decisions);
2562        assert!(plan.questions.is_empty() && plan.ready, "{plan:#?}");
2563    }
2564
2565    #[tokio::test]
2566    async fn the_generated_handoff_admits_only_the_transfer() {
2567        // A terminal digression stage restricts nothing on the turn it is
2568        // entered; the generated one admits only the transfer until it runs.
2569        let doc = booking();
2570        let mut doc = doc;
2571        doc["conversation"]
2572            .as_object_mut()
2573            .unwrap()
2574            .remove("policies");
2575        doc.as_object_mut().unwrap().remove("extract");
2576        let out = answer(
2577            &doc,
2578            &[Answer::choose("escalation", "handoff")],
2579            &Decisions::new(),
2580        )
2581        .unwrap();
2582        let mut spec = out.spec;
2583        spec["scenarios"] = json!([{
2584            "name": "asking for a person admits only the transfer",
2585            "steps": [
2586                { "set": { "key": "intent:human_agent", "value": true } },
2587                "turn",
2588                { "expect_denied": "book_table" },
2589                { "expect_denied": "check_availability" },
2590                { "expect_allowed": "handoff_to_staff" },
2591                { "tool_ok": "handoff_to_staff" },
2592                "turn",
2593                { "expect_denied": "handoff_to_staff" },
2594                { "expect_denied": "book_table" }
2595            ]
2596        }]);
2597        assert!(check(&spec).valid, "{:#?}", check(&spec));
2598        let reports = SessionSpec::from_value(spec).unwrap().run_scenarios().await;
2599        assert!(reports.iter().all(|r| r.passed), "{reports:#?}");
2600    }
2601
2602    #[test]
2603    fn decisions_suppress_questions_that_leave_the_spec_unchanged() {
2604        let doc = json!({
2605            "name": "a", "instruction": "b", "modality": "audio", "voice": "Puck",
2606            "greeting": "Hi."
2607        });
2608        assert!(plan(&doc, &Decisions::new()).questions.is_empty());
2609        let mut doc = doc;
2610        doc.as_object_mut().unwrap().remove("greeting");
2611        let out = answer(
2612            &doc,
2613            &[Answer::choose("greeting", "wait")],
2614            &Decisions::new(),
2615        )
2616        .unwrap();
2617        assert_eq!(out.spec, doc);
2618        assert!(plan(&out.spec, &out.decisions).questions.is_empty());
2619        assert_eq!(
2620            answer(
2621                &out.spec,
2622                &[Answer::choose("greeting", "wait")],
2623                &out.decisions
2624            ),
2625            Err(AnswerError::NotOpen("greeting".into()))
2626        );
2627    }
2628
2629    #[test]
2630    fn bad_answers_change_nothing() {
2631        let doc = json!({ "modality": "audio", "instruction": "x" });
2632        let none = Decisions::new();
2633        assert_eq!(
2634            answer(&doc, &[Answer::choose("voice", "Nope")], &none).unwrap_err(),
2635            AnswerError::UnknownChoice {
2636                id: "voice".into(),
2637                choice: "Nope".into(),
2638                options: VOICES.iter().map(|v| (*v).to_string()).collect(),
2639            }
2640        );
2641        assert!(matches!(
2642            answer(&doc, &[Answer::with_value("name", json!(""))], &none),
2643            Err(AnswerError::MissingValue { .. })
2644        ));
2645        assert!(matches!(
2646            answer(&doc, &[Answer::with_value("name", json!(7))], &none),
2647            Err(AnswerError::Invalid { .. })
2648        ));
2649        // A later failure discards earlier answers.
2650        assert!(
2651            answer(
2652                &doc,
2653                &[
2654                    Answer::with_value("name", json!("a")),
2655                    Answer::choose("nope", "x")
2656                ],
2657                &none
2658            )
2659            .is_err()
2660        );
2661    }
2662
2663    #[test]
2664    fn commit_gate_skips_read_only_tools() {
2665        let mut doc = booking();
2666        doc["conversation"]["stages"][1]["allow"] = json!(["book_table", "check_availability"]);
2667        let ids: Vec<String> = plan(&doc, &Decisions::new())
2668            .questions
2669            .into_iter()
2670            .map(|q| q.id)
2671            .collect();
2672        assert_eq!(ids, ["commit_gate:book_table"]);
2673        assert!(looks_committing(&SessionSpec::default(), "cancel-order"));
2674        assert!(!looks_committing(&SessionSpec::default(), "lookup_order"));
2675        assert!(looks_committing(&SessionSpec::default(), "bookTable"));
2676        assert!(looks_sensitive("card_number") && looks_sensitive("cardNumber"));
2677        assert!(looks_sensitive("dateOfBirth") && looks_sensitive("SSN"));
2678        assert!(!looks_sensitive("shipping_address") && !looks_sensitive("spinach"));
2679        assert_eq!(name_parts("bookTable-v2"), ["book", "table", "v2"]);
2680    }
2681}