Skip to main content

glass_browser/
task_protocol.rs

1//! Strict, bounded authored tasks for deterministic Web IR compilation.
2//!
3//! This module defines the input boundary only. Validation is side-effect free;
4//! compilation and browser execution remain separate follow-on layers.
5
6use crate::web_ir::WebIrEntityKind;
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9use std::error::Error;
10use std::fmt::{Display, Formatter};
11
12/// Version of the authored Task Protocol contract.
13pub const TASK_PROTOCOL_SCHEMA_VERSION: u32 = 1;
14pub(crate) const MAX_INPUTS: usize = 64;
15pub(crate) const MAX_INPUT_NAME_BYTES: usize = 64;
16const MAX_INPUT_VALUE_BYTES: usize = 4_096;
17pub(crate) const MAX_POSTCONDITIONS: usize = 32;
18pub(crate) const MAX_EXPECTATION_BYTES: usize = 256;
19const MAX_ACTIONS: u32 = 256;
20const MAX_TIMEOUT_MS: u64 = 120_000;
21const MAX_ITEMS: u32 = 4_096;
22
23/// Supported deterministic task families.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25pub enum TaskKind {
26    #[serde(rename = "form.inspect")]
27    FormInspect,
28    #[serde(rename = "form.fill")]
29    FormFill,
30    #[serde(rename = "form.validate")]
31    FormValidate,
32    #[serde(rename = "form.submit")]
33    FormSubmit,
34    #[serde(rename = "navigation.follow")]
35    NavigationFollow,
36    #[serde(rename = "navigation.selectTab")]
37    NavigationSelectTab,
38    #[serde(rename = "navigation.openMenu")]
39    NavigationOpenMenu,
40    #[serde(rename = "table.extract")]
41    TableExtract,
42    #[serde(rename = "collection.extract")]
43    CollectionExtract,
44    #[serde(rename = "region.extract")]
45    RegionExtract,
46    #[serde(rename = "field.read")]
47    FieldRead,
48    #[serde(rename = "dialog.inspect")]
49    DialogInspect,
50    #[serde(rename = "dialog.confirm")]
51    DialogConfirm,
52    #[serde(rename = "dialog.cancel")]
53    DialogCancel,
54    #[serde(rename = "pagination.next")]
55    PaginationNext,
56    #[serde(rename = "pagination.collect")]
57    PaginationCollect,
58}
59
60/// Effect class declared by the task author.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "camelCase")]
63pub enum TaskRiskClass {
64    ReadOnly,
65    LocalMutation,
66    RemoteReversible,
67    RemoteIrreversible,
68    Authentication,
69    DataDisclosure,
70    UnknownRisk,
71}
72
73/// Behavior when semantic resolution returns more than one candidate.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
75#[serde(rename_all = "camelCase")]
76pub enum TaskAmbiguityPolicy {
77    #[default]
78    Fail,
79    RequireConfirmation,
80}
81
82/// Revision policy requested by the task author.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
84#[serde(rename_all = "camelCase")]
85pub enum TaskRevisionPolicy {
86    #[default]
87    Exact,
88    Compatible,
89    Reextract,
90}
91
92/// Typed postcondition families reserved for the compiler and verifier.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95pub enum TaskPostconditionKind {
96    PageKind,
97    RegionPresent,
98    EntityState,
99    NavigationOccurred,
100    DialogClosed,
101    ValidationClear,
102    RecordsExtracted,
103}
104
105/// Semantic task scope; it contains no selectors or browser handles.
106#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase", deny_unknown_fields)]
108pub struct TaskScope {
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub region_name: Option<String>,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub entity_kind: Option<WebIrEntityKind>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub entity_name: Option<String>,
115}
116
117/// Bounded execution limits declared before compilation.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase", deny_unknown_fields)]
120pub struct TaskLimits {
121    pub max_actions: u32,
122    pub timeout_ms: u64,
123    pub max_items: u32,
124}
125
126impl Default for TaskLimits {
127    fn default() -> Self {
128        Self {
129            max_actions: 16,
130            timeout_ms: 15_000,
131            max_items: 128,
132        }
133    }
134}
135
136/// One typed success condition for a compiled task.
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase", deny_unknown_fields)]
139pub struct TaskPostcondition {
140    pub kind: TaskPostconditionKind,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub expected: Option<String>,
143}
144
145impl TaskPostcondition {
146    pub(crate) fn validate_at(&self, index: usize) -> Result<(), TaskProtocolError> {
147        if let Some(expected) = &self.expected
148            && (expected.len() > MAX_EXPECTATION_BYTES || expected.chars().any(char::is_control))
149        {
150            return Err(TaskProtocolError::new(
151                format!("postconditions[{index}].expected"),
152                "expected value exceeds its bound or contains a control character",
153            ));
154        }
155        match self.kind {
156            TaskPostconditionKind::RegionPresent => {
157                let Some(expected) = self.expected.as_deref() else {
158                    return Err(TaskProtocolError::new(
159                        format!("postconditions[{index}].expected"),
160                        "regionPresent requires the expected semantic region name",
161                    ));
162                };
163                validate_text(
164                    &format!("postconditions[{index}].expected"),
165                    expected,
166                    MAX_EXPECTATION_BYTES,
167                )?;
168            }
169            TaskPostconditionKind::PageKind => {
170                if let Some(expected) = self.expected.as_deref() {
171                    validate_text(
172                        &format!("postconditions[{index}].expected"),
173                        expected,
174                        MAX_EXPECTATION_BYTES,
175                    )?;
176                }
177            }
178            TaskPostconditionKind::EntityState => {
179                let Some(expected) = self.expected.as_deref() else {
180                    return Err(TaskProtocolError::new(
181                        format!("postconditions[{index}].expected"),
182                        "entityState requires '<entity-name>.<state>=<true|false>'",
183                    ));
184                };
185                let Some((selector, expected_value)) = expected.rsplit_once('=') else {
186                    return Err(TaskProtocolError::new(
187                        format!("postconditions[{index}].expected"),
188                        "entityState requires '<entity-name>.<state>=<true|false>'",
189                    ));
190                };
191                let Some((entity_name, state)) = selector.rsplit_once('.') else {
192                    return Err(TaskProtocolError::new(
193                        format!("postconditions[{index}].expected"),
194                        "entityState requires '<entity-name>.<state>=<true|false>'",
195                    ));
196                };
197                if entity_name.trim().is_empty()
198                    || !matches!(
199                        state,
200                        "disabled" | "readOnly" | "required" | "checked" | "empty"
201                    )
202                    || !matches!(expected_value, "true" | "false")
203                {
204                    return Err(TaskProtocolError::new(
205                        format!("postconditions[{index}].expected"),
206                        "entityState selector, state, or boolean value is invalid",
207                    ));
208                }
209            }
210            _ => {}
211        }
212
213        Ok(())
214    }
215}
216
217/// Versioned declarative task input accepted by Glass.
218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
219#[serde(rename_all = "camelCase", deny_unknown_fields)]
220pub struct GlassTask {
221    pub schema_version: u32,
222    pub task: TaskKind,
223    pub scope: TaskScope,
224    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
225    pub inputs: BTreeMap<String, String>,
226    pub limits: TaskLimits,
227    pub risk: TaskRiskClass,
228    #[serde(default)]
229    pub ambiguity: TaskAmbiguityPolicy,
230    #[serde(default)]
231    pub revision: TaskRevisionPolicy,
232    #[serde(default, skip_serializing_if = "Vec::is_empty")]
233    pub postconditions: Vec<TaskPostcondition>,
234}
235
236impl GlassTask {
237    /// Parse strict authored JSON into a task.
238    pub fn from_json(input: &str) -> Result<Self, TaskProtocolError> {
239        let task: Self = serde_json::from_str(input)
240            .map_err(|error| TaskProtocolError::new("$", error.to_string()))?;
241        task.validate()?;
242        Ok(task)
243    }
244
245    /// Validate the authored task without browser access or mutation.
246    pub fn validate(&self) -> Result<(), TaskProtocolError> {
247        if self.risk == TaskRiskClass::UnknownRisk {
248            return Err(TaskProtocolError::new(
249                "risk",
250                "unknown risk cannot be compiled; declare a bounded risk class",
251            ));
252        }
253
254        if self.schema_version != TASK_PROTOCOL_SCHEMA_VERSION {
255            return Err(TaskProtocolError::new(
256                "schemaVersion",
257                "unsupported Task Protocol schema version",
258            ));
259        }
260        self.scope.validate()?;
261        self.scope.validate_for_task(self.task)?;
262        self.limits.validate()?;
263        if self.inputs.len() > MAX_INPUTS {
264            return Err(TaskProtocolError::new(
265                "inputs",
266                "input count exceeds the Task Protocol bound",
267            ));
268        }
269        for (name, value) in &self.inputs {
270            validate_text("inputs.name", name, MAX_INPUT_NAME_BYTES)?;
271            if value.len() > MAX_INPUT_VALUE_BYTES || value.chars().any(char::is_control) {
272                return Err(TaskProtocolError::new(
273                    format!("inputs.{name}"),
274                    "input value exceeds its bound or contains a control character",
275                ));
276            }
277        }
278        validate_input_contract(self.task, &self.inputs)?;
279
280        if self.postconditions.len() > MAX_POSTCONDITIONS {
281            return Err(TaskProtocolError::new(
282                "postconditions",
283                "postcondition count exceeds the Task Protocol bound",
284            ));
285        }
286        for (index, postcondition) in self.postconditions.iter().enumerate() {
287            if !postcondition_allowed_for(self.task, postcondition.kind) {
288                return Err(TaskProtocolError::new(
289                    format!("postconditions[{index}].kind"),
290                    "postcondition kind is incompatible with the task family",
291                ));
292            }
293            postcondition.validate_at(index)?;
294            if postcondition.kind == TaskPostconditionKind::RecordsExtracted
295                && let Some(expected) = postcondition.expected.as_deref()
296            {
297                let minimum = expected.parse::<u32>().map_err(|_| {
298                    TaskProtocolError::new(
299                        format!("postconditions[{index}].expected"),
300                        "recordsExtracted expected must be a non-negative integer",
301                    )
302                })?;
303                if minimum > self.limits.max_items {
304                    return Err(TaskProtocolError::new(
305                        format!("postconditions[{index}].expected"),
306                        "recordsExtracted expected exceeds task maxItems",
307                    ));
308                }
309            }
310        }
311        if matches!(self.task, TaskKind::FormSubmit) && self.postconditions.is_empty() {
312            return Err(TaskProtocolError::new(
313                "postconditions",
314                "form.submit requires at least one bounded postcondition",
315            ));
316        }
317        if matches!(self.task, TaskKind::FormFill) && self.inputs.is_empty() {
318            return Err(TaskProtocolError::new(
319                "inputs",
320                "form.fill requires at least one bounded input",
321            ));
322        }
323        if matches!(
324            self.task,
325            TaskKind::FormInspect
326                | TaskKind::FormFill
327                | TaskKind::FormValidate
328                | TaskKind::FormSubmit
329                | TaskKind::FieldRead
330                | TaskKind::NavigationSelectTab
331                | TaskKind::PaginationNext
332                | TaskKind::NavigationOpenMenu
333                | TaskKind::PaginationCollect
334                | TaskKind::TableExtract
335                | TaskKind::CollectionExtract
336                | TaskKind::RegionExtract
337        ) && self.scope.region_name.is_none()
338        {
339            return Err(TaskProtocolError::new(
340                "scope.regionName",
341                "browser-backed task requires a semantic region scope",
342            ));
343        }
344
345        match self.task {
346            TaskKind::FormSubmit if !self.inputs.contains_key("submit") => {
347                return Err(TaskProtocolError::new(
348                    "inputs.submit",
349                    "form.submit requires the semantic submit target in inputs.submit",
350                ));
351            }
352            TaskKind::FormSubmit if self.inputs.keys().any(|name| name != "submit") => {
353                return Err(TaskProtocolError::new(
354                    "inputs",
355                    "form.submit accepts only the submit target input",
356                ));
357            }
358            TaskKind::NavigationOpenMenu if !self.inputs.contains_key("menu") => {
359                return Err(TaskProtocolError::new(
360                    "inputs.menu",
361                    "navigation.openMenu requires a bounded menu input",
362                ));
363            }
364            TaskKind::NavigationSelectTab if !self.inputs.contains_key("tab") => {
365                return Err(TaskProtocolError::new(
366                    "inputs.tab",
367                    "navigation.selectTab requires a bounded tab input",
368                ));
369            }
370            TaskKind::PaginationCollect if !self.inputs.contains_key("next") => {
371                return Err(TaskProtocolError::new(
372                    "inputs.next",
373                    "pagination.collect requires a bounded next control input",
374                ));
375            }
376            TaskKind::PaginationNext if !self.inputs.contains_key("next") => {
377                return Err(TaskProtocolError::new(
378                    "inputs.next",
379                    "pagination.next requires a bounded next control input",
380                ));
381            }
382            TaskKind::NavigationFollow if !self.inputs.contains_key("url") => {
383                return Err(TaskProtocolError::new(
384                    "inputs.url",
385                    "navigation.follow requires a bounded url input",
386                ));
387            }
388            TaskKind::FieldRead if !self.inputs.contains_key("field") => {
389                return Err(TaskProtocolError::new(
390                    "inputs.field",
391                    "field.read requires the semantic field name in inputs.field",
392                ));
393            }
394            _ => {}
395        }
396        Ok(())
397    }
398
399    /// Serialize a validated task deterministically.
400    pub fn to_canonical_json(&self) -> Result<String, TaskProtocolError> {
401        self.validate()?;
402        serde_json::to_string(self).map_err(|error| TaskProtocolError::new("$", error.to_string()))
403    }
404}
405
406impl TaskLimits {
407    pub(crate) fn validate(&self) -> Result<(), TaskProtocolError> {
408        if !(1..=MAX_ACTIONS).contains(&self.max_actions) {
409            return Err(TaskProtocolError::new(
410                "limits.maxActions",
411                "maxActions must be between 1 and 256",
412            ));
413        }
414        if !(1..=MAX_TIMEOUT_MS).contains(&self.timeout_ms) {
415            return Err(TaskProtocolError::new(
416                "limits.timeoutMs",
417                "timeoutMs must be between 1 and 120000",
418            ));
419        }
420        if !(1..=MAX_ITEMS).contains(&self.max_items) {
421            return Err(TaskProtocolError::new(
422                "limits.maxItems",
423                "maxItems must be between 1 and 4096",
424            ));
425        }
426        Ok(())
427    }
428}
429
430impl TaskScope {
431    pub(crate) fn validate(&self) -> Result<(), TaskProtocolError> {
432        if self.region_name.is_none() && self.entity_kind.is_none() && self.entity_name.is_none() {
433            return Err(TaskProtocolError::new(
434                "scope",
435                "scope requires a semantic region or entity constraint",
436            ));
437        }
438        if let Some(region_name) = &self.region_name {
439            validate_text("scope.regionName", region_name, 128)?;
440        }
441        if let Some(entity_name) = &self.entity_name {
442            validate_text("scope.entityName", entity_name, 128)?;
443        }
444        if self.entity_name.is_some() && self.entity_kind.is_none() {
445            return Err(TaskProtocolError::new(
446                "scope.entityKind",
447                "entityName requires entityKind",
448            ));
449        }
450        Ok(())
451    }
452    pub(crate) fn validate_for_task(&self, task: TaskKind) -> Result<(), TaskProtocolError> {
453        if task == TaskKind::RegionExtract {
454            if let Some(actual) = self.entity_kind
455                && !matches!(
456                    actual,
457                    WebIrEntityKind::Region
458                        | WebIrEntityKind::Form
459                        | WebIrEntityKind::Table
460                        | WebIrEntityKind::Collection
461                        | WebIrEntityKind::Dialog
462                )
463            {
464                return Err(TaskProtocolError::new(
465                    "scope.entityKind",
466                    "entity kind is incompatible with region extraction",
467                ));
468            }
469            return Ok(());
470        }
471        let expected_kind = match task {
472            TaskKind::FormInspect
473            | TaskKind::FormFill
474            | TaskKind::FormValidate
475            | TaskKind::FormSubmit => WebIrEntityKind::Form,
476            TaskKind::FieldRead => WebIrEntityKind::Field,
477            TaskKind::NavigationSelectTab => WebIrEntityKind::Tab,
478            TaskKind::NavigationOpenMenu => WebIrEntityKind::NavigationItem,
479            TaskKind::TableExtract => WebIrEntityKind::Table,
480            TaskKind::CollectionExtract => WebIrEntityKind::Collection,
481            TaskKind::RegionExtract => WebIrEntityKind::Region,
482            TaskKind::DialogInspect | TaskKind::DialogConfirm | TaskKind::DialogCancel => {
483                WebIrEntityKind::Dialog
484            }
485            TaskKind::PaginationNext | TaskKind::PaginationCollect => {
486                WebIrEntityKind::PaginationControl
487            }
488            TaskKind::NavigationFollow => WebIrEntityKind::Page,
489        };
490        if let Some(actual) = self.entity_kind
491            && actual != expected_kind
492        {
493            return Err(TaskProtocolError::new(
494                "scope.entityKind",
495                "entity kind is incompatible with the task family",
496            ));
497        }
498        Ok(())
499    }
500}
501
502pub(crate) fn postcondition_allowed_for(task: TaskKind, kind: TaskPostconditionKind) -> bool {
503    use TaskPostconditionKind::*;
504    match task {
505        TaskKind::FormInspect | TaskKind::FormFill | TaskKind::FormValidate => {
506            matches!(
507                kind,
508                ValidationClear | RegionPresent | PageKind | EntityState
509            )
510        }
511        TaskKind::FormSubmit => matches!(
512            kind,
513            NavigationOccurred
514                | ValidationClear
515                | RegionPresent
516                | PageKind
517                | DialogClosed
518                | EntityState
519        ),
520        TaskKind::NavigationFollow => matches!(kind, NavigationOccurred | RegionPresent | PageKind),
521        TaskKind::NavigationSelectTab | TaskKind::NavigationOpenMenu => {
522            matches!(kind, RegionPresent | PageKind | EntityState)
523        }
524
525        TaskKind::TableExtract | TaskKind::CollectionExtract | TaskKind::RegionExtract => {
526            matches!(kind, RecordsExtracted | RegionPresent | PageKind)
527        }
528        TaskKind::FieldRead => matches!(kind, RegionPresent | PageKind | EntityState),
529        TaskKind::DialogInspect => matches!(kind, DialogClosed | RegionPresent | PageKind),
530        TaskKind::DialogConfirm | TaskKind::DialogCancel => {
531            matches!(kind, DialogClosed | PageKind)
532        }
533        TaskKind::PaginationNext => matches!(
534            kind,
535            NavigationOccurred | RecordsExtracted | RegionPresent | PageKind
536        ),
537        TaskKind::PaginationCollect => {
538            matches!(kind, RecordsExtracted | RegionPresent | PageKind)
539        }
540    }
541}
542fn validate_input_contract(
543    task: TaskKind,
544    inputs: &BTreeMap<String, String>,
545) -> Result<(), TaskProtocolError> {
546    let expected = match task {
547        TaskKind::FormFill => return Ok(()),
548        TaskKind::FormSubmit => &["submit"][..],
549        TaskKind::NavigationFollow => &["url"][..],
550        TaskKind::NavigationSelectTab => &["tab"][..],
551        TaskKind::NavigationOpenMenu => &["menu"][..],
552        TaskKind::FieldRead => &["field"][..],
553        TaskKind::PaginationNext | TaskKind::PaginationCollect => &["next"][..],
554        TaskKind::FormInspect
555        | TaskKind::FormValidate
556        | TaskKind::TableExtract
557        | TaskKind::CollectionExtract
558        | TaskKind::RegionExtract
559        | TaskKind::DialogInspect
560        | TaskKind::DialogConfirm
561        | TaskKind::DialogCancel => &[][..],
562    };
563    if expected.len() == 1 && !inputs.contains_key(expected[0]) {
564        return Ok(());
565    }
566
567    let names = inputs.keys().map(String::as_str).collect::<Vec<_>>();
568    if names.as_slice() != expected {
569        return Err(TaskProtocolError::new(
570            "inputs",
571            "input names are incompatible with the task family",
572        ));
573    }
574    Ok(())
575}
576
577fn validate_text(path: &str, value: &str, max_bytes: usize) -> Result<(), TaskProtocolError> {
578    if value.is_empty() || value.len() > max_bytes || value.chars().any(char::is_control) {
579        return Err(TaskProtocolError::new(
580            path,
581            "value must be non-empty, bounded, and free of control characters",
582        ));
583    }
584    Ok(())
585}
586
587/// Path-aware Task Protocol validation failure.
588#[derive(Debug, Clone, PartialEq, Eq)]
589pub struct TaskProtocolError {
590    pub path: String,
591    pub reason: String,
592}
593
594impl TaskProtocolError {
595    fn new(path: impl Into<String>, reason: impl Into<String>) -> Self {
596        Self {
597            path: path.into(),
598            reason: reason.into(),
599        }
600    }
601}
602
603impl Display for TaskProtocolError {
604    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
605        write!(formatter, "{}: {}", self.path, self.reason)
606    }
607}
608
609impl Error for TaskProtocolError {}
610
611#[cfg(test)]
612mod tests {
613    use super::*;
614    use serde_json::json;
615
616    fn task() -> GlassTask {
617        GlassTask {
618            schema_version: TASK_PROTOCOL_SCHEMA_VERSION,
619            task: TaskKind::FormFill,
620            scope: TaskScope {
621                region_name: Some("Shipping address".into()),
622                entity_kind: Some(WebIrEntityKind::Form),
623                entity_name: None,
624            },
625            inputs: BTreeMap::from([(String::from("city"), String::from("Kuching"))]),
626            limits: TaskLimits::default(),
627            risk: TaskRiskClass::LocalMutation,
628            ambiguity: TaskAmbiguityPolicy::Fail,
629            revision: TaskRevisionPolicy::Exact,
630            postconditions: vec![TaskPostcondition {
631                kind: TaskPostconditionKind::ValidationClear,
632                expected: None,
633            }],
634        }
635    }
636
637    #[test]
638    fn valid_task_round_trips_canonically() {
639        let task = task();
640        let first = task.to_canonical_json().unwrap();
641        let second = GlassTask::from_json(&first)
642            .unwrap()
643            .to_canonical_json()
644            .unwrap();
645        assert_eq!(first, second);
646        assert!(first.contains("form.fill"));
647        assert!(first.contains("Shipping"));
648    }
649
650    #[test]
651    fn authored_json_rejects_unknown_fields() {
652        let mut value = serde_json::to_value(task()).unwrap();
653        value["futureField"] = json!(true);
654        let error = GlassTask::from_json(&value.to_string()).unwrap_err();
655        assert_eq!(error.path, "$");
656    }
657
658    #[test]
659    fn validation_rejects_empty_scope_and_unbounded_limits() {
660        let mut invalid = task();
661        invalid.scope = TaskScope::default();
662        assert_eq!(invalid.validate().unwrap_err().path, "scope");
663        invalid = task();
664        invalid.limits.max_actions = 0;
665        assert_eq!(invalid.validate().unwrap_err().path, "limits.maxActions");
666        invalid = task();
667        invalid.limits.timeout_ms = MAX_TIMEOUT_MS + 1;
668        assert_eq!(invalid.validate().unwrap_err().path, "limits.timeoutMs");
669    }
670
671    #[test]
672    fn form_fill_requires_inputs_and_entity_names_require_kinds() {
673        let mut invalid = task();
674        invalid.inputs.clear();
675        assert_eq!(invalid.validate().unwrap_err().path, "inputs");
676        invalid = task();
677        invalid.scope.entity_name = Some("Email".into());
678        invalid.scope.entity_kind = None;
679        assert_eq!(invalid.validate().unwrap_err().path, "scope.entityKind");
680    }
681
682    #[test]
683    fn field_read_requires_semantic_field_input() {
684        let mut invalid = task();
685        invalid.postconditions.clear();
686        invalid.task = TaskKind::FieldRead;
687        invalid.scope.entity_kind = Some(WebIrEntityKind::Field);
688        assert_eq!(invalid.validate().unwrap_err().path, "inputs.field");
689    }
690
691    #[test]
692    fn entity_state_postconditions_require_a_bounded_boolean_predicate() {
693        let mut authored = task();
694        authored.postconditions = vec![TaskPostcondition {
695            kind: TaskPostconditionKind::EntityState,
696            expected: Some("Email.disabled=false".into()),
697        }];
698        authored.validate().unwrap();
699
700        for invalid in [
701            "Email.disabled",
702            "Email.value=private",
703            "Email.unknown=true",
704            ".disabled=true",
705        ] {
706            authored.postconditions[0].expected = Some(invalid.into());
707            assert_eq!(
708                authored.validate().unwrap_err().path,
709                "postconditions[0].expected"
710            );
711        }
712    }
713
714    #[test]
715    fn browser_backed_tasks_require_region_scope() {
716        let mut invalid = task();
717        invalid.postconditions.clear();
718        invalid.task = TaskKind::FieldRead;
719        invalid.scope.entity_kind = Some(WebIrEntityKind::Field);
720        invalid.scope.region_name = None;
721        assert_eq!(invalid.validate().unwrap_err().path, "scope.regionName");
722    }
723
724    #[test]
725    fn navigation_follow_requires_bounded_url_input() {
726        let mut task = task();
727        task.postconditions.clear();
728        task.task = TaskKind::NavigationFollow;
729        task.scope.entity_kind = Some(WebIrEntityKind::Page);
730        task.inputs.clear();
731        assert_eq!(task.validate().unwrap_err().path, "inputs.url");
732        task.inputs
733            .insert("url".into(), "https://example.test/next".into());
734        task.validate().unwrap();
735        task.task = TaskKind::NavigationSelectTab;
736        task.scope.entity_kind = Some(WebIrEntityKind::Tab);
737        task.inputs.clear();
738        assert_eq!(task.validate().unwrap_err().path, "inputs.tab");
739        task.inputs.insert("tab".into(), "Payment".into());
740        task.validate().unwrap();
741        task.task = TaskKind::NavigationOpenMenu;
742        task.scope.entity_kind = Some(WebIrEntityKind::NavigationItem);
743        task.inputs.clear();
744        assert_eq!(task.validate().unwrap_err().path, "inputs.menu");
745        task.inputs.insert("menu".into(), "Products".into());
746        task.validate().unwrap();
747        task.task = TaskKind::PaginationNext;
748        task.scope.entity_kind = Some(WebIrEntityKind::PaginationControl);
749        task.inputs.clear();
750        assert_eq!(task.validate().unwrap_err().path, "inputs.next");
751        task.inputs.insert("next".into(), "Next page".into());
752        task.validate().unwrap();
753    }
754    #[test]
755    fn pagination_collect_requires_bounded_next_input() {
756        let mut task = task();
757        task.postconditions.clear();
758        task.task = TaskKind::PaginationCollect;
759        task.scope.entity_kind = Some(WebIrEntityKind::PaginationControl);
760        task.inputs.clear();
761        assert_eq!(task.validate().unwrap_err().path, "inputs.next");
762        task.inputs.insert("next".into(), "Next page".into());
763        task.validate().unwrap();
764    }
765
766    #[test]
767    fn region_extract_accepts_structural_region_kinds() {
768        for entity_kind in [
769            WebIrEntityKind::Region,
770            WebIrEntityKind::Form,
771            WebIrEntityKind::Table,
772            WebIrEntityKind::Collection,
773            WebIrEntityKind::Dialog,
774        ] {
775            let mut authored = task();
776            authored.task = TaskKind::RegionExtract;
777            authored.scope.entity_kind = Some(entity_kind);
778            authored.inputs.clear();
779            authored.postconditions = vec![TaskPostcondition {
780                kind: TaskPostconditionKind::RecordsExtracted,
781                expected: Some("0".into()),
782            }];
783            authored.validate().unwrap();
784        }
785    }
786
787    #[test]
788    fn form_submit_requires_a_postcondition() {
789        let mut task = task();
790        task.task = TaskKind::FormSubmit;
791        task.inputs = BTreeMap::from([(String::from("submit"), String::from("Submit"))]);
792        task.postconditions.clear();
793        assert_eq!(task.validate().unwrap_err().path, "postconditions");
794        task.postconditions.push(TaskPostcondition {
795            kind: TaskPostconditionKind::NavigationOccurred,
796            expected: None,
797        });
798        task.validate().unwrap();
799    }
800
801    #[test]
802    fn unknown_risk_is_rejected_fail_closed() {
803        let mut invalid = task();
804        invalid.risk = TaskRiskClass::UnknownRisk;
805        assert_eq!(invalid.validate().unwrap_err().path, "risk");
806    }
807
808    #[test]
809    fn task_families_reject_ignored_input_names() {
810        let mut invalid = task();
811        invalid.task = TaskKind::FormInspect;
812        invalid.inputs = BTreeMap::from([(String::from("ignored"), String::from("value"))]);
813        assert_eq!(invalid.validate().unwrap_err().path, "inputs");
814    }
815
816    #[test]
817    fn region_postconditions_require_a_verifiable_name() {
818        let mut invalid = task();
819        invalid.postconditions = vec![TaskPostcondition {
820            kind: TaskPostconditionKind::RegionPresent,
821            expected: None,
822        }];
823        assert_eq!(
824            invalid.validate().unwrap_err().path,
825            "postconditions[0].expected"
826        );
827    }
828
829    #[test]
830    fn navigation_and_dialog_tasks_allow_non_region_semantic_scopes() {
831        let mut navigation = task();
832        navigation.task = TaskKind::NavigationFollow;
833        navigation.scope.region_name = None;
834        navigation.scope.entity_kind = Some(WebIrEntityKind::Page);
835        navigation.inputs = BTreeMap::from([(
836            String::from("url"),
837            String::from("https://example.test/next"),
838        )]);
839        navigation.postconditions = vec![TaskPostcondition {
840            kind: TaskPostconditionKind::NavigationOccurred,
841            expected: None,
842        }];
843        navigation.validate().unwrap();
844
845        for kind in [
846            TaskKind::DialogInspect,
847            TaskKind::DialogConfirm,
848            TaskKind::DialogCancel,
849        ] {
850            let mut dialog = task();
851            dialog.task = kind;
852            dialog.scope.region_name = None;
853            dialog.scope.entity_kind = Some(WebIrEntityKind::Dialog);
854            dialog.inputs.clear();
855            dialog.postconditions = vec![TaskPostcondition {
856                kind: TaskPostconditionKind::DialogClosed,
857                expected: None,
858            }];
859            dialog.validate().unwrap();
860        }
861    }
862}