Skip to main content

cvkg_core/
lib.rs

1//! # CVKG Agentic Development Guidelines (v1.2)
2//!
3//! All AI agents contributing to this crate MUST follow ALL seven rules:
4//!
5//! ── Karpathy Guidelines (1–4) ────────────────────────────────────────────
6//! 1. THINK FIRST     -- State assumptions. Surface ambiguity. Push back on complexity.
7//! 2. STAY SIMPLE     -- Minimum code. No speculative features. No unasked-for abstractions.
8//! 3. BE SURGICAL     -- Touch only what's required. Own your orphans. Don't improve neighbors.
9//! 4. VERIFY GOALS    -- Turn tasks into checkable criteria. Loop until they pass. Never commit broken.
10//!
11//! ── CVKG Extended Protocols (5–7) ────────────────────────────────────────
12//! 5. TRIPLE-PASS     -- Read the target, its surrounding context, and its full call graph
13//                      at least THREE TIMES before making any edit or revision.
14//! 6. COMMENT ALL     -- Every major pub fn, unsafe block, and non-trivial algorithm in
15//                      every .rs/.ts/.h/.wgsl file MUST have a descriptive doc comment.
16//                      Comments describe WHY and WHAT CONTRACT, not HOW mechanically.
17//! 7. MONITOR LOOPS   -- Check every tool call / command for progress every 30 seconds.
18//                      After 3 consecutive identical failures, stop, write BLOCKED.md,
19//                      and move to unblocked work. Never silently accept a broken state.
20//!
21//! Sources:
22//   Karpathy: https://github.com/multica-ai/andrej-karpathy-skills
23//   CVKG Extended: Section 2 of the CVKG Design Specification
24
25//! The View trait is the fundamental building block of CVKG. Every UI element -- from a plain text label
26//! to a complex navigation controller -- is a View. The trait is intentionally minimal; complexity emerges
27//! through modifier composition.
28//!
29//! # Conformance rules:
30//! 1. `body()` must be pure and side-effect free
31//! 2. Primitive views use `Never` as `Body` and register a `PaintCommand` directly with the scene graph
32//! 3. `View` types must implement `Send` but not necessarily `Sync`, enabling safe multi-threaded layout passes
33
34use serde::{Deserialize, Serialize};
35use std::collections::HashMap;
36use std::str::FromStr;
37
38pub mod error_types;
39pub mod future_views;
40pub mod security;
41
42pub use error_types::CvkgError;
43pub use future_views::{HologramView, ParticleEmitter, StreamingText};
44
45// P1-13: extracted modules
46pub mod asset;
47pub mod dependency;
48pub mod error_boundary;
49pub mod knowledge;
50pub mod renderer;
51pub mod undo;
52pub mod virtual_list;
53pub mod window;
54
55// P1-13: re-exports for backward compatibility
56pub use asset::{AssetKey, AssetState, DesignTokens, TokenValue};
57pub use dependency::{DependencyGraph, FrameBudgetTracker, InputLatencyTracker, SubsystemBudget};
58pub use error_boundary::{ComponentErrorState, ErrorBoundary};
59#[cfg(not(target_arch = "wasm32"))]
60pub use knowledge::fallback_runtime;
61pub use knowledge::{
62    AnnouncementPriority, AppState, KnowledgeFragment, KnowledgeId, LAYOUT_DIRTY, MemoryLayer,
63    SYSTEM_STATE, TemporalEdge, TemporalNode, UiFidelityLevel, begin_render_phase,
64    end_render_phase, get_system_state, is_rendering, load_system_state, set_rendering,
65    snapshot_system_state, update_system_state,
66};
67pub use undo::{UndoGroup, UndoManager};
68pub use window::{Window, WindowCloseAction, WindowConfig, WindowHandle, WindowId, WindowLevel};
69
70pub mod companion;
71pub use companion::*;
72
73pub mod view;
74pub use view::*;
75pub mod aria;
76pub use aria::*;
77
78pub mod keyboard;
79pub use keyboard::*;
80
81pub mod focus;
82pub use focus::*;
83
84// =============================================================================
85// REDUCED MOTION
86// =============================================================================
87
88/// Detects OS-level reduced motion preference via [`AccessibilityPreferences`].
89///
90/// This delegates to `AccessibilityPreferences::detect_from_system()` which
91/// queries the correct OS API on macOS, Linux, and Windows.
92pub mod reduced_motion;
93pub use reduced_motion::*;
94
95/// An object-safe version of the View trait for type erasure.
96pub mod erased_view;
97pub use erased_view::*;
98
99/// SharedElementModifier enables shared-element transitions.
100/// When two views share the same Bifrost Bridge ID, the Sleipnir solver will
101/// interpolate their geometry and effects (blur, glow) during the transition.
102pub mod modifiers;
103pub use modifiers::*;
104pub mod render_base;
105pub use render_base::*;
106
107/// The Renderer trait defines the atomic drawing operations for all CVKG backends.
108/// This trait is object-safe and used by the View::render system.
109/// # Implementation Requirements
110/// 1. Coordinate system is origin-top-left (0,0) with Y increasing downwards.
111/// 2. Colors are [R, G, B, A] in the [0.0, 1.0] range.
112/// 3. All operations must be batchable by the underlying backend.
113///    Trait providing timing information for the render loop.
114pub mod renderer_trait;
115pub use renderer::*;
116pub use renderer_trait::*;
117pub mod accessibility;
118pub use accessibility::*;
119/// Defines the hardware acceleration tier and feature set available to the renderer.
120pub mod render_tier;
121pub use render_tier::*;
122pub mod mesh;
123pub use mesh::*;
124
125impl Default for Camera3D {
126    fn default() -> Self {
127        Self {
128            position: glam::Vec3::new(0.0, 0.0, 10.0),
129            target: glam::Vec3::ZERO,
130            up: glam::Vec3::Y,
131            fov_y: 45.0f32.to_radians(),
132            near: 0.1,
133            far: 1000.0,
134            perspective: true,
135            aspect: 16.0 / 9.0,
136        }
137    }
138}
139
140impl Camera3D {
141    /// Compute the view matrix (world → camera space).
142    pub fn view_matrix(&self) -> glam::Mat4 {
143        glam::Mat4::look_at_lh(self.position, self.target, self.up)
144    }
145
146    /// Compute the projection matrix.
147    pub fn projection_matrix(&self) -> glam::Mat4 {
148        if self.perspective {
149            glam::Mat4::perspective_lh(self.fov_y, self.aspect, self.near, self.far)
150        } else {
151            // Orthographic with fov_y as half-height
152            let top = self.fov_y;
153            let right = top * self.aspect;
154            glam::Mat4::orthographic_lh(-right, right, -top, top, self.near, self.far)
155        }
156    }
157
158    /// Compute the combined view-projection matrix.
159    pub fn view_projection(&self) -> glam::Mat4 {
160        self.projection_matrix() * self.view_matrix()
161    }
162}
163
164/// FrameRenderer extends Renderer with frame lifecycle management.
165/// It is typically implemented by the host windowing/rendering environment.
166pub mod spring;
167pub use spring::*;
168pub mod frame_renderer;
169pub use frame_renderer::*;
170pub mod state;
171pub use state::*;
172pub mod env_core;
173pub use env_core::*;
174pub mod env;
175pub use env::*;
176/// Geometry modifiers
177/// Size of the view in logical pixels
178pub mod geometry_modifiers;
179#[allow(ambiguous_glob_reexports)]
180pub use geometry_modifiers::*;
181pub mod layout;
182pub use layout::*;
183
184// Size and FrameRenderer are pub items in this module; no re-export alias needed.
185
186pub mod agents;
187pub mod animation;
188pub mod frame_phase;
189pub mod gpu;
190pub mod material;
191pub mod runtime;
192pub mod scene_graph;
193pub use frame_phase::FramePhase;
194pub mod frame_manifest;
195pub use frame_manifest::validate_manifests;
196pub use frame_manifest::{FrameManifest, PassNode, PassNodeDescriptor, TimeBudgetRequest};
197pub mod sdf_shadow;
198pub mod shadow;
199
200// Re-export commonly used types
201pub use layout::{LayoutCache, LayoutKey, LayoutView, Rect, SizeProposal};
202pub use material::DrawMaterial;
203pub use scene_graph::{NodeId, bifrost_registry};
204pub mod color;
205pub mod data_table;
206pub mod elevation;
207pub mod form_validation;
208pub mod responsive;
209pub use color::SemanticColors;
210
211// Duplicate AssetState removed - original definition at line 67
212
213/// AssetManager defines the interface for loading and caching external resources.
214pub mod event;
215pub use event::*;
216pub mod suspense;
217pub use suspense::*;
218/// Berserker mode states for the rendering pipeline.
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220pub enum RenderIntensityMode {
221    Normal,
222    Rage,    // Red tint, slight shake
223    Frenzy,  // Heavy red tint, motion blur, aggressive shake
224    GodMode, // Golden aura, lightning arcs
225}
226
227/// Seer trait for AI-assisted UI components.
228/// Allows components to receive "prophecies" (predictions) from an AI backend.
229pub trait Seer: Send + Sync {
230    /// Provide a prediction for the next user action or content.
231    fn predict(&self, context: &str) -> String;
232    /// Stream real-time "whispers" (transcriptions/intent).
233    fn whispers(&self) -> Vec<String>;
234}
235
236pub mod theme;
237pub use theme::{
238    ThemeContext, clear_current_theme, glassmorphism_enabled, set_current_theme, set_theme_context,
239    use_theme, use_theme_context,
240};
241
242pub mod hooks;
243pub use hooks::*;
244
245pub mod a11y_prefs;
246pub use a11y_prefs::*;
247pub mod clipboard;
248pub use clipboard::*;
249
250// =============================================================================
251// TEXT INPUT -- Direction enum for cursor movement
252// =============================================================================
253
254pub mod text_input;
255pub use text_input::*;
256
257/// Action details for interactive buttons inside a notification.
258pub mod notifications;
259pub use notifications::*;
260pub mod file_dialog;
261pub use file_dialog::*;
262pub mod document;
263pub use document::*;
264pub mod menu;
265pub use menu::*;
266pub mod localization;
267pub use localization::*;
268
269pub mod system_theme;
270pub use system_theme::*;
271// AUDIO / HAPTIC -- Item 14: Spatial Audio / Haptic Feedback
272// =============================================================================
273// OS-agnostic: pure trait abstractions. Platform backends via cfg in renderer.
274
275pub mod audio_haptic;
276pub use audio_haptic::{
277    AudioEngine, HapticEngine, HapticIntensity, NullAudioEngine, NullHapticEngine, haptic_error,
278    haptic_impact, haptic_selection, haptic_success, play_sound, set_audio_engine,
279    set_haptic_engine, sounds,
280};
281
282// =============================================================================
283// PARALLAX -- Depth-based scroll offset system
284// =============================================================================
285
286pub mod parallax;
287pub use parallax::{DisplayEnvironment, ParallaxModifier, PerformanceContract, Tier3Fallback};
288
289pub mod identity;
290pub use identity::*;
291
292pub mod simple_geom;
293pub use simple_geom::*;
294pub mod dirty_flags;
295pub use dirty_flags::*;
296
297// =========================================================================
298// P1-15: Subscriber List Mutex Poisoning
299// =========================================================================
300//
301// Regression tests for the audit finding: a single panicking subscriber
302// would poison the Mutex and break all future state updates forever.
303// The fix wraps each callback in catch_unwind, so panics are isolated
304// and logged without affecting other subscribers or future updates.
305
306// =========================================================================
307// P1-17: Suspense::new_async Shared Fallback Runtime
308// =========================================================================
309//
310// Regression tests for the audit finding: when no ambient tokio
311// runtime exists, new_async spawned a new OS thread + runtime per
312// call. The fix introduces a process-wide shared fallback runtime.
313
314pub mod dirty_region;
315pub use dirty_region::*;
316
317// =========================================================================
318// P1-43: Typed Event Triggers (Bevy-inspired)
319// =========================================================================
320pub mod triggers;
321pub use triggers::{EventCtx, TriggerEvent, TriggerRegistry};
322
323// =========================================================================
324// P1-43: FrameBudget -- global frame budget contract
325// =========================================================================
326//
327// The P1-43 audit found that no global frame budget contract
328// exists. Individual subsystems may exceed their time allocation
329// without coordination. P0-2 already handles per-frame
330// degradation (skipping non-essential passes when over budget)
331// but doesn't coordinate allocation across subsystems.
332//
333// This struct provides the foundation for future frame budget
334// coordination. It tracks wall-clock time per frame and per
335// subsystem, and allows callers to check whether a subsystem
336// is within its allocated time slice.
337//
338// Currently a passive observer. Future work would add:
339//  - Per-subsystem time allocation
340//  - Automatic QualityLevel adjustment when over budget
341//  - Integration with the renderer's frame loop
342pub mod virtual_window;
343pub use virtual_window::*;
344
345// Test infrastructure -- MockRenderer and test-call recording
346pub mod testing;