Skip to main content

glass_browser/
task_compiler.rs

1//! Deterministic compilation from authored tasks and stable Glass Web IR v1.
2//!
3//! Compilation is browser-free: it binds intent to bounded semantic entities,
4//! emits explicit evidence and revision guards, and never carries input values.
5
6use crate::extraction::{EvidenceQuality, EvidenceSource};
7use crate::task_protocol::{
8    GlassTask, MAX_INPUT_NAME_BYTES, MAX_INPUTS, MAX_POSTCONDITIONS, TASK_PROTOCOL_SCHEMA_VERSION,
9    TaskAmbiguityPolicy, TaskKind, TaskLimits, TaskPostcondition, TaskPostconditionKind,
10    TaskProtocolError, TaskRevisionPolicy, TaskRiskClass, TaskScope, postcondition_allowed_for,
11};
12use crate::web_ir::{
13    GlassWebIrV1, WEB_IR_SCHEMA_VERSION, WebIrAction, WebIrEntity, WebIrEntityDetails,
14    WebIrEntityKind, WebIrRelationshipKind,
15};
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18use std::collections::{BTreeMap, BTreeSet};
19use std::error::Error;
20use std::fmt::{Display, Formatter};
21
22use crate::browser::session::{
23    KnowledgeLookupContext, KnowledgeMemoryInfluence, KnowledgeRetrievalQuery,
24    KnowledgeRetrievalReport, KnowledgeStore,
25};
26/// Version of the deterministic execution-plan contract.
27pub const TASK_PLAN_SCHEMA_VERSION: u32 = 1;
28
29/// Intent-level operations emitted by the Task Protocol compiler.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(rename_all = "camelCase")]
32pub enum TaskPlanOperation {
33    ObserveScope,
34    InspectForm,
35    FillInputs,
36    ValidateForm,
37    SubmitForm,
38    FollowNavigation,
39    SelectTab,
40    OpenMenu,
41    ExtractTable,
42    ExtractCollection,
43    ExtractRegion,
44    ReadField,
45    InspectDialog,
46    ConfirmDialog,
47    CancelDialog,
48    NextPage,
49    CollectPages,
50}
51
52/// Version of the compiler logic recorded in every execution plan.
53/// Version 2 adds entity-scoped evidence, revision-bound semantic binding
54/// keys, and explicit runtime capability requirements. Version-1 plans must
55/// be recompiled from their authored task and current Web IR before execution.
56pub const TASK_COMPILER_VERSION: u32 = 2;
57
58/// Evidence floor required before a compiled operation may execute.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(rename_all = "camelCase", deny_unknown_fields)]
61pub struct TaskEvidenceRequirements {
62    pub minimum_quality: EvidenceQuality,
63    pub required_sources: Vec<EvidenceSource>,
64    pub require_complete: bool,
65}
66
67/// Evidence required from one selected entity. This prevents unrelated page
68/// evidence from satisfying an executable operation.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "camelCase", deny_unknown_fields)]
71pub struct TaskEntityEvidenceRequirement {
72    pub entity_id: String,
73    pub minimum_quality: EvidenceQuality,
74    pub required_sources: Vec<EvidenceSource>,
75}
76
77/// Stable semantic key used by a live runtime to create an ephemeral browser
78/// binding from the exact compiled revision. It intentionally contains no
79/// browser or DOM handle.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase", deny_unknown_fields)]
82pub struct TaskEntityBindingKey {
83    pub entity_id: String,
84    pub kind: WebIrEntityKind,
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub role: Option<String>,
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub name: Option<String>,
89}
90
91/// Runtime features required to interpret a compiled plan.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase")]
94pub enum TaskRuntimeCapability {
95    Observe,
96    Read,
97    Mutate,
98    Navigate,
99    Extract,
100    Dialog,
101    Pagination,
102    VerifyEntityState,
103}
104
105/// Memory output is deliberately separated from executable plan fields. It
106/// explains advisory ranking and never supplies a target or postcondition.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[serde(rename_all = "camelCase", deny_unknown_fields)]
109pub struct TaskMemoryAdvisory {
110    pub retrieval: KnowledgeRetrievalReport,
111    pub influence: KnowledgeMemoryInfluence,
112    /// Explicit proof that memory only ranked candidates and did not alter
113    /// the executable plan derived from the current Web IR.
114    #[serde(default = "default_executable_plan_unchanged")]
115    pub executable_plan_unchanged: bool,
116}
117
118fn default_executable_plan_unchanged() -> bool {
119    false
120}
121
122#[derive(Debug, Clone, Default)]
123pub struct TaskCompilationOptions<'a> {
124    pub knowledge_store: Option<&'a KnowledgeStore>,
125    pub knowledge_context: Option<&'a KnowledgeLookupContext>,
126}
127
128/// One inspectable runtime guard emitted by compilation.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(
131    tag = "kind",
132    rename_all = "camelCase",
133    rename_all_fields = "camelCase",
134    deny_unknown_fields
135)]
136pub enum TaskPlanPrecondition {
137    RevisionEquals {
138        revision: u64,
139    },
140    EntityPresent {
141        entity_id: String,
142    },
143    EntityEnabled {
144        entity_id: String,
145    },
146    ActionSupported {
147        entity_id: String,
148        action: WebIrAction,
149    },
150}
151
152/// One stable, typed step in an execution plan.
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(rename_all = "camelCase", deny_unknown_fields)]
155pub struct TaskPlanStep {
156    pub ordinal: u16,
157    pub operation: TaskPlanOperation,
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub input_names: Vec<String>,
160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
161    pub entity_ids: Vec<String>,
162    #[serde(default)]
163    pub requires_confirmation: bool,
164}
165
166/// Browser-free output of Task Protocol compilation.
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase", deny_unknown_fields)]
169pub struct TaskExecutionPlan {
170    pub schema_version: u32,
171    pub task_schema_version: u32,
172    pub compiler_version: u32,
173    pub source_ir_schema_version: u32,
174    pub source_ir_revision: u64,
175    pub task_fingerprint: String,
176    pub task: TaskKind,
177    pub scope: TaskScope,
178    pub limits: TaskLimits,
179    pub risk: TaskRiskClass,
180    pub ambiguity: TaskAmbiguityPolicy,
181    pub revision: TaskRevisionPolicy,
182    pub confirmation_required: bool,
183    pub selected_entity_ids: Vec<String>,
184    pub evidence_requirements: TaskEvidenceRequirements,
185    #[serde(default, skip_serializing_if = "Vec::is_empty")]
186    pub entity_evidence_requirements: Vec<TaskEntityEvidenceRequirement>,
187    #[serde(default, skip_serializing_if = "Vec::is_empty")]
188    pub entity_binding_keys: Vec<TaskEntityBindingKey>,
189    #[serde(default, skip_serializing_if = "Vec::is_empty")]
190    pub required_runtime_capabilities: Vec<TaskRuntimeCapability>,
191    pub preconditions: Vec<TaskPlanPrecondition>,
192    pub steps: Vec<TaskPlanStep>,
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub memory_advisory: Option<TaskMemoryAdvisory>,
195    #[serde(default, skip_serializing_if = "Vec::is_empty")]
196    pub postconditions: Vec<TaskPostcondition>,
197}
198
199impl TaskExecutionPlan {
200    /// Validate plan invariants before handing the plan to a runtime.
201    pub fn validate(&self) -> Result<(), TaskCompilationError> {
202        if self.schema_version != TASK_PLAN_SCHEMA_VERSION {
203            return Err(TaskCompilationError::new(
204                "schemaVersion",
205                "unsupported execution-plan schema version",
206            ));
207        }
208        if self.task_schema_version != TASK_PROTOCOL_SCHEMA_VERSION {
209            return Err(TaskCompilationError::new(
210                "taskSchemaVersion",
211                "unsupported Task Protocol schema version",
212            ));
213        }
214        if self.compiler_version != TASK_COMPILER_VERSION {
215            return Err(TaskCompilationError::new(
216                "compilerVersion",
217                "unsupported task compiler version",
218            ));
219        }
220        if self.source_ir_schema_version != WEB_IR_SCHEMA_VERSION {
221            return Err(TaskCompilationError::new(
222                "sourceIrSchemaVersion",
223                "unsupported source Glass Web IR schema version",
224            ));
225        }
226        if self.task_fingerprint.len() != 64
227            || !self
228                .task_fingerprint
229                .bytes()
230                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
231        {
232            return Err(TaskCompilationError::new(
233                "taskFingerprint",
234                "task fingerprint must be a lowercase SHA-256 digest",
235            ));
236        }
237        let selected = self
238            .selected_entity_ids
239            .iter()
240            .map(String::as_str)
241            .collect::<BTreeSet<_>>();
242        if selected.is_empty() || selected.len() != self.selected_entity_ids.len() {
243            return Err(TaskCompilationError::new(
244                "selectedEntityIds",
245                "selected entity IDs must be non-empty and unique",
246            ));
247        }
248        if self.evidence_requirements.required_sources.is_empty()
249            || self
250                .evidence_requirements
251                .required_sources
252                .windows(2)
253                .any(|pair| pair[0] >= pair[1])
254        {
255            return Err(TaskCompilationError::new(
256                "evidenceRequirements.requiredSources",
257                "required evidence sources must be non-empty, sorted, and unique",
258            ));
259        }
260        if self.entity_evidence_requirements.len() != self.selected_entity_ids.len()
261            || self
262                .entity_evidence_requirements
263                .iter()
264                .map(|requirement| requirement.entity_id.as_str())
265                .collect::<BTreeSet<_>>()
266                != selected
267        {
268            return Err(TaskCompilationError::new(
269                "entityEvidenceRequirements",
270                "every selected entity must have exactly one evidence requirement",
271            ));
272        }
273        if self.entity_binding_keys.len() != self.selected_entity_ids.len()
274            || self
275                .entity_binding_keys
276                .iter()
277                .map(|binding| binding.entity_id.as_str())
278                .collect::<BTreeSet<_>>()
279                != selected
280        {
281            return Err(TaskCompilationError::new(
282                "entityBindingKeys",
283                "every selected entity must have exactly one semantic binding key",
284            ));
285        }
286        for (index, requirement) in self.entity_evidence_requirements.iter().enumerate() {
287            if requirement.required_sources.is_empty()
288                || requirement
289                    .required_sources
290                    .windows(2)
291                    .any(|pair| pair[0] >= pair[1])
292            {
293                return Err(TaskCompilationError::new(
294                    format!("entityEvidenceRequirements[{index}].requiredSources"),
295                    "entity evidence sources must be non-empty, sorted, and unique",
296                ));
297            }
298        }
299        if self.required_runtime_capabilities.is_empty()
300            || self
301                .required_runtime_capabilities
302                .windows(2)
303                .any(|pair| pair[0] >= pair[1])
304        {
305            return Err(TaskCompilationError::new(
306                "requiredRuntimeCapabilities",
307                "runtime capabilities must be non-empty, sorted, and unique",
308            ));
309        }
310        if !self.preconditions.iter().any(|precondition| {
311            matches!(
312                precondition,
313                TaskPlanPrecondition::RevisionEquals { revision }
314                    if *revision == self.source_ir_revision
315            )
316        }) {
317            return Err(TaskCompilationError::new(
318                "preconditions",
319                "plan must guard its source Web IR revision",
320            ));
321        }
322        if self.risk == TaskRiskClass::UnknownRisk {
323            return Err(TaskCompilationError::new(
324                "risk",
325                "unknown risk cannot be represented by a fail-closed execution plan",
326            ));
327        }
328
329        self.scope.validate().map_err(TaskCompilationError::from)?;
330        self.scope
331            .validate_for_task(self.task)
332            .map_err(TaskCompilationError::from)?;
333        self.limits.validate().map_err(TaskCompilationError::from)?;
334        if self.postconditions.is_empty() {
335            return Err(TaskCompilationError::new(
336                "postconditions",
337                "compiled execution plans require at least one verification postcondition",
338            ));
339        }
340        if self.postconditions.len() > MAX_POSTCONDITIONS {
341            return Err(TaskCompilationError::new(
342                "postconditions",
343                "postcondition count exceeds the Task Protocol bound",
344            ));
345        }
346        for (index, postcondition) in self.postconditions.iter().enumerate() {
347            if !postcondition_allowed_for(self.task, postcondition.kind) {
348                return Err(TaskCompilationError::new(
349                    format!("postconditions[{index}].kind"),
350                    "postcondition kind is incompatible with the task family",
351                ));
352            }
353            postcondition
354                .validate_at(index)
355                .map_err(TaskCompilationError::from)?;
356            if postcondition.kind == crate::task_protocol::TaskPostconditionKind::RecordsExtracted
357                && let Some(expected) = postcondition.expected.as_deref()
358            {
359                let minimum = expected.parse::<u32>().map_err(|_| {
360                    TaskCompilationError::new(
361                        format!("postconditions[{index}].expected"),
362                        "recordsExtracted expected must be a non-negative integer",
363                    )
364                })?;
365                if minimum > self.limits.max_items {
366                    return Err(TaskCompilationError::new(
367                        format!("postconditions[{index}].expected"),
368                        "recordsExtracted expected exceeds plan maxItems",
369                    ));
370                }
371            }
372        }
373        if self.task == TaskKind::FormSubmit && self.postconditions.is_empty() {
374            return Err(TaskCompilationError::new(
375                "postconditions",
376                "form.submit requires at least one bounded postcondition",
377            ));
378        }
379        if self.steps.is_empty() {
380            return Err(TaskCompilationError::new(
381                "steps",
382                "execution plan must contain at least one step",
383            ));
384        }
385        if self.steps.len() > self.limits.max_actions as usize {
386            return Err(TaskCompilationError::new(
387                "steps",
388                "execution plan exceeds the maxActions bound",
389            ));
390        }
391        let expected_operation = operation_for_task(self.task);
392        let expected_operations = [TaskPlanOperation::ObserveScope, expected_operation];
393        if self.steps.len() != expected_operations.len()
394            || self
395                .steps
396                .iter()
397                .map(|step| step.operation)
398                .ne(expected_operations)
399        {
400            return Err(TaskCompilationError::new(
401                "steps",
402                "execution plan operation sequence does not exactly match the task family",
403            ));
404        }
405        let minimum_risk = minimum_risk_for_task(self.task);
406        if !risk_at_least(self.risk, minimum_risk) {
407            return Err(TaskCompilationError::new(
408                "risk",
409                "declared risk is below the minimum risk required by the task operation",
410            ));
411        }
412        if confirmation_required_for(self.risk, self.ambiguity, self.revision)
413            && !self.confirmation_required
414        {
415            return Err(TaskCompilationError::new(
416                "confirmationRequired",
417                "plan metadata must require confirmation for this task",
418            ));
419        }
420        for (index, step) in self.steps.iter().enumerate() {
421            let expected = u16::try_from(index + 1).map_err(|_| {
422                TaskCompilationError::new("steps", "execution plan has too many steps")
423            })?;
424            if step.ordinal != expected {
425                return Err(TaskCompilationError::new(
426                    format!("steps[{index}].ordinal"),
427                    "step ordinals must be contiguous and one-based",
428                ));
429            }
430            if step.operation == TaskPlanOperation::ObserveScope && step.requires_confirmation {
431                return Err(TaskCompilationError::new(
432                    format!("steps[{index}].requiresConfirmation"),
433                    "scope observation cannot require confirmation",
434                ));
435            }
436            if step.requires_confirmation && !self.confirmation_required {
437                return Err(TaskCompilationError::new(
438                    format!("steps[{index}].requiresConfirmation"),
439                    "a confirmation-gated step requires plan confirmation metadata",
440                ));
441            }
442            if step.operation == TaskPlanOperation::ObserveScope && !step.entity_ids.is_empty() {
443                return Err(TaskCompilationError::new(
444                    format!("steps[{index}].entityIds"),
445                    "scope observation cannot carry resolved entity IDs",
446                ));
447            }
448            if step.operation != TaskPlanOperation::ObserveScope
449                && (step.entity_ids.is_empty()
450                    || step
451                        .entity_ids
452                        .iter()
453                        .any(|entity_id| !selected.contains(entity_id.as_str())))
454            {
455                return Err(TaskCompilationError::new(
456                    format!("steps[{index}].entityIds"),
457                    "task operations require selected source entity IDs",
458                ));
459            }
460            if self.confirmation_required
461                && step.operation != TaskPlanOperation::ObserveScope
462                && !step.requires_confirmation
463            {
464                return Err(TaskCompilationError::new(
465                    format!("steps[{index}].requiresConfirmation"),
466                    "task operations must be confirmation-gated when the plan requires it",
467                ));
468            }
469            if matches!(
470                step.operation,
471                TaskPlanOperation::FillInputs | TaskPlanOperation::SubmitForm
472            ) && step.input_names.is_empty()
473            {
474                return Err(TaskCompilationError::new(
475                    format!("steps[{index}].inputNames"),
476                    "form operations require at least one input name",
477                ));
478            }
479            if !matches!(
480                step.operation,
481                TaskPlanOperation::FillInputs | TaskPlanOperation::SubmitForm
482            ) && !step.input_names.is_empty()
483            {
484                return Err(TaskCompilationError::new(
485                    format!("steps[{index}].inputNames"),
486                    "input names are only valid for form operations",
487                ));
488            }
489            if step.operation == TaskPlanOperation::SubmitForm
490                && step.input_names != ["submit".to_string()]
491            {
492                return Err(TaskCompilationError::new(
493                    format!("steps[{index}].inputNames"),
494                    "submitForm must carry exactly the submit input name",
495                ));
496            }
497            let mut input_names = BTreeSet::new();
498            if step.input_names.len() > MAX_INPUTS {
499                return Err(TaskCompilationError::new(
500                    format!("steps[{index}].inputNames"),
501                    "input name count exceeds the Task Protocol bound",
502                ));
503            }
504            for input_name in &step.input_names {
505                if input_name.is_empty()
506                    || input_name.len() > MAX_INPUT_NAME_BYTES
507                    || input_name.chars().any(char::is_control)
508                    || !input_names.insert(input_name)
509                {
510                    return Err(TaskCompilationError::new(
511                        format!("steps[{index}].inputNames"),
512                        "input names must be unique, bounded, and free of control characters",
513                    ));
514                }
515            }
516        }
517        Ok(())
518    }
519
520    /// Serialize a validated execution plan deterministically.
521    pub fn to_canonical_json(&self) -> Result<String, TaskCompilationError> {
522        self.validate()?;
523        serde_json::to_string(self)
524            .map_err(|error| TaskCompilationError::new("$", error.to_string()))
525    }
526    /// Canonical representation of executable fields only. Advisory memory
527    /// provenance is intentionally removed so enabled and disabled plans can
528    /// be compared without allowing memory to alter execution.
529    pub fn executable_canonical_json(&self) -> Result<String, TaskCompilationError> {
530        let mut executable = self.clone();
531        executable.memory_advisory = None;
532        executable.to_canonical_json()
533    }
534}
535
536/// Compile an authored task without browser access or side effects.
537pub fn compile_task(
538    task: &GlassTask,
539    ir: &GlassWebIrV1,
540) -> Result<TaskExecutionPlan, TaskCompilationError> {
541    compile_task_with_options(task, ir, TaskCompilationOptions::default())
542}
543
544/// Compile a task while optionally consulting bounded historical knowledge.
545/// Historical records can only produce advisory provenance; entity selection,
546/// executable preconditions, and postconditions always come from live IR.
547pub fn compile_task_with_options(
548    task: &GlassTask,
549    ir: &GlassWebIrV1,
550    options: TaskCompilationOptions<'_>,
551) -> Result<TaskExecutionPlan, TaskCompilationError> {
552    task.validate().map_err(TaskCompilationError::from)?;
553    ir.validate()
554        .map_err(|error| TaskCompilationError::new(format!("ir.{}", error.path), error.reason))?;
555    let effective_risk = max_risk(task.risk, minimum_risk_for_task(task.task));
556    let confirmation_required =
557        confirmation_required_for(effective_risk, task.ambiguity, task.revision);
558    let require_complete = effective_risk != TaskRiskClass::ReadOnly;
559    let minimum_quality = EvidenceQuality::Strong;
560    let mut required_sources = if matches!(
561        task.task,
562        TaskKind::DialogInspect | TaskKind::DialogConfirm | TaskKind::DialogCancel
563    ) {
564        vec![EvidenceSource::Dialogs]
565    } else {
566        vec![EvidenceSource::Accessibility]
567    };
568    if matches!(
569        task.task,
570        TaskKind::FormFill | TaskKind::FormValidate | TaskKind::FormSubmit
571    ) {
572        required_sources.push(EvidenceSource::Forms);
573    }
574    required_sources.sort();
575    required_sources.dedup();
576    if require_complete && ir.limits.truncated {
577        return Err(TaskCompilationError::new(
578            "ir.limits.truncated",
579            "mutating tasks require complete bounded source evidence",
580        ));
581    }
582    for source in &required_sources {
583        if ir.limits.missing_sources.contains(source) {
584            return Err(TaskCompilationError::new(
585                "ir.limits.missingSources",
586                format!("required {source:?} evidence is unavailable"),
587            ));
588        }
589    }
590
591    let selected = select_entities(task, ir)?;
592    for entity in &selected {
593        if !quality_satisfies(entity.quality, minimum_quality) {
594            return Err(TaskCompilationError::new(
595                "ir.entities",
596                format!(
597                    "entity {:?} does not satisfy the {:?} evidence floor",
598                    entity.id, minimum_quality
599                ),
600            ));
601        }
602    }
603    let mut entity_evidence_requirements = Vec::with_capacity(selected.len());
604    for entity in &selected {
605        let mut entity_sources = required_sources_for_selected_entity(task.task, entity);
606        entity_sources.sort();
607        entity_sources.dedup();
608        for source in &entity_sources {
609            if !entity.evidence_sources.contains(source) {
610                return Err(TaskCompilationError::new(
611                    format!("ir.entities.{}.evidenceSources", entity.id),
612                    format!("selected entity lacks required {source:?} evidence"),
613                ));
614            }
615        }
616        entity_evidence_requirements.push(TaskEntityEvidenceRequirement {
617            entity_id: entity.id.clone(),
618            minimum_quality,
619            required_sources: entity_sources,
620        });
621    }
622    entity_evidence_requirements.sort_by(|left, right| left.entity_id.cmp(&right.entity_id));
623
624    let mut selected_entity_ids = selected
625        .iter()
626        .map(|entity| entity.id.clone())
627        .collect::<Vec<_>>();
628    selected_entity_ids.sort();
629    selected_entity_ids.dedup();
630    let action = action_for_task(task.task);
631    let mut preconditions = vec![TaskPlanPrecondition::RevisionEquals {
632        revision: ir.revision,
633    }];
634    let mut action_supported = false;
635    for entity_id in &selected_entity_ids {
636        preconditions.push(TaskPlanPrecondition::EntityPresent {
637            entity_id: entity_id.clone(),
638        });
639        let details = ir.entity_details.get(entity_id).ok_or_else(|| {
640            TaskCompilationError::new(
641                format!("ir.entityDetails.{entity_id}"),
642                "selected entity is missing required execution details",
643            )
644        })?;
645        if require_complete {
646            preconditions.push(TaskPlanPrecondition::EntityEnabled {
647                entity_id: entity_id.clone(),
648            });
649        }
650        if let Some(supported_action) = supported_action_for_task(task.task, details) {
651            action_supported = true;
652            preconditions.push(TaskPlanPrecondition::ActionSupported {
653                entity_id: entity_id.clone(),
654                action: supported_action,
655            });
656        }
657    }
658    if !action_supported {
659        return Err(TaskCompilationError::new(
660            "ir.entityDetails.supportedActions",
661            format!("selected entities do not support {action:?}"),
662        ));
663    }
664
665    let input_names = if task.task == TaskKind::FormSubmit {
666        vec!["submit".to_string()]
667    } else {
668        task.inputs.keys().cloned().collect::<Vec<_>>()
669    };
670    let operations = [
671        TaskPlanOperation::ObserveScope,
672        operation_for_task(task.task),
673    ];
674    let steps = operations
675        .into_iter()
676        .enumerate()
677        .map(|(index, operation)| TaskPlanStep {
678            ordinal: u16::try_from(index + 1).expect("fixed operation sequence is bounded"),
679            operation,
680            input_names: if matches!(
681                operation,
682                TaskPlanOperation::FillInputs | TaskPlanOperation::SubmitForm
683            ) {
684                input_names.clone()
685            } else {
686                Vec::new()
687            },
688            entity_ids: if operation == TaskPlanOperation::ObserveScope {
689                Vec::new()
690            } else {
691                selected_entity_ids.clone()
692            },
693            requires_confirmation: confirmation_required
694                && operation != TaskPlanOperation::ObserveScope,
695        })
696        .collect();
697    let memory_advisory = match (options.knowledge_store, options.knowledge_context) {
698        (Some(store), Some(context)) => {
699            // A caller-provided context is only trusted when it describes the
700            // exact Web IR revision being compiled. Otherwise historical
701            // validation could accidentally make an old record look current.
702            if context.current_revision != ir.revision {
703                return Err(TaskCompilationError::new(
704                    "memory.currentRevision",
705                    "knowledge context revision must match the current Web IR revision",
706                ));
707            }
708            let mut query = KnowledgeRetrievalQuery {
709                page_kind: ir.document.kind.clone(),
710                task_kind: Some(format!("{:?}", task.task)),
711                max_results: 8,
712                ..KnowledgeRetrievalQuery::default()
713            };
714            query.entity_roles = selected
715                .iter()
716                .filter_map(|entity| entity.role.clone())
717                .collect();
718            query.landmarks = selected
719                .iter()
720                .map(|entity| format!("{:?}", entity.kind))
721                .collect();
722            let retrieval = store.retrieve(context, &query);
723            Some(TaskMemoryAdvisory {
724                influence: if retrieval.selected_record_ids.is_empty() {
725                    KnowledgeMemoryInfluence::None
726                } else {
727                    KnowledgeMemoryInfluence::RankingOnly
728                },
729                retrieval,
730                // The executable fields above are fully derived from live
731                // Web IR. Retrieval is deliberately performed only after
732                // those fields are fixed and can therefore only rank.
733                executable_plan_unchanged: true,
734            })
735        }
736        _ => None,
737    };
738    let task_fingerprint = task_fingerprint(task, ir, &selected_entity_ids)?;
739    let required_runtime_capabilities = runtime_capabilities_for(task);
740    let mut entity_binding_keys = selected
741        .iter()
742        .map(|entity| TaskEntityBindingKey {
743            entity_id: entity.id.clone(),
744            kind: entity.kind,
745            role: entity.role.clone(),
746            name: entity.name.clone(),
747        })
748        .collect::<Vec<_>>();
749    entity_binding_keys.sort_by(|left, right| left.entity_id.cmp(&right.entity_id));
750    let plan = TaskExecutionPlan {
751        schema_version: TASK_PLAN_SCHEMA_VERSION,
752        task_schema_version: task.schema_version,
753        compiler_version: TASK_COMPILER_VERSION,
754        source_ir_schema_version: ir.schema_version,
755        source_ir_revision: ir.revision,
756        task_fingerprint,
757        task: task.task,
758        scope: task.scope.clone(),
759        limits: task.limits,
760        risk: effective_risk,
761        ambiguity: task.ambiguity,
762        revision: task.revision,
763        confirmation_required,
764        selected_entity_ids,
765        evidence_requirements: TaskEvidenceRequirements {
766            minimum_quality,
767            required_sources,
768            require_complete,
769        },
770        entity_evidence_requirements,
771        entity_binding_keys,
772        required_runtime_capabilities,
773        preconditions,
774        steps,
775        memory_advisory,
776        postconditions: effective_postconditions(task),
777    };
778    plan.validate()?;
779    Ok(plan)
780}
781
782fn required_sources_for_selected_entity(
783    task: TaskKind,
784    entity: &WebIrEntity,
785) -> Vec<EvidenceSource> {
786    if matches!(
787        task,
788        TaskKind::DialogInspect | TaskKind::DialogConfirm | TaskKind::DialogCancel
789    ) {
790        return vec![EvidenceSource::Dialogs];
791    }
792    if matches!(task, TaskKind::FormFill | TaskKind::FormValidate)
793        && entity.kind == WebIrEntityKind::Field
794    {
795        return vec![EvidenceSource::Accessibility, EvidenceSource::Forms];
796    }
797    vec![EvidenceSource::Accessibility]
798}
799
800fn runtime_capabilities_for(task: &GlassTask) -> Vec<TaskRuntimeCapability> {
801    let mut capabilities = vec![TaskRuntimeCapability::Observe];
802    capabilities.push(match task.task {
803        TaskKind::FormInspect
804        | TaskKind::FormValidate
805        | TaskKind::FieldRead
806        | TaskKind::DialogInspect => TaskRuntimeCapability::Read,
807        TaskKind::TableExtract | TaskKind::CollectionExtract | TaskKind::RegionExtract => {
808            TaskRuntimeCapability::Extract
809        }
810        TaskKind::NavigationFollow => TaskRuntimeCapability::Navigate,
811        TaskKind::DialogConfirm | TaskKind::DialogCancel => TaskRuntimeCapability::Dialog,
812        TaskKind::PaginationNext | TaskKind::PaginationCollect => TaskRuntimeCapability::Pagination,
813        TaskKind::FormFill
814        | TaskKind::FormSubmit
815        | TaskKind::NavigationSelectTab
816        | TaskKind::NavigationOpenMenu => TaskRuntimeCapability::Mutate,
817    });
818    if task
819        .postconditions
820        .iter()
821        .any(|postcondition| postcondition.kind == TaskPostconditionKind::EntityState)
822    {
823        capabilities.push(TaskRuntimeCapability::VerifyEntityState);
824    }
825    capabilities.sort();
826    capabilities.dedup();
827    capabilities
828}
829
830/// Convenience entry point for an explicitly enabled knowledge-assisted
831/// compilation.
832pub fn compile_task_with_knowledge(
833    task: &GlassTask,
834    ir: &GlassWebIrV1,
835    knowledge_store: &KnowledgeStore,
836    knowledge_context: &KnowledgeLookupContext,
837) -> Result<TaskExecutionPlan, TaskCompilationError> {
838    compile_task_with_options(
839        task,
840        ir,
841        TaskCompilationOptions {
842            knowledge_store: Some(knowledge_store),
843            knowledge_context: Some(knowledge_context),
844        },
845    )
846}
847
848pub(crate) fn effective_postconditions(task: &GlassTask) -> Vec<TaskPostcondition> {
849    if !task.postconditions.is_empty() {
850        return task.postconditions.clone();
851    }
852    let kind = match task.task {
853        TaskKind::FormValidate => TaskPostconditionKind::ValidationClear,
854        TaskKind::FormSubmit | TaskKind::NavigationFollow | TaskKind::PaginationNext => {
855            TaskPostconditionKind::NavigationOccurred
856        }
857        TaskKind::TableExtract
858        | TaskKind::CollectionExtract
859        | TaskKind::RegionExtract
860        | TaskKind::PaginationCollect => TaskPostconditionKind::RecordsExtracted,
861        TaskKind::DialogConfirm | TaskKind::DialogCancel => TaskPostconditionKind::DialogClosed,
862        TaskKind::FormInspect
863        | TaskKind::FormFill
864        | TaskKind::NavigationSelectTab
865        | TaskKind::NavigationOpenMenu
866        | TaskKind::FieldRead
867        | TaskKind::DialogInspect => TaskPostconditionKind::PageKind,
868    };
869    vec![TaskPostcondition {
870        kind,
871        expected: None,
872    }]
873}
874
875fn select_entities<'a>(
876    task: &GlassTask,
877    ir: &'a GlassWebIrV1,
878) -> Result<Vec<&'a WebIrEntity>, TaskCompilationError> {
879    let selector = task
880        .scope
881        .entity_name
882        .as_deref()
883        .or_else(|| task_selector_name(task));
884    let mut candidates = ir
885        .entities
886        .iter()
887        .filter(|entity| {
888            task.scope.entity_kind.map_or_else(
889                || entity_kind_matches_task(entity, task.task),
890                |kind| entity.kind == kind,
891            )
892        })
893        .collect::<Vec<_>>();
894    if let Some(selector) = selector {
895        candidates.retain(|entity| {
896            entity
897                .name
898                .as_deref()
899                .is_some_and(|name| normalized_name(name) == normalized_name(selector))
900        });
901    }
902    candidates.sort_by_key(|entity| entity.id.as_str());
903    if candidates.is_empty() {
904        return Err(TaskCompilationError::new(
905            "scope",
906            "no compatible entity exists in the source Glass Web IR",
907        ));
908    }
909    if candidates.len() > 1 && task.ambiguity == TaskAmbiguityPolicy::Fail {
910        let mut candidate_ids = candidates
911            .iter()
912            .take(8)
913            .map(|entity| entity.id.as_str())
914            .collect::<Vec<_>>()
915            .join(", ");
916        if candidates.len() > 8 {
917            candidate_ids.push_str(", …");
918        }
919        return Err(TaskCompilationError::new(
920            "scope",
921            format!(
922                "multiple compatible entities exist and ambiguity policy is fail: {candidate_ids}"
923            ),
924        ));
925    }
926    let mut selected = candidates;
927    let selected_scope_ids = selected
928        .iter()
929        .map(|entity| entity.id.as_str())
930        .collect::<BTreeSet<_>>();
931    let scoped_entity_ids = matches!(task.task, TaskKind::FormFill | TaskKind::FormSubmit)
932        .then(|| entities_scoped_to(ir, selected_scope_ids.iter().copied()));
933
934    if task.task == TaskKind::FormFill {
935        let mut scoped_fields_by_name = BTreeMap::<String, Vec<&WebIrEntity>>::new();
936        for entity in ir.entities.iter().filter(|entity| {
937            entity.kind == WebIrEntityKind::Field
938                && scoped_entity_ids
939                    .as_ref()
940                    .is_some_and(|ids| ids.contains(entity.id.as_str()))
941        }) {
942            if let Some(name) = entity.name.as_deref() {
943                scoped_fields_by_name
944                    .entry(normalized_name(name))
945                    .or_default()
946                    .push(entity);
947            }
948        }
949        for input_name in task.inputs.keys() {
950            let normalized_input_name = normalized_name(input_name);
951            let fields = scoped_fields_by_name
952                .get(&normalized_input_name)
953                .map(Vec::as_slice)
954                .unwrap_or_default();
955            if fields.len() != 1 {
956                let candidates = ir
957                    .entities
958                    .iter()
959                    .filter(|entity| {
960                        entity.kind == WebIrEntityKind::Field
961                            && entity.name.as_deref().is_some_and(|name| {
962                                normalized_name(name) == normalized_name(input_name)
963                            })
964                    })
965                    .take(8)
966                    .map(|entity| {
967                        let parents = ir
968                            .relationships
969                            .iter()
970                            .filter(|relationship| relationship.to == entity.id)
971                            .map(|relationship| relationship.from.as_str())
972                            .take(4)
973                            .collect::<Vec<_>>()
974                            .join("|");
975                        format!("{}<-{}", entity.id, parents)
976                    })
977                    .collect::<Vec<_>>()
978                    .join(",");
979                return Err(TaskCompilationError::new(
980                    format!("inputs.{input_name}"),
981                    format!(
982                        "form input must resolve to exactly one source Web IR field (found {}; scope {}; candidates {})",
983                        fields.len(),
984                        selected_scope_ids
985                            .iter()
986                            .copied()
987                            .collect::<Vec<_>>()
988                            .join("|"),
989                        candidates
990                    ),
991                ));
992            }
993            selected.push(fields[0]);
994        }
995    }
996    if task.task == TaskKind::FormSubmit {
997        let submit_name = &task.inputs["submit"];
998        let submitters =
999            ir.entities
1000                .iter()
1001                .filter(|entity| {
1002                    matches!(
1003                        entity.kind,
1004                        WebIrEntityKind::Action | WebIrEntityKind::UnknownInteractive
1005                    ) && scoped_entity_ids
1006                        .as_ref()
1007                        .is_some_and(|ids| ids.contains(entity.id.as_str()))
1008                        && entity.name.as_deref().is_some_and(|name| {
1009                            normalized_name(name) == normalized_name(submit_name)
1010                        })
1011                })
1012                .collect::<Vec<_>>();
1013        if submitters.len() != 1 {
1014            return Err(TaskCompilationError::new(
1015                "inputs.submit",
1016                "submit target must resolve to exactly one source Web IR action",
1017            ));
1018        }
1019        selected.push(submitters[0]);
1020    }
1021    selected.sort_by_key(|entity| entity.id.as_str());
1022    selected.dedup_by_key(|entity| entity.id.as_str());
1023    Ok(selected)
1024}
1025
1026fn entities_scoped_to<'a>(
1027    ir: &'a GlassWebIrV1,
1028    scope_ids: impl IntoIterator<Item = &'a str>,
1029) -> BTreeSet<&'a str> {
1030    let mut adjacency = BTreeMap::<&str, Vec<&str>>::new();
1031    for relationship in &ir.relationships {
1032        if !matches!(
1033            relationship.kind,
1034            WebIrRelationshipKind::Contains
1035                | WebIrRelationshipKind::Owns
1036                | WebIrRelationshipKind::Submits
1037                | WebIrRelationshipKind::ScopedTo
1038        ) {
1039            continue;
1040        }
1041        adjacency
1042            .entry(relationship.from.as_str())
1043            .or_default()
1044            .push(relationship.to.as_str());
1045        if relationship.kind == WebIrRelationshipKind::ScopedTo {
1046            adjacency
1047                .entry(relationship.to.as_str())
1048                .or_default()
1049                .push(relationship.from.as_str());
1050        }
1051    }
1052    let mut frontier = scope_ids.into_iter().collect::<Vec<_>>();
1053    let mut visited = BTreeSet::new();
1054    while let Some(parent) = frontier.pop() {
1055        if !visited.insert(parent) {
1056            continue;
1057        }
1058        if let Some(children) = adjacency.get(parent) {
1059            frontier.extend(children.iter().copied());
1060        }
1061    }
1062    visited
1063}
1064
1065fn entity_kind_matches_task(entity: &WebIrEntity, task: TaskKind) -> bool {
1066    match task {
1067        TaskKind::FormInspect
1068        | TaskKind::FormFill
1069        | TaskKind::FormValidate
1070        | TaskKind::FormSubmit => entity.kind == WebIrEntityKind::Form,
1071        TaskKind::NavigationFollow => entity.kind == WebIrEntityKind::Page,
1072        TaskKind::NavigationSelectTab => {
1073            entity.kind == WebIrEntityKind::Tab || entity.role.as_deref() == Some("tab")
1074        }
1075        TaskKind::NavigationOpenMenu => matches!(
1076            entity.kind,
1077            WebIrEntityKind::NavigationItem
1078                | WebIrEntityKind::Action
1079                | WebIrEntityKind::UnknownInteractive
1080        ),
1081        TaskKind::TableExtract => entity.kind == WebIrEntityKind::Table,
1082        TaskKind::CollectionExtract => entity.kind == WebIrEntityKind::Collection,
1083        TaskKind::RegionExtract => matches!(
1084            entity.kind,
1085            WebIrEntityKind::Region
1086                | WebIrEntityKind::Form
1087                | WebIrEntityKind::Table
1088                | WebIrEntityKind::Collection
1089                | WebIrEntityKind::Dialog
1090        ),
1091        TaskKind::FieldRead => entity.kind == WebIrEntityKind::Field,
1092        TaskKind::DialogInspect | TaskKind::DialogConfirm | TaskKind::DialogCancel => {
1093            entity.kind == WebIrEntityKind::Dialog
1094        }
1095        TaskKind::PaginationNext | TaskKind::PaginationCollect => {
1096            matches!(
1097                entity.kind,
1098                WebIrEntityKind::PaginationControl
1099                    | WebIrEntityKind::Action
1100                    | WebIrEntityKind::NavigationItem
1101                    | WebIrEntityKind::UnknownInteractive
1102            )
1103        }
1104    }
1105}
1106
1107fn task_selector_name(task: &GlassTask) -> Option<&str> {
1108    match task.task {
1109        TaskKind::NavigationSelectTab => task.inputs.get("tab").map(String::as_str),
1110        TaskKind::NavigationOpenMenu => task.inputs.get("menu").map(String::as_str),
1111        TaskKind::FieldRead => task.inputs.get("field").map(String::as_str),
1112        TaskKind::PaginationNext | TaskKind::PaginationCollect => {
1113            task.inputs.get("next").map(String::as_str)
1114        }
1115        TaskKind::DialogInspect | TaskKind::DialogConfirm | TaskKind::DialogCancel => None,
1116        TaskKind::NavigationFollow => None,
1117        _ => task.scope.region_name.as_deref(),
1118    }
1119}
1120
1121fn normalized_name(value: &str) -> String {
1122    value
1123        .chars()
1124        .filter(|character| character.is_alphanumeric())
1125        .flat_map(char::to_lowercase)
1126        .collect()
1127}
1128
1129fn quality_satisfies(actual: EvidenceQuality, minimum: EvidenceQuality) -> bool {
1130    fn rank(quality: EvidenceQuality) -> u8 {
1131        match quality {
1132            EvidenceQuality::Opaque => 0,
1133            EvidenceQuality::Conflicted => 1,
1134            EvidenceQuality::Inferred => 2,
1135            EvidenceQuality::Partial => 3,
1136            EvidenceQuality::Strong => 4,
1137            EvidenceQuality::Confirmed => 5,
1138        }
1139    }
1140    rank(actual) >= rank(minimum)
1141}
1142
1143fn action_for_task(task: TaskKind) -> WebIrAction {
1144    match task {
1145        TaskKind::FormInspect | TaskKind::FormValidate | TaskKind::FieldRead => WebIrAction::Read,
1146        TaskKind::FormFill => WebIrAction::Type,
1147        TaskKind::FormSubmit => WebIrAction::Submit,
1148        TaskKind::NavigationFollow => WebIrAction::Navigate,
1149        TaskKind::NavigationSelectTab => WebIrAction::Select,
1150        TaskKind::NavigationOpenMenu => WebIrAction::Click,
1151        TaskKind::TableExtract
1152        | TaskKind::CollectionExtract
1153        | TaskKind::RegionExtract
1154        | TaskKind::PaginationCollect => WebIrAction::Extract,
1155        TaskKind::DialogInspect => WebIrAction::Read,
1156        TaskKind::DialogConfirm => WebIrAction::Confirm,
1157        TaskKind::DialogCancel => WebIrAction::Cancel,
1158        TaskKind::PaginationNext => WebIrAction::Paginate,
1159    }
1160}
1161
1162fn supported_action_for_task(task: TaskKind, details: &WebIrEntityDetails) -> Option<WebIrAction> {
1163    let preferred = action_for_task(task);
1164    if details.supported_actions.contains(&preferred) {
1165        return Some(preferred);
1166    }
1167    (task == TaskKind::PaginationNext && details.supported_actions.contains(&WebIrAction::Click))
1168        .then_some(WebIrAction::Click)
1169}
1170
1171fn task_fingerprint(
1172    task: &GlassTask,
1173    ir: &GlassWebIrV1,
1174    selected_entity_ids: &[String],
1175) -> Result<String, TaskCompilationError> {
1176    let input_names = task.inputs.keys().collect::<Vec<_>>();
1177    let material = serde_json::to_vec(&serde_json::json!({
1178        "compilerVersion": TASK_COMPILER_VERSION,
1179        "taskSchemaVersion": task.schema_version,
1180        "task": task.task,
1181        "scope": task.scope,
1182        "inputNames": input_names,
1183        "limits": task.limits,
1184        "risk": task.risk,
1185        "ambiguity": task.ambiguity,
1186        "revision": task.revision,
1187        "postconditions": task.postconditions,
1188        "sourceIrSchemaVersion": ir.schema_version,
1189        "sourceIrRevision": ir.revision,
1190        "selectedEntityIds": selected_entity_ids,
1191    }))
1192    .map_err(|error| TaskCompilationError::new("taskFingerprint", error.to_string()))?;
1193    Ok(format!("{:x}", Sha256::digest(material)))
1194}
1195
1196fn operation_for_task(task: TaskKind) -> TaskPlanOperation {
1197    match task {
1198        TaskKind::FormInspect => TaskPlanOperation::InspectForm,
1199        TaskKind::FormFill => TaskPlanOperation::FillInputs,
1200        TaskKind::FormValidate => TaskPlanOperation::ValidateForm,
1201        TaskKind::FormSubmit => TaskPlanOperation::SubmitForm,
1202        TaskKind::NavigationFollow => TaskPlanOperation::FollowNavigation,
1203        TaskKind::NavigationSelectTab => TaskPlanOperation::SelectTab,
1204        TaskKind::NavigationOpenMenu => TaskPlanOperation::OpenMenu,
1205        TaskKind::TableExtract => TaskPlanOperation::ExtractTable,
1206        TaskKind::CollectionExtract => TaskPlanOperation::ExtractCollection,
1207        TaskKind::RegionExtract => TaskPlanOperation::ExtractRegion,
1208        TaskKind::FieldRead => TaskPlanOperation::ReadField,
1209        TaskKind::DialogInspect => TaskPlanOperation::InspectDialog,
1210        TaskKind::DialogConfirm => TaskPlanOperation::ConfirmDialog,
1211        TaskKind::DialogCancel => TaskPlanOperation::CancelDialog,
1212        TaskKind::PaginationNext => TaskPlanOperation::NextPage,
1213        TaskKind::PaginationCollect => TaskPlanOperation::CollectPages,
1214    }
1215}
1216fn minimum_risk_for_task(task: TaskKind) -> TaskRiskClass {
1217    match task {
1218        TaskKind::FormFill => TaskRiskClass::LocalMutation,
1219        TaskKind::FormSubmit => TaskRiskClass::RemoteIrreversible,
1220        TaskKind::DialogConfirm | TaskKind::DialogCancel => TaskRiskClass::RemoteReversible,
1221        TaskKind::NavigationFollow
1222        | TaskKind::NavigationSelectTab
1223        | TaskKind::NavigationOpenMenu
1224        | TaskKind::PaginationNext
1225        | TaskKind::PaginationCollect => TaskRiskClass::LocalMutation,
1226        TaskKind::FormInspect
1227        | TaskKind::FormValidate
1228        | TaskKind::TableExtract
1229        | TaskKind::CollectionExtract
1230        | TaskKind::RegionExtract
1231        | TaskKind::FieldRead
1232        | TaskKind::DialogInspect => TaskRiskClass::ReadOnly,
1233    }
1234}
1235
1236fn risk_rank(risk: TaskRiskClass) -> u8 {
1237    match risk {
1238        TaskRiskClass::ReadOnly => 0,
1239        TaskRiskClass::LocalMutation => 1,
1240        TaskRiskClass::RemoteReversible => 2,
1241        TaskRiskClass::RemoteIrreversible => 3,
1242        TaskRiskClass::Authentication => 4,
1243        TaskRiskClass::DataDisclosure => 5,
1244        TaskRiskClass::UnknownRisk => 6,
1245    }
1246}
1247
1248fn risk_at_least(actual: TaskRiskClass, minimum: TaskRiskClass) -> bool {
1249    actual == TaskRiskClass::UnknownRisk || risk_rank(actual) >= risk_rank(minimum)
1250}
1251
1252fn max_risk(left: TaskRiskClass, right: TaskRiskClass) -> TaskRiskClass {
1253    if risk_rank(left) >= risk_rank(right) {
1254        left
1255    } else {
1256        right
1257    }
1258}
1259
1260fn confirmation_required_for(
1261    risk: TaskRiskClass,
1262    ambiguity: TaskAmbiguityPolicy,
1263    revision: TaskRevisionPolicy,
1264) -> bool {
1265    matches!(
1266        risk,
1267        TaskRiskClass::RemoteIrreversible
1268            | TaskRiskClass::Authentication
1269            | TaskRiskClass::DataDisclosure
1270            | TaskRiskClass::UnknownRisk
1271    ) || matches!(ambiguity, TaskAmbiguityPolicy::RequireConfirmation)
1272        || (revision == TaskRevisionPolicy::Reextract && risk != TaskRiskClass::ReadOnly)
1273}
1274
1275/// Path-aware compiler or plan validation failure.
1276#[derive(Debug, Clone, PartialEq, Eq)]
1277pub struct TaskCompilationError {
1278    pub path: String,
1279    pub reason: String,
1280}
1281
1282impl TaskCompilationError {
1283    fn new(path: impl Into<String>, reason: impl Into<String>) -> Self {
1284        Self {
1285            path: path.into(),
1286            reason: reason.into(),
1287        }
1288    }
1289}
1290
1291impl From<TaskProtocolError> for TaskCompilationError {
1292    fn from(error: TaskProtocolError) -> Self {
1293        Self {
1294            path: error.path,
1295            reason: error.reason,
1296        }
1297    }
1298}
1299
1300impl Display for TaskCompilationError {
1301    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
1302        write!(formatter, "{}: {}", self.path, self.reason)
1303    }
1304}
1305
1306impl Error for TaskCompilationError {}
1307
1308#[cfg(test)]
1309pub(crate) fn test_compiler_ir() -> GlassWebIrV1 {
1310    use crate::extraction::{
1311        EvidenceCoverage, EvidenceFact, ExtractionEvidence, ExtractionEvidenceLimits,
1312        ExtractionScope,
1313    };
1314    let facts = [
1315        (EvidenceSource::Accessibility, "form", "Checkout"),
1316        (EvidenceSource::Accessibility, "textbox", "Email"),
1317        (EvidenceSource::Forms, "textbox", "Email"),
1318        (EvidenceSource::Accessibility, "button", "Submit"),
1319        (EvidenceSource::Forms, "button", "Submit"),
1320        (EvidenceSource::Accessibility, "tab", "Payment"),
1321        (EvidenceSource::Accessibility, "menuitem", "Products"),
1322        (EvidenceSource::Accessibility, "table", "Checkout"),
1323        (EvidenceSource::Accessibility, "list", "Checkout"),
1324        (EvidenceSource::Accessibility, "main", "Checkout"),
1325        (EvidenceSource::Dialogs, "dialog", "Checkout"),
1326        (EvidenceSource::Accessibility, "link", "Next"),
1327        (EvidenceSource::Accessibility, "button", "Next"),
1328    ]
1329    .into_iter()
1330    .map(|(source, role, name)| EvidenceFact {
1331        source,
1332        kind: if source == EvidenceSource::Forms {
1333            "control"
1334        } else {
1335            "node"
1336        }
1337        .into(),
1338        quality: if source == EvidenceSource::Forms {
1339            EvidenceQuality::Strong
1340        } else {
1341            EvidenceQuality::Confirmed
1342        },
1343        role: Some(role.into()),
1344        name: Some(name.into()),
1345        input_type: (role == "textbox").then(|| "email".into()),
1346        autocomplete: (role == "textbox").then(|| "email".into()),
1347        required: (role == "textbox").then_some(true),
1348        read_only: (role == "textbox").then_some(false),
1349        empty: (role == "textbox").then_some(true),
1350        checked: None,
1351        disabled: Some(false),
1352        geometry_present: None,
1353        parent_role: matches!(name, "Email" | "Submit").then(|| "form".into()),
1354        relationship_hint: None,
1355    })
1356    .collect();
1357    crate::web_ir::reconcile_evidence(&ExtractionEvidence {
1358        schema_version: crate::extraction::EXTRACTION_CONTRACT_SCHEMA_VERSION,
1359        revision: 7,
1360        scope: ExtractionScope::Document,
1361        sources: vec![EvidenceSource::Accessibility, EvidenceSource::Forms],
1362        facts,
1363        limits: ExtractionEvidenceLimits {
1364            truncated: false,
1365            omitted_facts: 0,
1366            text_bytes: 256,
1367            missing_sources: Vec::new(),
1368        },
1369        coverage: EvidenceCoverage {
1370            structural: EvidenceQuality::Strong,
1371            semantic: EvidenceQuality::Strong,
1372            interactive_entities_observed: 5,
1373            opaque_regions: 0,
1374            reasons: Vec::new(),
1375        },
1376        surface_set: None,
1377    })
1378    .unwrap()
1379}
1380#[cfg(test)]
1381mod tests {
1382    use super::*;
1383    use crate::task_protocol::{TaskAmbiguityPolicy, TaskLimits, TaskPostconditionKind, TaskScope};
1384    use std::collections::BTreeMap;
1385
1386    fn task(kind: TaskKind, risk: TaskRiskClass) -> GlassTask {
1387        let inputs = match kind {
1388            TaskKind::FormFill => BTreeMap::from([("email".into(), "a@example.test".into())]),
1389            TaskKind::FormSubmit => BTreeMap::from([("submit".into(), "Submit".into())]),
1390            TaskKind::NavigationFollow => {
1391                BTreeMap::from([("url".into(), "https://example.test/next".into())])
1392            }
1393            TaskKind::NavigationSelectTab => BTreeMap::from([("tab".into(), "Payment".into())]),
1394            TaskKind::NavigationOpenMenu => BTreeMap::from([("menu".into(), "Products".into())]),
1395            TaskKind::FieldRead => BTreeMap::from([("field".into(), "Email".into())]),
1396            TaskKind::PaginationNext | TaskKind::PaginationCollect => {
1397                BTreeMap::from([("next".into(), "Next".into())])
1398            }
1399            _ => BTreeMap::new(),
1400        };
1401        let postcondition_kind = match kind {
1402            TaskKind::FormSubmit | TaskKind::NavigationFollow => {
1403                TaskPostconditionKind::NavigationOccurred
1404            }
1405            TaskKind::TableExtract
1406            | TaskKind::CollectionExtract
1407            | TaskKind::RegionExtract
1408            | TaskKind::PaginationNext
1409            | TaskKind::PaginationCollect => TaskPostconditionKind::RecordsExtracted,
1410            TaskKind::NavigationSelectTab | TaskKind::NavigationOpenMenu | TaskKind::FieldRead => {
1411                TaskPostconditionKind::PageKind
1412            }
1413            TaskKind::DialogInspect | TaskKind::DialogConfirm | TaskKind::DialogCancel => {
1414                TaskPostconditionKind::DialogClosed
1415            }
1416            _ => TaskPostconditionKind::ValidationClear,
1417        };
1418        let expected = match postcondition_kind {
1419            TaskPostconditionKind::PageKind => Some("form".into()),
1420            TaskPostconditionKind::RecordsExtracted => Some("0".into()),
1421            _ => None,
1422        };
1423        GlassTask {
1424            schema_version: TASK_PROTOCOL_SCHEMA_VERSION,
1425            task: kind,
1426            scope: TaskScope {
1427                region_name: Some("Checkout".into()),
1428                entity_kind: (kind == TaskKind::RegionExtract).then_some(WebIrEntityKind::Region),
1429                ..TaskScope::default()
1430            },
1431            inputs,
1432            limits: TaskLimits::default(),
1433            risk,
1434            ambiguity: TaskAmbiguityPolicy::Fail,
1435            revision: Default::default(),
1436            postconditions: vec![TaskPostcondition {
1437                kind: postcondition_kind,
1438                expected,
1439            }],
1440        }
1441    }
1442
1443    #[test]
1444    fn compiler_emits_stable_semantic_operations_without_values() {
1445        let plan = compile_task(
1446            &task(TaskKind::FormFill, TaskRiskClass::LocalMutation),
1447            &test_compiler_ir(),
1448        )
1449        .unwrap();
1450        assert_eq!(
1451            plan.steps
1452                .iter()
1453                .map(|step| step.operation)
1454                .collect::<Vec<_>>(),
1455            vec![
1456                TaskPlanOperation::ObserveScope,
1457                TaskPlanOperation::FillInputs
1458            ]
1459        );
1460
1461        assert_eq!(plan.steps[1].input_names, vec!["email"]);
1462        assert!(!plan.to_canonical_json().unwrap().contains("a@example.test"));
1463    }
1464
1465    #[test]
1466    fn submit_requires_submit_input_and_confirmation() {
1467        let plan = compile_task(
1468            &task(TaskKind::FormSubmit, TaskRiskClass::ReadOnly),
1469            &test_compiler_ir(),
1470        )
1471        .unwrap();
1472        assert_eq!(plan.steps[1].input_names, vec!["submit"]);
1473        assert_eq!(plan.risk, TaskRiskClass::RemoteIrreversible);
1474        assert!(plan.confirmation_required);
1475    }
1476
1477    #[test]
1478    fn navigation_compiles_against_the_document_execution_boundary() {
1479        let authored = task(TaskKind::NavigationFollow, TaskRiskClass::ReadOnly);
1480
1481        let plan = compile_task(&authored, &test_compiler_ir()).unwrap();
1482
1483        assert_eq!(plan.selected_entity_ids, ["page"]);
1484        assert!(plan.preconditions.iter().any(|precondition| matches!(
1485            precondition,
1486            TaskPlanPrecondition::ActionSupported {
1487                entity_id,
1488                action: WebIrAction::Navigate,
1489            } if entity_id == "page"
1490        )));
1491    }
1492
1493    #[test]
1494    fn compiler_generates_verification_postconditions_from_task_intent() {
1495        let mut authored = task(TaskKind::RegionExtract, TaskRiskClass::ReadOnly);
1496        authored.postconditions.clear();
1497
1498        let plan = compile_task(&authored, &test_compiler_ir()).unwrap();
1499
1500        assert_eq!(
1501            plan.postconditions,
1502            vec![TaskPostcondition {
1503                kind: TaskPostconditionKind::RecordsExtracted,
1504                expected: None,
1505            }]
1506        );
1507    }
1508
1509    #[test]
1510    fn plan_rejects_extra_operations_and_preserves_revision_policy() {
1511        let mut plan = compile_task(
1512            &task(TaskKind::RegionExtract, TaskRiskClass::ReadOnly),
1513            &test_compiler_ir(),
1514        )
1515        .unwrap();
1516        plan.steps.push(plan.steps[1].clone());
1517        assert_eq!(plan.validate().unwrap_err().path, "steps");
1518        let mut authored = task(TaskKind::RegionExtract, TaskRiskClass::ReadOnly);
1519        authored.revision = TaskRevisionPolicy::Compatible;
1520        let plan = compile_task(&authored, &test_compiler_ir()).unwrap();
1521        assert_eq!(plan.revision, TaskRevisionPolicy::Compatible);
1522    }
1523
1524    #[test]
1525    fn plan_validation_rejects_downgraded_risk() {
1526        let mut plan = compile_task(
1527            &task(TaskKind::FormSubmit, TaskRiskClass::RemoteIrreversible),
1528            &test_compiler_ir(),
1529        )
1530        .unwrap();
1531        plan.risk = TaskRiskClass::ReadOnly;
1532        assert_eq!(plan.validate().unwrap_err().path, "risk");
1533    }
1534    #[test]
1535    fn compilation_is_deterministic_for_identical_authored_tasks() {
1536        let authored = task(TaskKind::FormFill, TaskRiskClass::LocalMutation);
1537        let first = compile_task(&authored, &test_compiler_ir())
1538            .unwrap()
1539            .to_canonical_json()
1540            .unwrap();
1541        let second = compile_task(&authored, &test_compiler_ir())
1542            .unwrap()
1543            .to_canonical_json()
1544            .unwrap();
1545        assert_eq!(first, second);
1546    }
1547
1548    #[test]
1549    fn maximum_form_inputs_compile_deterministically_from_one_scope_walk() {
1550        let mut ir = test_compiler_ir();
1551        let original_field = ir
1552            .entities
1553            .iter()
1554            .find(|entity| entity.kind == WebIrEntityKind::Field)
1555            .unwrap()
1556            .clone();
1557        let original_details = ir.entity_details[&original_field.id].clone();
1558        let ownership = ir
1559            .relationships
1560            .iter()
1561            .find(|relationship| relationship.to == original_field.id)
1562            .unwrap()
1563            .clone();
1564        let mut authored = task(TaskKind::FormFill, TaskRiskClass::LocalMutation);
1565        authored.inputs.clear();
1566
1567        for index in 0..MAX_INPUTS {
1568            let name = format!("Field{index:02}");
1569            authored.inputs.insert(name.clone(), "value".into());
1570            if index == 0 {
1571                let field = ir
1572                    .entities
1573                    .iter_mut()
1574                    .find(|entity| entity.id == original_field.id)
1575                    .unwrap();
1576                field.name = Some(name);
1577                continue;
1578            }
1579            let id = format!("field-{index:02}");
1580            let mut field = original_field.clone();
1581            field.id.clone_from(&id);
1582            field.name = Some(name);
1583            ir.entities.push(field);
1584            ir.entity_details
1585                .insert(id.clone(), original_details.clone());
1586            let mut relationship = ownership.clone();
1587            relationship.to = id;
1588            ir.relationships.push(relationship);
1589        }
1590        ir.validate().unwrap();
1591
1592        let first = compile_task(&authored, &ir).unwrap();
1593        let second = compile_task(&authored, &ir).unwrap();
1594        assert_eq!(first, second);
1595        assert_eq!(first.steps[1].input_names.len(), MAX_INPUTS);
1596        assert_eq!(first.selected_entity_ids.len(), MAX_INPUTS + 1);
1597    }
1598
1599    #[test]
1600    fn compiler_rejects_incompatible_scope_kind() {
1601        let mut authored = task(TaskKind::FormFill, TaskRiskClass::LocalMutation);
1602        authored.scope.entity_kind = Some(crate::web_ir::WebIrEntityKind::Table);
1603        let error = compile_task(&authored, &test_compiler_ir()).unwrap_err();
1604        assert_eq!(error.path, "scope.entityKind");
1605    }
1606
1607    #[test]
1608    fn compiler_declares_entity_state_runtime_capability() {
1609        let mut authored = task(TaskKind::FormFill, TaskRiskClass::LocalMutation);
1610        authored.postconditions = vec![TaskPostcondition {
1611            kind: TaskPostconditionKind::EntityState,
1612            expected: Some("Email.empty=false".into()),
1613        }];
1614        let plan = compile_task(&authored, &test_compiler_ir()).unwrap();
1615        assert!(
1616            plan.required_runtime_capabilities
1617                .contains(&TaskRuntimeCapability::VerifyEntityState)
1618        );
1619    }
1620
1621    #[test]
1622    fn compiler_rejects_unknown_risk_before_plan_emission() {
1623        let error = compile_task(
1624            &task(TaskKind::FormFill, TaskRiskClass::UnknownRisk),
1625            &test_compiler_ir(),
1626        )
1627        .unwrap_err();
1628        assert_eq!(error.path, "risk");
1629    }
1630
1631    #[test]
1632    fn compiler_rejects_selected_entities_without_execution_details() {
1633        let mut ir = test_compiler_ir();
1634        let form_id = ir
1635            .entities
1636            .iter()
1637            .find(|entity| entity.kind == crate::web_ir::WebIrEntityKind::Form)
1638            .unwrap()
1639            .id
1640            .clone();
1641        ir.entity_details.remove(&form_id);
1642
1643        let error =
1644            compile_task(&task(TaskKind::FormInspect, TaskRiskClass::ReadOnly), &ir).unwrap_err();
1645
1646        assert_eq!(error.path, format!("ir.entityDetails.{form_id}"));
1647    }
1648
1649    #[test]
1650    fn compiler_requires_explicit_confirmation_for_ambiguous_entities() {
1651        let mut ir = test_compiler_ir();
1652        let form = ir
1653            .entities
1654            .iter()
1655            .find(|entity| entity.kind == crate::web_ir::WebIrEntityKind::Form)
1656            .unwrap()
1657            .clone();
1658        let mut duplicate = form.clone();
1659        duplicate.id = "entity_form_duplicate".into();
1660        let mut duplicate_details = ir.entity_details[&form.id].clone();
1661        duplicate_details.semantic_stability_key = Some("form|duplicate|checkout".into());
1662        ir.entities.push(duplicate.clone());
1663        ir.entity_details
1664            .insert(duplicate.id.clone(), duplicate_details);
1665        ir.validate().unwrap();
1666
1667        let authored = task(TaskKind::FormInspect, TaskRiskClass::ReadOnly);
1668        let error = compile_task(&authored, &ir).unwrap_err();
1669        assert_eq!(error.path, "scope");
1670
1671        let mut confirmed = authored;
1672        confirmed.ambiguity = TaskAmbiguityPolicy::RequireConfirmation;
1673        let plan = compile_task(&confirmed, &ir).unwrap();
1674        assert!(plan.confirmation_required);
1675        assert_eq!(plan.selected_entity_ids.len(), 2);
1676    }
1677
1678    #[test]
1679    fn compiler_does_not_fall_back_when_named_target_is_absent() {
1680        let mut authored = task(TaskKind::NavigationOpenMenu, TaskRiskClass::LocalMutation);
1681        authored.inputs.insert("menu".into(), "Missing menu".into());
1682
1683        let error = compile_task(&authored, &test_compiler_ir()).unwrap_err();
1684
1685        assert_eq!(error.path, "scope");
1686        assert_eq!(
1687            error.reason,
1688            "no compatible entity exists in the source Glass Web IR"
1689        );
1690    }
1691
1692    #[test]
1693    fn form_compilation_scopes_duplicate_fields_to_the_selected_form() {
1694        let mut ir = test_compiler_ir();
1695        let original_form = ir
1696            .entities
1697            .iter()
1698            .find(|entity| entity.kind == WebIrEntityKind::Form)
1699            .unwrap()
1700            .clone();
1701        let original_field = ir
1702            .entities
1703            .iter()
1704            .find(|entity| entity.kind == WebIrEntityKind::Field)
1705            .unwrap()
1706            .clone();
1707        let mut other_form = original_form.clone();
1708        other_form.id = "other-form".into();
1709        other_form.name = Some("Other".into());
1710        let mut other_field = original_field.clone();
1711        other_field.id = "other-email".into();
1712        ir.entity_details.insert(
1713            other_form.id.clone(),
1714            ir.entity_details[&original_form.id].clone(),
1715        );
1716        ir.entity_details.insert(
1717            other_field.id.clone(),
1718            ir.entity_details[&original_field.id].clone(),
1719        );
1720        ir.entities
1721            .extend([other_form.clone(), other_field.clone()]);
1722        ir.relationships.push(crate::web_ir::WebIrRelationship {
1723            from: other_form.id,
1724            to: other_field.id,
1725            kind: WebIrRelationshipKind::Owns,
1726        });
1727        ir.entities.sort_by(|left, right| left.id.cmp(&right.id));
1728        ir.relationships.sort_by_key(|relationship| {
1729            (
1730                relationship.from.clone(),
1731                relationship.to.clone(),
1732                relationship.kind,
1733            )
1734        });
1735        ir.validate().unwrap();
1736        let mut authored = task(TaskKind::FormFill, TaskRiskClass::LocalMutation);
1737        authored.scope.entity_name = Some("Checkout".into());
1738        authored.scope.entity_kind = Some(WebIrEntityKind::Form);
1739
1740        let plan = compile_task(&authored, &ir).unwrap();
1741
1742        assert!(plan.selected_entity_ids.contains(&original_field.id));
1743        assert!(
1744            !plan
1745                .selected_entity_ids
1746                .contains(&"other-email".to_string())
1747        );
1748    }
1749
1750    #[test]
1751    fn unrelated_form_evidence_cannot_satisfy_the_selected_field() {
1752        let mut ir = test_compiler_ir();
1753        let field = ir
1754            .entities
1755            .iter_mut()
1756            .find(|entity| entity.kind == WebIrEntityKind::Field)
1757            .unwrap();
1758        field
1759            .evidence_sources
1760            .retain(|source| *source != EvidenceSource::Forms);
1761        let error =
1762            compile_task(&task(TaskKind::FormFill, TaskRiskClass::LocalMutation), &ir).unwrap_err();
1763        assert!(error.path.ends_with("evidenceSources"));
1764        assert!(error.reason.contains("Forms"));
1765    }
1766
1767    #[test]
1768    fn pagination_next_accepts_a_named_clickable_control() {
1769        let mut ir = test_compiler_ir();
1770        let control = ir
1771            .entities
1772            .iter_mut()
1773            .find(|entity| {
1774                entity.role.as_deref() == Some("button") && entity.name.as_deref() == Some("Next")
1775            })
1776            .unwrap();
1777        control.kind = WebIrEntityKind::Action;
1778        control.name = Some("No-op next".into());
1779        let details = ir.entity_details.get_mut(&control.id).unwrap();
1780        details.supported_actions = vec![WebIrAction::Click];
1781        details.semantic_stability_key = Some("action|button|no-op next".into());
1782        ir.validate().unwrap();
1783        let mut authored = task(TaskKind::PaginationNext, TaskRiskClass::LocalMutation);
1784        authored.inputs.insert("next".into(), "No-op next".into());
1785
1786        let plan = compile_task(&authored, &ir).unwrap();
1787
1788        assert!(plan.preconditions.iter().any(|precondition| matches!(
1789            precondition,
1790            TaskPlanPrecondition::ActionSupported {
1791                action: WebIrAction::Click,
1792                ..
1793            }
1794        )));
1795    }
1796
1797    #[test]
1798    fn plan_rejects_records_postcondition_beyond_item_limit() {
1799        let mut plan = compile_task(
1800            &task(TaskKind::RegionExtract, TaskRiskClass::ReadOnly),
1801            &test_compiler_ir(),
1802        )
1803        .unwrap();
1804        plan.limits.max_items = 1;
1805        plan.postconditions[0].expected = Some("2".into());
1806        assert_eq!(
1807            plan.validate().unwrap_err().path,
1808            "postconditions[0].expected"
1809        );
1810    }
1811
1812    #[test]
1813    fn memory_bypass_preserves_the_executable_plan_byte_for_byte() {
1814        let authored = task(TaskKind::FormFill, TaskRiskClass::LocalMutation);
1815        let ir = test_compiler_ir();
1816        let baseline = compile_task(&authored, &ir).unwrap();
1817        let bypassed = compile_task_with_options(
1818            &authored,
1819            &ir,
1820            TaskCompilationOptions {
1821                knowledge_store: None,
1822                knowledge_context: None,
1823            },
1824        )
1825        .unwrap();
1826
1827        assert_eq!(baseline.steps, bypassed.steps);
1828        assert_eq!(baseline.preconditions, bypassed.preconditions);
1829        assert_eq!(baseline.selected_entity_ids, bypassed.selected_entity_ids);
1830        assert_eq!(
1831            baseline.to_canonical_json().unwrap(),
1832            bypassed.to_canonical_json().unwrap()
1833        );
1834        assert!(bypassed.memory_advisory.is_none());
1835    }
1836}