Skip to main content

gemini_adk_rs/extract/
mod.rs

1//! The extraction kit — `Extract` records with deterministic recognizers.
2//!
3//! An [`Extract`] record declares typed fields, each filled by a [`Recognizer`]
4//! that reads the conversation transcript on the CPU — no model, no network, no
5//! accelerator. It compiles to a [`TurnExtractor`] (so it plugs into the
6//! existing extraction pipeline) and promotes recognized fields into governed
7//! `State`, where `Flow` guards (`done(captured([...]))`) and repair read them.
8//!
9//! This is the deterministic, transcript-sourced slice of the kit. LLM / fetch
10//! / MCP / agent *resolvers* and the `#[derive(Extract)]` macro layer on top of
11//! this same record model.
12//!
13//! ```
14//! use gemini_adk_rs::extract::{Extract, Recognizer};
15//!
16//! let order = Extract::record("order")
17//!     .field("quantity", Recognizer::integer())
18//!     .field("item", Recognizer::one_of(["pizza", "salad", "soda"]))
19//!     .field("confirmed", Recognizer::yes_no())
20//!     .window(3)
21//!     .build();
22//! ```
23
24use std::future::Future;
25use std::sync::Arc;
26use std::time::{Duration, Instant};
27
28use async_trait::async_trait;
29use dashmap::DashMap;
30use regex::Regex;
31use serde_json::Value;
32use std::sync::LazyLock;
33
34use crate::AsyncSourceFn;
35use crate::live::extractor::{ExtractionTrigger, FieldPromotion, OnComplete, TurnExtractor};
36use crate::live::transcript::TranscriptTurn;
37use crate::llm::LlmError;
38use crate::orchestration::AgentMode;
39use crate::state::State;
40use crate::text::TextAgent;
41
42static MONEY_RE: LazyLock<Regex> = LazyLock::new(|| {
43    Regex::new(r"\$?\s?(\d{1,3}(?:,\d{3})*|\d+)(?:\.(\d{1,2}))?")
44        .expect("MONEY_RE literal is a valid regex")
45});
46static INT_RE: LazyLock<Regex> =
47    LazyLock::new(|| Regex::new(r"-?\d+").expect("INT_RE literal is a valid regex"));
48static DATE_RE: LazyLock<Regex> = LazyLock::new(|| {
49    Regex::new(r"\b\d{4}-\d{2}-\d{2}\b").expect("DATE_RE literal is a valid regex")
50});
51// 12-hour clock with an am/pm marker: "3pm", "3:30 pm".
52static TIME12_RE: LazyLock<Regex> = LazyLock::new(|| {
53    Regex::new(r"(?i)\b(\d{1,2})(?::(\d{2}))?\s*([ap]m)\b")
54        .expect("TIME12_RE literal is a valid regex")
55});
56// 24-hour clock: "15:00", "09:30".
57static TIME24_RE: LazyLock<Regex> = LazyLock::new(|| {
58    Regex::new(r"\b([01]?\d|2[0-3]):([0-5]\d)\b").expect("TIME24_RE literal is a valid regex")
59});
60
61/// Normalize a clock time found in `text` to a 24-hour `"HH:MM"` string.
62fn parse_time(text: &str) -> Option<String> {
63    if let Some(c) = TIME12_RE.captures(text) {
64        let mut hour: u32 = c.get(1)?.as_str().parse().ok()?;
65        let min: u32 = c.get(2).map(|m| m.as_str()).unwrap_or("00").parse().ok()?;
66        let pm = c.get(3)?.as_str().eq_ignore_ascii_case("pm");
67        if hour > 12 {
68            return None; // "13pm" is not a real time
69        }
70        if pm && hour < 12 {
71            hour += 12;
72        } else if !pm && hour == 12 {
73            hour = 0; // 12am -> 00:00
74        }
75        return Some(format!("{hour:02}:{min:02}"));
76    }
77    let c = TIME24_RE.captures(text)?;
78    Some(format!(
79        "{:02}:{}",
80        c.get(1)?.as_str().parse::<u32>().ok()?,
81        c.get(2)?.as_str()
82    ))
83}
84
85/// A deterministic transcript recognizer: `text -> (value, confidence)`.
86///
87/// Recognizers run on the CPU over the user transcript. Confidence is in
88/// `0.0..=1.0`; deterministic matches are high-confidence, fuzzy matches carry
89/// their similarity score.
90#[derive(Clone)]
91pub enum Recognizer {
92    /// First integer in the text. If `near` is non-empty, at least one anchor
93    /// word must be present for the match to count.
94    Integer {
95        /// Anchor words that must appear for the integer to be recognized.
96        near: Vec<String>,
97    },
98    /// A monetary amount (`$1,250.00`, `200`) → JSON number.
99    Money,
100    /// First capture group (or whole match) of a regex → string.
101    Regex(Regex),
102    /// The first option that appears (case-insensitive substring) → string.
103    OneOf(Vec<String>),
104    /// The option with the best Jaro-Winkler similarity ≥ `min` → string.
105    /// Useful for ASR-mangled names matched against a roster.
106    Fuzzy {
107        /// Candidate values to match against.
108        options: Vec<String>,
109        /// Minimum similarity in `0.0..=1.0`.
110        min: f64,
111    },
112    /// Affirmative/negative detection → boolean.
113    YesNo,
114    /// A calendar/clock expression → a JSON object with any of the keys
115    /// `date` (`YYYY-MM-DD`), `time` (24h `HH:MM`), `day` (`today`/`tomorrow`/
116    /// `tonight`/`yesterday`), `weekday`, and `part` (`morning`/`afternoon`/
117    /// `evening`/`noon`/`midnight`). Deterministic, on-device — a small
118    /// Duckling-style normalizer, not a full grammar.
119    DateTime,
120}
121
122impl Recognizer {
123    /// First integer, optionally anchored to nearby words.
124    pub fn integer() -> Self {
125        Recognizer::Integer { near: Vec::new() }
126    }
127    /// Integer recognized only when one of `anchors` is present.
128    pub fn integer_near<I, S>(anchors: I) -> Self
129    where
130        I: IntoIterator<Item = S>,
131        S: Into<String>,
132    {
133        Recognizer::Integer {
134            near: anchors.into_iter().map(Into::into).collect(),
135        }
136    }
137    /// A monetary amount.
138    pub fn money() -> Self {
139        Recognizer::Money
140    }
141    /// A regex (first capture group, or the whole match).
142    pub fn regex(pattern: &str) -> Self {
143        Recognizer::Regex(Regex::new(pattern).expect("invalid recognizer regex"))
144    }
145    /// Match against a fixed set of options (case-insensitive substring).
146    pub fn one_of<I, S>(options: I) -> Self
147    where
148        I: IntoIterator<Item = S>,
149        S: Into<String>,
150    {
151        Recognizer::OneOf(options.into_iter().map(Into::into).collect())
152    }
153    /// Fuzzy-match against options with a default 0.85 threshold.
154    pub fn fuzzy<I, S>(options: I) -> Self
155    where
156        I: IntoIterator<Item = S>,
157        S: Into<String>,
158    {
159        Recognizer::Fuzzy {
160            options: options.into_iter().map(Into::into).collect(),
161            min: 0.85,
162        }
163    }
164    /// Affirmative/negative.
165    pub fn yes_no() -> Self {
166        Recognizer::YesNo
167    }
168    /// A calendar/clock expression normalized to a JSON object.
169    pub fn datetime() -> Self {
170        Recognizer::DateTime
171    }
172
173    /// Recognize a value in `text`, with a confidence in `0.0..=1.0`.
174    pub fn recognize(&self, text: &str) -> Option<(Value, f32)> {
175        let lower = text.to_lowercase();
176        match self {
177            Recognizer::Integer { near } => {
178                if !near.is_empty() && !near.iter().any(|a| lower.contains(&a.to_lowercase())) {
179                    return None;
180                }
181                let m = INT_RE.find(text)?;
182                m.as_str()
183                    .parse::<i64>()
184                    .ok()
185                    .map(|n| (Value::from(n), 1.0))
186            }
187            Recognizer::Money => {
188                let caps = MONEY_RE.captures(text)?;
189                let whole = caps.get(1)?.as_str().replace(',', "");
190                let cents = caps.get(2).map(|c| c.as_str()).unwrap_or("0");
191                let amount: f64 = format!("{whole}.{cents:0<2}").parse().ok()?;
192                Some((Value::from(amount), 1.0))
193            }
194            Recognizer::Regex(re) => {
195                let caps = re.captures(text)?;
196                let s = caps.get(1).or_else(|| caps.get(0))?.as_str().to_string();
197                Some((Value::from(s), 1.0))
198            }
199            Recognizer::OneOf(options) => options
200                .iter()
201                .find(|o| lower.contains(&o.to_lowercase()))
202                .map(|o| (Value::from(o.clone()), 1.0)),
203            Recognizer::Fuzzy { options, min } => {
204                let mut best: Option<(&String, f64)> = None;
205                for opt in options {
206                    let ol = opt.to_lowercase();
207                    // Best similarity of the option against the whole text and each word.
208                    let sim = std::iter::once(lower.as_str())
209                        .chain(lower.split_whitespace())
210                        .map(|w| strsim::jaro_winkler(&ol, w))
211                        .fold(0.0_f64, f64::max);
212                    if sim >= *min && best.map(|(_, b)| sim > b).unwrap_or(true) {
213                        best = Some((opt, sim));
214                    }
215                }
216                best.map(|(opt, sim)| (Value::from(opt.clone()), sim as f32))
217            }
218            Recognizer::YesNo => {
219                // Whole-word tokens (keeping apostrophes so "don't" stays intact),
220                // so "incorrect" doesn't match "correct" and "another" doesn't match
221                // "no". Negation is checked first: "not correct"/"don't confirm" → false.
222                const NO: &[&str] = &[
223                    "no",
224                    "nope",
225                    "nah",
226                    "not",
227                    "don't",
228                    "dont",
229                    "doesn't",
230                    "isn't",
231                    "won't",
232                    "never",
233                    "incorrect",
234                    "wrong",
235                    "negative",
236                ];
237                const YES: &[&str] = &[
238                    "yes",
239                    "yeah",
240                    "yep",
241                    "yup",
242                    "sure",
243                    "correct",
244                    "confirm",
245                    "confirmed",
246                    "ok",
247                    "okay",
248                    "right",
249                    "affirmative",
250                ];
251                let tokens: Vec<&str> = lower
252                    .split(|c: char| !(c.is_alphanumeric() || c == '\''))
253                    .filter(|t| !t.is_empty())
254                    .collect();
255                if tokens.iter().any(|t| NO.contains(t)) {
256                    Some((Value::Bool(false), 0.9))
257                } else if tokens.iter().any(|t| YES.contains(t)) {
258                    Some((Value::Bool(true), 0.9))
259                } else {
260                    None
261                }
262            }
263            Recognizer::DateTime => {
264                const WEEKDAYS: &[&str] = &[
265                    "monday",
266                    "tuesday",
267                    "wednesday",
268                    "thursday",
269                    "friday",
270                    "saturday",
271                    "sunday",
272                ];
273                let mut obj = serde_json::Map::new();
274                if let Some(m) = DATE_RE.find(text) {
275                    obj.insert("date".into(), Value::from(m.as_str().to_string()));
276                }
277                if let Some(t) = parse_time(&lower) {
278                    obj.insert("time".into(), Value::from(t));
279                }
280                if let Some(d) = ["today", "tomorrow", "tonight", "yesterday"]
281                    .into_iter()
282                    .find(|d| lower.contains(d))
283                {
284                    obj.insert("day".into(), Value::from(d));
285                }
286                if let Some(w) = WEEKDAYS.iter().find(|w| lower.contains(*w)) {
287                    obj.insert("weekday".into(), Value::from(*w));
288                }
289                if let Some(p) = ["morning", "afternoon", "evening", "noon", "midnight"]
290                    .into_iter()
291                    .find(|p| lower.contains(p))
292                {
293                    obj.insert("part".into(), Value::from(p));
294                }
295                if obj.is_empty() {
296                    None
297                } else {
298                    Some((Value::Object(obj), 1.0))
299                }
300            }
301        }
302    }
303}
304
305/// How a field is filled.
306#[derive(Clone)]
307enum Source {
308    /// Deterministic transcript recognizer (sync, no state).
309    Recognize(Recognizer),
310    /// Async resolver: bind `args` from `State`, fetch, optionally cache.
311    Resolve {
312        /// State keys bound into the args object passed to the fetcher.
313        args: Vec<String>,
314        /// Optional cache time-to-live keyed by `(field, canonical args)`.
315        ttl: Option<Duration>,
316        /// The async fetcher.
317        /// (An [`AsyncSourceFn`] bound from the args object, not the whole `State`.)
318        fetch: AsyncSourceFn<Value>,
319    },
320}
321
322/// Post-recognition validator: a recognized value is only promoted when this
323/// returns `true`.
324type FieldValidator = Arc<dyn Fn(&Value) -> bool + Send + Sync>;
325
326/// A field in an [`Extract`] record.
327#[derive(Clone)]
328pub struct Field {
329    name: String,
330    source: Source,
331    state_key: String,
332    overwrite: bool,
333    /// Optional predicate; a recognized value failing it is rejected (not promoted).
334    validate: Option<FieldValidator>,
335}
336
337/// A declarative extraction record: typed fields filled by recognizers and/or
338/// async resolvers.
339#[derive(Clone)]
340pub struct Extract {
341    name: String,
342    fields: Vec<Field>,
343    window: usize,
344    trigger: ExtractionTrigger,
345    on_complete: Option<OnComplete>,
346}
347
348impl Extract {
349    /// Start building a record with the given extractor name.
350    pub fn record(name: impl Into<String>) -> ExtractBuilder {
351        ExtractBuilder {
352            name: name.into(),
353            fields: Vec::new(),
354            window: 3,
355            trigger: ExtractionTrigger::EveryTurn,
356            on_complete: None,
357        }
358    }
359
360    /// Compile into a [`TurnExtractor`] for registration.
361    pub fn into_extractor(self) -> Arc<dyn TurnExtractor> {
362        Arc::new(RecordExtractor::new(self))
363    }
364
365    /// The `(field name, state key)` pairs this record promotes. Callers that run
366    /// the extractor and promote the returned record into `State` themselves (e.g.
367    /// the simulation harness) use this to map each field to its state key.
368    pub fn field_state_keys(&self) -> Vec<(String, String)> {
369        self.fields
370            .iter()
371            .map(|f| (f.name.clone(), f.state_key.clone()))
372            .collect()
373    }
374}
375
376/// Builder for an [`Extract`] record.
377pub struct ExtractBuilder {
378    name: String,
379    fields: Vec<Field>,
380    window: usize,
381    trigger: ExtractionTrigger,
382    on_complete: Option<OnComplete>,
383}
384
385impl ExtractBuilder {
386    /// Add a field filled by `recognizer`, promoted to a state key of the same name.
387    pub fn field(mut self, name: impl Into<String>, recognizer: Recognizer) -> Self {
388        let name = name.into();
389        self.fields.push(Field {
390            state_key: name.clone(),
391            name,
392            source: Source::Recognize(recognizer),
393            overwrite: false,
394            validate: None,
395        });
396        self
397    }
398    /// Add a field promoted to a custom state key.
399    pub fn field_to(
400        mut self,
401        name: impl Into<String>,
402        state_key: impl Into<String>,
403        recognizer: Recognizer,
404    ) -> Self {
405        self.fields.push(Field {
406            name: name.into(),
407            state_key: state_key.into(),
408            source: Source::Recognize(recognizer),
409            overwrite: false,
410            validate: None,
411        });
412        self
413    }
414    /// Add a field filled by an **async resolver** — a tool call, HTTP fetch, or
415    /// MCP request. `args` names the `State` keys bound into the JSON object
416    /// passed to `fetch`; the returned value becomes the field. With a `ttl`,
417    /// results are memoized by `(field, canonical args)` for that duration.
418    pub fn field_resolve<I, S, F, Fut>(
419        mut self,
420        name: impl Into<String>,
421        args: I,
422        ttl: Option<Duration>,
423        fetch: F,
424    ) -> Self
425    where
426        I: IntoIterator<Item = S>,
427        S: Into<String>,
428        F: Fn(Value) -> Fut + Send + Sync + 'static,
429        Fut: Future<Output = Result<Value, String>> + Send + 'static,
430    {
431        let name = name.into();
432        let fetch = Arc::new(fetch);
433        self.fields.push(Field {
434            state_key: name.clone(),
435            name,
436            source: Source::Resolve {
437                args: args.into_iter().map(Into::into).collect(),
438                ttl,
439                fetch: Arc::new(move |a| {
440                    let fetch = fetch.clone();
441                    Box::pin(async move { fetch(a).await })
442                }),
443            },
444            overwrite: false,
445            validate: None,
446        });
447        self
448    }
449    /// Attach a validator to the **most recently added** field: a recognized
450    /// value is promoted only when `predicate` returns `true` (else it is
451    /// rejected, as if no value was recognized this turn).
452    pub fn validate<F>(mut self, predicate: F) -> Self
453    where
454        F: Fn(&Value) -> bool + Send + Sync + 'static,
455    {
456        if let Some(field) = self.fields.last_mut() {
457            field.validate = Some(Arc::new(predicate));
458        }
459        self
460    }
461
462    /// Number of recent turns the recognizers read (default 3).
463    pub fn window(mut self, n: usize) -> Self {
464        self.window = n;
465        self
466    }
467    /// When the record runs (default `EveryTurn`).
468    pub fn trigger(mut self, trigger: ExtractionTrigger) -> Self {
469        self.trigger = trigger;
470        self
471    }
472    /// Run `agent` (in `mode`) when this record lands fields in state — the
473    /// `on_complete(dispatch(agent))` effect. Its result lands in `{name}:result`.
474    pub fn on_complete(mut self, agent: Arc<dyn TextAgent>, mode: AgentMode) -> Self {
475        self.on_complete = Some(OnComplete { agent, mode });
476        self
477    }
478    /// Finalize the record.
479    pub fn build(self) -> Extract {
480        Extract {
481            name: self.name,
482            fields: self.fields,
483            window: self.window,
484            trigger: self.trigger,
485            on_complete: self.on_complete,
486        }
487    }
488}
489
490/// A [`TurnExtractor`] that runs an [`Extract`] record's recognizers and
491/// resolvers, and promotes the recognized fields into state.
492pub struct RecordExtractor {
493    spec: Extract,
494    promotions: Vec<FieldPromotion>,
495    /// Per-field resolver cache keyed by `(field, canonical args)`.
496    cache: Arc<DashMap<String, (Value, Instant)>>,
497}
498
499impl RecordExtractor {
500    /// Build from a record spec.
501    pub fn new(spec: Extract) -> Self {
502        let promotions = spec
503            .fields
504            .iter()
505            .map(|f| {
506                let p = if f.overwrite {
507                    FieldPromotion::overwrite(&f.name)
508                } else {
509                    FieldPromotion::keep_known(&f.name)
510                };
511                p.to(&f.state_key)
512            })
513            .collect();
514        Self {
515            spec,
516            promotions,
517            cache: Arc::new(DashMap::new()),
518        }
519    }
520
521    /// Resolve one async field, honoring the per-field TTL cache.
522    ///
523    /// Args bind from `fresh` (values recognized in *this* turn, keyed by their
524    /// state key) first, then from session `State` — so a resolver sees a slot
525    /// recognized in the same utterance, not a stale value.
526    async fn resolve_field(
527        &self,
528        field: &str,
529        args: &[String],
530        ttl: Option<Duration>,
531        fetch: &AsyncSourceFn<Value>,
532        fresh: &serde_json::Map<String, Value>,
533        state: &State,
534    ) -> Option<Value> {
535        // Bind args, preferring this turn's recognitions (skip absent keys).
536        let mut obj = serde_json::Map::new();
537        for key in args {
538            if let Some(v) = fresh.get(key).cloned().or_else(|| state.get::<Value>(key)) {
539                obj.insert(key.clone(), v);
540            }
541        }
542        let args_value = Value::Object(obj);
543        let cache_key = format!("{field}|{args_value}");
544        if let Some(ttl) = ttl
545            && let Some(entry) = self.cache.get(&cache_key)
546            && state.clock().since(entry.1) < ttl
547        {
548            return Some(entry.0.clone());
549        }
550        match fetch(args_value).await {
551            Ok(value) => {
552                if ttl.is_some() {
553                    self.cache
554                        .insert(cache_key, (value.clone(), state.clock().now()));
555                }
556                Some(value)
557            }
558            Err(e) => {
559                tracing::warn!(field, "resolver failed: {e}");
560                None
561            }
562        }
563    }
564}
565
566#[async_trait]
567impl TurnExtractor for RecordExtractor {
568    fn name(&self) -> &str {
569        &self.spec.name
570    }
571
572    fn window_size(&self) -> usize {
573        self.spec.window
574    }
575
576    fn trigger(&self) -> ExtractionTrigger {
577        self.spec.trigger.clone()
578    }
579
580    fn promotion_rules(&self) -> &[FieldPromotion] {
581        &self.promotions
582    }
583
584    fn on_complete(&self) -> Option<OnComplete> {
585        self.spec.on_complete.clone()
586    }
587
588    async fn extract(&self, window: &[TranscriptTurn]) -> Result<Value, LlmError> {
589        // Recognizer-only path (no State): used by callers that don't bind args.
590        let text = window
591            .iter()
592            .map(|t| t.user.as_str())
593            .collect::<Vec<_>>()
594            .join(" ");
595        let mut obj = serde_json::Map::new();
596        for field in &self.spec.fields {
597            if let Source::Recognize(rec) = &field.source
598                && let Some((value, _confidence)) = rec.recognize(&text)
599            {
600                if field.validate.as_ref().is_some_and(|v| !v(&value)) {
601                    continue; // recognized but rejected by the slot validator
602                }
603                obj.insert(field.name.clone(), value);
604            }
605        }
606        Ok(Value::Object(obj))
607    }
608
609    async fn extract_with_state(
610        &self,
611        window: &[TranscriptTurn],
612        state: &State,
613    ) -> Result<Value, LlmError> {
614        let text = window
615            .iter()
616            .map(|t| t.user.as_str())
617            .collect::<Vec<_>>()
618            .join(" ");
619        let mut obj = serde_json::Map::new();
620        // Sync recognizers over the transcript. `fresh` maps each recognized
621        // field's *state key* to its value, so resolvers can bind args from
622        // values recognized in this same turn (before promotion runs).
623        let mut fresh = serde_json::Map::new();
624        for field in &self.spec.fields {
625            if let Source::Recognize(rec) = &field.source
626                && let Some((value, confidence)) = rec.recognize(&text)
627            {
628                if field.validate.as_ref().is_some_and(|v| !v(&value)) {
629                    continue; // recognized but rejected by the slot validator
630                }
631                // Record provenance + confidence under the `state_meta:` convention
632                // so `State::evidence()` can surface how a slot was filled.
633                let _ = state.set(
634                    format!("state_meta:{}", field.state_key),
635                    serde_json::json!({ "source": "extraction", "confidence": confidence }),
636                );
637                fresh.insert(field.state_key.clone(), value.clone());
638                obj.insert(field.name.clone(), value);
639            }
640        }
641        // Async resolvers, bound from this turn's recognitions + State.
642        let resolves = self
643            .spec
644            .fields
645            .iter()
646            .filter_map(|field| match &field.source {
647                Source::Resolve { args, ttl, fetch } => Some(async {
648                    self.resolve_field(&field.name, args, *ttl, fetch, &fresh, state)
649                        .await
650                        .map(|v| (field.name.clone(), v))
651                }),
652                Source::Recognize(_) => None,
653            });
654        for resolved in futures_util::future::join_all(resolves)
655            .await
656            .into_iter()
657            .flatten()
658        {
659            obj.insert(resolved.0, resolved.1);
660        }
661        Ok(Value::Object(obj))
662    }
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668
669    #[test]
670    fn static_regex_literals_compile() {
671        // Forces each `LazyLock`: a bad literal fails here, not at runtime.
672        for re in [&MONEY_RE, &INT_RE, &DATE_RE, &TIME12_RE, &TIME24_RE] {
673            LazyLock::force(re);
674        }
675    }
676    use serde_json::json;
677
678    fn turn(user: &str) -> TranscriptTurn {
679        TranscriptTurn {
680            turn_number: 0,
681            user: user.to_string(),
682            model: String::new(),
683            tool_calls: Vec::new(),
684            timestamp: std::time::Instant::now(),
685        }
686    }
687
688    #[test]
689    fn recognizers_basic() {
690        assert_eq!(
691            Recognizer::integer()
692                .recognize("I want 3 of them")
693                .unwrap()
694                .0,
695            json!(3)
696        );
697        assert_eq!(
698            Recognizer::money()
699                .recognize("that'll be $1,250.50")
700                .unwrap()
701                .0,
702            json!(1250.50)
703        );
704        assert_eq!(
705            Recognizer::one_of(["pizza", "salad"])
706                .recognize("a large PIZZA please")
707                .unwrap()
708                .0,
709            json!("pizza")
710        );
711        assert_eq!(
712            Recognizer::yes_no()
713                .recognize("yes that's right")
714                .unwrap()
715                .0,
716            json!(true)
717        );
718        assert_eq!(
719            Recognizer::yes_no().recognize("no thanks").unwrap().0,
720            json!(false)
721        );
722        assert!(Recognizer::yes_no().recognize("maybe later").is_none());
723    }
724
725    #[test]
726    fn yes_no_negation_wins_and_is_word_aware() {
727        let r = Recognizer::yes_no();
728        // Negation beats an affirmative substring.
729        assert_eq!(r.recognize("not correct").unwrap().0, json!(false));
730        assert_eq!(r.recognize("don't confirm that").unwrap().0, json!(false));
731        // "incorrect" must not match "correct"; it's a negation.
732        assert_eq!(r.recognize("that's incorrect").unwrap().0, json!(false));
733        // Word-aware: "another" does not contain a standalone "no".
734        assert!(r.recognize("another option").is_none());
735        // Plain affirmation still works.
736        assert_eq!(r.recognize("yes please").unwrap().0, json!(true));
737    }
738
739    #[tokio::test]
740    async fn resolver_binds_args_recognized_this_turn() {
741        // `slot` is recognized this turn (not yet in State); the resolver must
742        // bind it from the same utterance, not see it missing.
743        let spec = Extract::record("booking")
744            .field("slot", Recognizer::one_of(["morning", "afternoon"]))
745            .field_resolve("availability", ["slot"], None, |args: Value| async move {
746                Ok(json!({ "slot_seen": args.get("slot").cloned() }))
747            })
748            .build();
749        let ext = RecordExtractor::new(spec);
750        let state = State::new(); // slot is NOT in State yet
751        let out = ext
752            .extract_with_state(&[turn("afternoon works")], &state)
753            .await
754            .unwrap();
755        assert_eq!(out["slot"], json!("afternoon"));
756        assert_eq!(out["availability"], json!({ "slot_seen": "afternoon" }));
757    }
758
759    #[test]
760    fn datetime_normalizes_clock_and_calendar() {
761        let r = Recognizer::datetime();
762        // 12-hour clock with pm.
763        assert_eq!(
764            r.recognize("can we meet at 3pm").unwrap().0,
765            json!({"time": "15:00"})
766        );
767        // Minutes + am, plus a relative day.
768        assert_eq!(
769            r.recognize("tomorrow at 9:30 am works").unwrap().0,
770            json!({"time": "09:30", "day": "tomorrow"})
771        );
772        // 12am normalizes to midnight.
773        assert_eq!(
774            r.recognize("12am sharp").unwrap().0,
775            json!({"time": "00:00"})
776        );
777        // 24-hour clock + weekday + part of day + ISO date.
778        assert_eq!(
779            r.recognize("friday afternoon, 2026-06-05 at 15:00")
780                .unwrap()
781                .0,
782            json!({"date": "2026-06-05", "time": "15:00", "weekday": "friday", "part": "afternoon"})
783        );
784        // A bare integer is not a time.
785        assert!(r.recognize("a table for 4 people").is_none());
786        // "13pm" is not a real clock time.
787        assert!(r.recognize("at 13pm").is_none());
788    }
789
790    #[test]
791    fn integer_near_anchors() {
792        let r = Recognizer::integer_near(["quantity", "want"]);
793        assert_eq!(r.recognize("I want 5").unwrap().0, json!(5));
794        assert!(r.recognize("call me at 5").is_none()); // no anchor word
795    }
796
797    #[test]
798    fn fuzzy_matches_misheard_name() {
799        let r = Recognizer::fuzzy(["Johnson", "Jackson", "Jensen"]);
800        let (v, conf) = r.recognize("the name is jonson").unwrap();
801        assert_eq!(v, json!("Johnson"));
802        assert!(conf > 0.85);
803    }
804
805    #[tokio::test]
806    async fn record_extractor_captures_fields() {
807        let spec = Extract::record("order")
808            .field("quantity", Recognizer::integer_near(["want", "get"]))
809            .field("item", Recognizer::one_of(["pizza", "salad", "soda"]))
810            .window(2)
811            .build();
812        let extractor = RecordExtractor::new(spec);
813        assert_eq!(extractor.name(), "order");
814        assert_eq!(extractor.window_size(), 2);
815        assert_eq!(extractor.promotion_rules().len(), 2);
816
817        let window = vec![turn("I want 2 large pizza")];
818        let out = extractor.extract(&window).await.unwrap();
819        assert_eq!(out["quantity"], json!(2));
820        assert_eq!(out["item"], json!("pizza"));
821    }
822
823    #[tokio::test]
824    async fn record_resolves_async_field_from_state() {
825        let spec = Extract::record("booking")
826            .field("slot", Recognizer::one_of(["morning", "afternoon"]))
827            .field_resolve("availability", ["slot"], None, |args: Value| async move {
828                let slot = args.get("slot").and_then(|v| v.as_str()).unwrap_or("");
829                Ok(serde_json::json!({ "open": slot == "afternoon" }))
830            })
831            .build();
832        let ext = RecordExtractor::new(spec);
833        let state = State::new();
834        let _ = state.set("slot", "afternoon");
835        let out = ext
836            .extract_with_state(&[turn("afternoon please")], &state)
837            .await
838            .unwrap();
839        assert_eq!(out["slot"], json!("afternoon"));
840        assert_eq!(out["availability"], json!({ "open": true }));
841    }
842
843    #[tokio::test]
844    async fn resolver_field_caches_within_ttl() {
845        use std::sync::atomic::{AtomicUsize, Ordering};
846        let calls = Arc::new(AtomicUsize::new(0));
847        let counter = calls.clone();
848        let spec = Extract::record("b")
849            .field_resolve("v", ["k"], Some(Duration::from_secs(60)), move |_args| {
850                let counter = counter.clone();
851                async move {
852                    counter.fetch_add(1, Ordering::SeqCst);
853                    Ok(json!("x"))
854                }
855            })
856            .build();
857        let ext = RecordExtractor::new(spec);
858        let state = State::new();
859        let _ = state.set("k", 1);
860        let _ = ext.extract_with_state(&[turn("a")], &state).await.unwrap();
861        let _ = ext.extract_with_state(&[turn("a")], &state).await.unwrap();
862        // Identical args within the TTL → fetched once.
863        assert_eq!(calls.load(Ordering::SeqCst), 1);
864    }
865
866    #[tokio::test]
867    async fn on_complete_is_exposed() {
868        use crate::error::AgentError;
869        struct A;
870        #[async_trait]
871        impl TextAgent for A {
872            fn name(&self) -> &str {
873                "a"
874            }
875            async fn run(&self, _s: &State) -> Result<String, AgentError> {
876                Ok("done".into())
877            }
878        }
879        let spec = Extract::record("x")
880            .field("q", Recognizer::integer())
881            .on_complete(Arc::new(A), AgentMode::Dispatch)
882            .build();
883        assert!(RecordExtractor::new(spec).on_complete().is_some());
884    }
885
886    #[tokio::test]
887    async fn record_extractor_omits_unrecognized() {
888        let spec = Extract::record("order")
889            .field("item", Recognizer::one_of(["pizza"]))
890            .build();
891        let out = RecordExtractor::new(spec)
892            .extract(&[turn("hello there")])
893            .await
894            .unwrap();
895        assert!(out.as_object().unwrap().is_empty());
896    }
897}