aga 2.0.0

AgenticGraphicsAcceleration — standalone agentic-first GPU rendering backend; wgpu replacement with Vulkan, OpenGL, and complete ontology
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! Ontology registry, UI tree, and node types.
//!
//! The [`OntologyRegistry`] catalogs widget schemas, while [`UiTree`] and
//! [`UiNode`] represent the live widget tree that agents can inspect.

use super::{AgentCapability, Discoverable, SemanticRole, WidgetSchema};
use crate::core::Rect;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Global registry of widget types and the live UI tree.
///
/// 1. **Type catalog**: Agents can list all available widget types, search by
///    name/role/tag, and read schemas before interacting.
/// 2. **UI tree**: The current widget hierarchy exposed as a navigable tree.
#[derive(Debug, Default)]
pub struct OntologyRegistry {
    schemas: HashMap<String, WidgetSchema>,
    tree: Option<UiTree>,
}

impl OntologyRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    // ── Type Catalog ─────────────────────────────────────────────────

    /// Register a widget type's schema.
    pub fn register_schema(&mut self, schema: WidgetSchema) {
        self.schemas.insert(schema.name.clone(), schema);
    }

    /// Register a discoverable widget type (convenience).
    pub fn register<W: Discoverable>(&mut self, instance: &W) {
        self.register_schema(instance.schema());
    }

    /// List all registered widget type names.
    pub fn list_types(&self) -> Vec<&str> {
        self.schemas.keys().map(|s| s.as_str()).collect()
    }

    /// Get the schema for a widget type by name.
    pub fn get_schema(&self, name: &str) -> Option<&WidgetSchema> {
        self.schemas.get(name)
    }

    /// Find widget types matching a semantic role.
    pub fn find_by_role(&self, role: SemanticRole) -> Vec<&WidgetSchema> {
        self.schemas
            .values()
            .filter(|s| s.default_role == role)
            .collect()
    }

    /// Search widget types by tag (case-insensitive substring match).
    pub fn search(&self, query: &str) -> Vec<&WidgetSchema> {
        let query_lower = query.to_lowercase();
        self.schemas
            .values()
            .filter(|s| {
                s.name.to_lowercase().contains(&query_lower)
                    || s.description.to_lowercase().contains(&query_lower)
                    || s.tags
                        .iter()
                        .any(|t| t.to_lowercase().contains(&query_lower))
            })
            .collect()
    }

    /// Export the full type catalog as JSON.
    pub fn export_catalog(&self) -> serde_json::Value {
        serde_json::to_value(&self.schemas).unwrap_or_default()
    }

    /// Validate params against a declared action schema.
    pub fn validate_action_params(
        &self,
        widget_type: &str,
        action: &str,
        params: &serde_json::Value,
    ) -> Result<(), String> {
        let Some(schema) = self.schemas.get(widget_type) else {
            return Ok(());
        };
        let Some(declared) = schema.actions.iter().find(|a| a.name == action) else {
            return Ok(());
        };
        declared.validate_params(params)
    }

    // ── Live UI Tree ─────────────────────────────────────────────────

    /// Set the current UI tree snapshot.
    pub fn set_tree(&mut self, tree: UiTree) {
        self.tree = Some(tree);
    }

    /// Get the current UI tree.
    pub fn tree(&self) -> Option<&UiTree> {
        self.tree.as_ref()
    }

    /// Find a node in the UI tree by its agent ID.
    pub fn find_node(&self, agent_id: &str) -> Option<&UiNode> {
        self.tree.as_ref().and_then(|t| t.find(agent_id))
    }

    /// Export the UI tree as JSON for agent consumption.
    pub fn export_tree(&self) -> serde_json::Value {
        match &self.tree {
            Some(tree) => serde_json::to_value(tree).unwrap_or_default(),
            None => serde_json::Value::Null,
        }
    }
}

/// A snapshot of the live UI widget tree.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiTree {
    pub root: UiNode,
}

impl UiTree {
    pub fn new(root: UiNode) -> Self {
        Self { root }
    }

    /// Depth-first search for a node by agent_id.
    pub fn find(&self, agent_id: &str) -> Option<&UiNode> {
        self.root.find(agent_id)
    }

    /// Collect all nodes matching a role.
    pub fn find_by_role(&self, role: SemanticRole) -> Vec<&UiNode> {
        let mut results = Vec::new();
        self.root.collect_by_role(role, &mut results);
        results
    }

    /// Collect all focusable nodes.
    pub fn focusable_nodes(&self) -> Vec<&UiNode> {
        let mut results = Vec::new();
        self.root.collect_by_capability("focusable", &mut results);
        results
    }
}

/// A node in the UI tree representing a single widget instance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiNode {
    /// Optional unique agent-addressable ID.
    pub agent_id: Option<String>,
    /// The widget type name (matches a registered schema).
    pub widget_type: String,
    /// Semantic role of this instance.
    pub role: SemanticRole,
    /// Capabilities of this instance.
    pub capabilities: Vec<AgentCapability>,
    /// Current state snapshot as JSON.
    pub state: serde_json::Value,
    /// Accessibility label.
    pub label: Option<String>,
    /// Bounding rectangle in logical pixel coordinates.
    pub bounds: Option<NodeBounds>,
    /// Accessibility attributes for screen readers and assistive agents.
    #[serde(default, skip_serializing_if = "Accessibility::is_empty")]
    pub accessibility: Accessibility,
    /// Child nodes.
    pub children: Vec<UiNode>,
}

/// Bounding rectangle of a UI node in logical pixel coordinates.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct NodeBounds {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl From<Rect> for NodeBounds {
    fn from(r: Rect) -> Self {
        Self {
            x: r.x,
            y: r.y,
            width: r.width,
            height: r.height,
        }
    }
}

/// Accessibility attributes following ARIA conventions.
///
/// Agents and screen readers use these to understand widget semantics.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Accessibility {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value_text: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expanded: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selected: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub required: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shortcut: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tab_index: Option<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub live: Option<String>,
}

impl Accessibility {
    pub fn is_empty(&self) -> bool {
        self.role.is_none()
            && self.description.is_none()
            && self.disabled.is_none()
            && self.value_text.is_none()
            && self.expanded.is_none()
            && self.selected.is_none()
            && self.required.is_none()
            && self.shortcut.is_none()
            && self.tab_index.is_none()
            && self.live.is_none()
    }
}

impl UiNode {
    #[must_use]
    pub fn new(widget_type: impl Into<String>, role: SemanticRole) -> Self {
        Self {
            agent_id: None,
            widget_type: widget_type.into(),
            role,
            capabilities: Vec::new(),
            state: serde_json::Value::Null,
            label: None,
            bounds: None,
            accessibility: Accessibility::default(),
            children: Vec::new(),
        }
    }

    #[must_use]
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.agent_id = Some(id.into());
        self
    }

    #[must_use]
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    #[must_use]
    pub fn with_bounds(mut self, bounds: NodeBounds) -> Self {
        self.bounds = Some(bounds);
        self
    }

    #[must_use]
    pub fn with_state(mut self, state: serde_json::Value) -> Self {
        self.state = state;
        self
    }

    #[must_use]
    pub fn with_capability(mut self, cap: AgentCapability) -> Self {
        self.capabilities.push(cap);
        self
    }

    #[must_use]
    pub fn with_child(mut self, child: UiNode) -> Self {
        self.children.push(child);
        self
    }

    /// Set accessibility attributes.
    #[must_use]
    pub fn with_accessibility(mut self, acc: Accessibility) -> Self {
        self.accessibility = acc;
        self
    }

    /// Convenience: set a named property in the state JSON object.
    #[must_use]
    pub fn with_property(mut self, key: &str, value: serde_json::Value) -> Self {
        if self.state.is_null() {
            self.state = serde_json::json!({});
        }
        if let Some(obj) = self.state.as_object_mut() {
            obj.insert(key.to_string(), value);
        }
        self
    }

    /// Depth-first search by agent_id.
    pub fn find(&self, agent_id: &str) -> Option<&UiNode> {
        if self.agent_id.as_deref() == Some(agent_id) {
            return Some(self);
        }
        for child in &self.children {
            if let Some(node) = child.find(agent_id) {
                return Some(node);
            }
        }
        None
    }

    /// Collect nodes matching a semantic role.
    pub fn collect_by_role<'a>(&'a self, role: SemanticRole, results: &mut Vec<&'a UiNode>) {
        if self.role == role {
            results.push(self);
        }
        for child in &self.children {
            child.collect_by_role(role, results);
        }
    }

    /// Collect nodes with a specific capability.
    pub fn collect_by_capability<'a>(&'a self, cap_name: &str, results: &mut Vec<&'a UiNode>) {
        if self.capabilities.iter().any(|c| c.name() == cap_name) {
            results.push(self);
        }
        for child in &self.children {
            child.collect_by_capability(cap_name, results);
        }
    }
}

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

    #[test]
    fn registry_search() {
        let mut reg = OntologyRegistry::new();
        reg.register_schema(WidgetSchema {
            name: "Button".into(),
            description: "A clickable button".into(),
            default_role: SemanticRole::Action,
            properties: vec![],
            actions: vec![],
            usage_hint: None,
            tags: vec!["button".into(), "action".into()],
        });
        assert_eq!(reg.search("button").len(), 1);
        assert_eq!(reg.search("nonexistent").len(), 0);
    }

    #[test]
    fn ui_tree_find() {
        let tree = UiTree::new(
            UiNode::new("Panel", SemanticRole::Container)
                .with_id("root")
                .with_child(
                    UiNode::new("Button", SemanticRole::Action)
                        .with_id("btn-1")
                        .with_capability(AgentCapability::Focusable),
                ),
        );
        assert!(tree.find("btn-1").is_some());
        assert!(tree.find("missing").is_none());
        assert_eq!(tree.focusable_nodes().len(), 1);
    }

    #[test]
    fn registry_list_types() {
        let mut reg = OntologyRegistry::new();
        reg.register_schema(WidgetSchema::new("Button", "btn", SemanticRole::Action));
        reg.register_schema(WidgetSchema::new("Label", "lbl", SemanticRole::Display));
        let types = reg.list_types();
        assert_eq!(types.len(), 2);
        assert!(types.contains(&"Button"));
        assert!(types.contains(&"Label"));
    }

    #[test]
    fn registry_get_schema() {
        let mut reg = OntologyRegistry::new();
        reg.register_schema(WidgetSchema::new("Button", "btn", SemanticRole::Action));
        assert!(reg.get_schema("Button").is_some());
        assert!(reg.get_schema("Missing").is_none());
    }

    #[test]
    fn registry_find_by_role() {
        let mut reg = OntologyRegistry::new();
        reg.register_schema(WidgetSchema::new("Button", "btn", SemanticRole::Action));
        reg.register_schema(WidgetSchema::new("Label", "lbl", SemanticRole::Display));
        reg.register_schema(WidgetSchema::new("Link", "link", SemanticRole::Action));
        assert_eq!(reg.find_by_role(SemanticRole::Action).len(), 2);
        assert_eq!(reg.find_by_role(SemanticRole::Display).len(), 1);
        assert_eq!(reg.find_by_role(SemanticRole::Container).len(), 0);
    }

    #[test]
    fn registry_export_catalog() {
        let mut reg = OntologyRegistry::new();
        reg.register_schema(WidgetSchema::new("Button", "btn", SemanticRole::Action));
        let catalog = reg.export_catalog();
        assert!(catalog.is_object());
        assert!(catalog.get("Button").is_some());
    }

    #[test]
    fn registry_validate_action_params_unknown_type() {
        let reg = OntologyRegistry::new();
        // Unknown widget type should pass validation (permissive)
        assert!(
            reg.validate_action_params("Unknown", "click", &serde_json::json!({}))
                .is_ok()
        );
    }

    #[test]
    fn ui_tree_find_by_role() {
        let tree = UiTree::new(
            UiNode::new("Panel", SemanticRole::Container)
                .with_id("root")
                .with_child(UiNode::new("Button", SemanticRole::Action).with_id("b1"))
                .with_child(UiNode::new("Button", SemanticRole::Action).with_id("b2"))
                .with_child(UiNode::new("Label", SemanticRole::Display).with_id("l1")),
        );
        assert_eq!(tree.find_by_role(SemanticRole::Action).len(), 2);
        assert_eq!(tree.find_by_role(SemanticRole::Display).len(), 1);
        assert_eq!(tree.find_by_role(SemanticRole::Container).len(), 1);
    }

    #[test]
    fn ui_node_builder_chain() {
        let node = UiNode::new("TextInput", SemanticRole::Input)
            .with_id("input-1")
            .with_label("Username")
            .with_bounds(NodeBounds {
                x: 10.0,
                y: 20.0,
                width: 200.0,
                height: 30.0,
            })
            .with_state(serde_json::json!({"value": ""}))
            .with_capability(AgentCapability::Focusable)
            .with_capability(AgentCapability::TextInput {
                multiline: false,
                max_length: Some(100),
            });

        assert_eq!(node.agent_id.as_deref(), Some("input-1"));
        assert_eq!(node.label.as_deref(), Some("Username"));
        assert!(node.bounds.is_some());
        assert_eq!(node.capabilities.len(), 2);
    }

    #[test]
    fn ui_node_with_property() {
        let node = UiNode::new("Slider", SemanticRole::Input)
            .with_property("value", serde_json::json!(50))
            .with_property("min", serde_json::json!(0));
        assert_eq!(node.state["value"], 50);
        assert_eq!(node.state["min"], 0);
    }

    #[test]
    fn node_bounds_from_rect() {
        let rect = Rect::new(1.0, 2.0, 3.0, 4.0);
        let nb: NodeBounds = rect.into();
        assert_eq!(nb.x, 1.0);
        assert_eq!(nb.y, 2.0);
        assert_eq!(nb.width, 3.0);
        assert_eq!(nb.height, 4.0);
    }

    #[test]
    fn accessibility_is_empty() {
        let a = Accessibility::default();
        assert!(a.is_empty());

        let a2 = Accessibility {
            role: Some("button".into()),
            ..Default::default()
        };
        assert!(!a2.is_empty());
    }

    #[test]
    fn registry_set_and_get_tree() {
        let mut reg = OntologyRegistry::new();
        assert!(reg.tree().is_none());

        let tree = UiTree::new(UiNode::new("Root", SemanticRole::Container));
        reg.set_tree(tree);
        assert!(reg.tree().is_some());
    }

    #[test]
    fn registry_find_node() {
        let mut reg = OntologyRegistry::new();
        let tree = UiTree::new(
            UiNode::new("Root", SemanticRole::Container)
                .with_id("root")
                .with_child(UiNode::new("Button", SemanticRole::Action).with_id("btn")),
        );
        reg.set_tree(tree);
        assert!(reg.find_node("btn").is_some());
        assert!(reg.find_node("missing").is_none());
    }

    #[test]
    fn registry_export_tree() {
        let mut reg = OntologyRegistry::new();
        assert!(reg.export_tree().is_null());

        let tree = UiTree::new(UiNode::new("Root", SemanticRole::Container).with_id("root"));
        reg.set_tree(tree);
        let exported = reg.export_tree();
        assert!(exported.is_object());
    }
}