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 assets;
48pub mod dependency;
49pub mod error_boundary;
50pub mod knowledge;
51pub mod renderer;
52pub mod undo;
53pub mod virtual_list;
54pub mod window;
55
56// P1-13: re-exports for backward compatibility
57pub use asset::{AssetKey, AssetState, DesignTokens, TokenValue};
58pub use assets::{AssetHotReloadListener, AssetServer};
59pub use dependency::{DependencyGraph, FrameBudgetTracker, InputLatencyTracker, SubsystemBudget};
60pub use error_boundary::{ComponentErrorState, ErrorBoundary};
61#[cfg(not(target_arch = "wasm32"))]
62pub use knowledge::fallback_runtime;
63pub use knowledge::{
64    AnnouncementPriority, AppState, KnowledgeFragment, KnowledgeId, LAYOUT_DIRTY, MemoryLayer,
65    SYSTEM_STATE, TemporalEdge, TemporalNode, UiFidelityLevel, begin_render_phase,
66    end_render_phase, get_system_state, is_rendering, load_system_state, set_rendering,
67    snapshot_system_state, update_system_state,
68};
69pub use undo::{UndoGroup, UndoManager};
70pub use window::{Window, WindowCloseAction, WindowConfig, WindowHandle, WindowId, WindowLevel};
71
72pub mod companion;
73pub use companion::*;
74
75pub mod view;
76pub use view::*;
77pub mod aria;
78pub use aria::*;
79
80pub mod keyboard;
81pub use keyboard::*;
82
83pub mod focus;
84pub use focus::*;
85
86// =============================================================================
87// REDUCED MOTION
88// =============================================================================
89
90/// Detects OS-level reduced motion preference via [`AccessibilityPreferences`].
91///
92/// This delegates to `AccessibilityPreferences::detect_from_system()` which
93/// queries the correct OS API on macOS, Linux, and Windows.
94pub mod reduced_motion;
95pub use reduced_motion::*;
96
97/// An object-safe version of the View trait for type erasure.
98pub mod erased_view;
99pub use erased_view::*;
100
101/// SharedElementModifier enables shared-element transitions.
102/// When two views share the same Bifrost Bridge ID, the Sleipnir solver will
103/// interpolate their geometry and effects (blur, glow) during the transition.
104pub mod modifiers;
105pub use modifiers::*;
106pub mod render_base;
107pub use render_base::*;
108
109/// The Renderer trait defines the atomic drawing operations for all CVKG backends.
110/// This trait is object-safe and used by the View::render system.
111/// # Implementation Requirements
112/// 1. Coordinate system is origin-top-left (0,0) with Y increasing downwards.
113/// 2. Colors are [R, G, B, A] in the [0.0, 1.0] range.
114/// 3. All operations must be batchable by the underlying backend.
115///    Trait providing timing information for the render loop.
116pub mod renderer_trait;
117pub use renderer::*;
118pub use renderer_trait::*;
119pub mod accessibility;
120pub use accessibility::*;
121/// Defines the hardware acceleration tier and feature set available to the renderer.
122pub mod render_tier;
123pub use render_tier::*;
124pub mod mesh;
125pub use mesh::*;
126
127impl Default for Camera3D {
128    fn default() -> Self {
129        Self {
130            position: glam::Vec3::new(0.0, 0.0, 10.0),
131            target: glam::Vec3::ZERO,
132            up: glam::Vec3::Y,
133            fov_y: 45.0f32.to_radians(),
134            near: 0.1,
135            far: 1000.0,
136            perspective: true,
137            aspect: 16.0 / 9.0,
138        }
139    }
140}
141
142impl Camera3D {
143    /// Compute the view matrix (world → camera space).
144    pub fn view_matrix(&self) -> glam::Mat4 {
145        glam::Mat4::look_at_lh(self.position, self.target, self.up)
146    }
147
148    /// Compute the projection matrix.
149    pub fn projection_matrix(&self) -> glam::Mat4 {
150        if self.perspective {
151            glam::Mat4::perspective_lh(self.fov_y, self.aspect, self.near, self.far)
152        } else {
153            // Orthographic with fov_y as half-height
154            let top = self.fov_y;
155            let right = top * self.aspect;
156            glam::Mat4::orthographic_lh(-right, right, -top, top, self.near, self.far)
157        }
158    }
159
160    /// Compute the combined view-projection matrix.
161    pub fn view_projection(&self) -> glam::Mat4 {
162        self.projection_matrix() * self.view_matrix()
163    }
164}
165
166/// FrameRenderer extends Renderer with frame lifecycle management.
167/// It is typically implemented by the host windowing/rendering environment.
168pub mod spring;
169pub use spring::*;
170pub mod frame_renderer;
171pub use frame_renderer::*;
172pub mod state;
173pub use state::*;
174pub mod env_core;
175pub use env_core::*;
176pub mod env;
177pub use env::*;
178/// Geometry modifiers
179/// Size of the view in logical pixels
180pub mod geometry_modifiers;
181#[allow(ambiguous_glob_reexports)]
182pub use geometry_modifiers::*;
183pub mod layout;
184pub use layout::*;
185
186// Size and FrameRenderer are pub items in this module; no re-export alias needed.
187
188pub mod agents;
189pub mod animation;
190pub mod frame_phase;
191pub mod gpu;
192pub mod material;
193pub mod runtime;
194pub mod scene_graph;
195pub use frame_phase::FramePhase;
196pub mod frame_manifest;
197pub use frame_manifest::validate_manifests;
198pub use frame_manifest::{FrameManifest, PassNode, PassNodeDescriptor, TimeBudgetRequest};
199pub mod sdf_shadow;
200pub mod shadow;
201
202// Re-export commonly used types
203pub use layout::{LayoutCache, LayoutKey, LayoutView, Rect, SizeProposal};
204pub use material::DrawMaterial;
205pub use scene_graph::{NodeId, bifrost_registry};
206pub mod color;
207pub mod data_table;
208pub mod elevation;
209pub mod form_validation;
210pub mod responsive;
211pub use color::SemanticColors;
212
213// Duplicate AssetState removed - original definition at line 67
214
215/// AssetManager defines the interface for loading and caching external resources.
216pub mod event;
217pub use event::*;
218pub mod suspense;
219pub use suspense::*;
220/// Berserker mode states for the rendering pipeline.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum RenderIntensityMode {
223    Normal,
224    Rage,    // Red tint, slight shake
225    Frenzy,  // Heavy red tint, motion blur, aggressive shake
226    GodMode, // Golden aura, lightning arcs
227}
228
229/// Seer trait for AI-assisted UI components.
230/// Allows components to receive "prophecies" (predictions) from an AI backend.
231pub trait Seer: Send + Sync {
232    /// Provide a prediction for the next user action or content.
233    fn predict(&self, context: &str) -> String;
234    /// Stream real-time "whispers" (transcriptions/intent).
235    fn whispers(&self) -> Vec<String>;
236}
237
238pub mod theme;
239pub use theme::{
240    ThemeContext, clear_current_theme, glassmorphism_enabled, set_current_theme, set_theme_context,
241    use_theme, use_theme_context,
242};
243
244pub mod hooks;
245pub use hooks::*;
246
247pub mod a11y_prefs;
248pub use a11y_prefs::*;
249pub mod clipboard;
250pub use clipboard::*;
251
252// =============================================================================
253// TEXT INPUT -- Direction enum for cursor movement
254// =============================================================================
255
256pub mod text_input;
257pub use text_input::*;
258
259/// Action details for interactive buttons inside a notification.
260pub mod notifications;
261pub use notifications::*;
262pub mod file_dialog;
263pub use file_dialog::*;
264pub mod document;
265pub use document::*;
266pub mod menu;
267pub use menu::*;
268pub mod localization;
269pub use localization::*;
270
271pub mod system_theme;
272pub use system_theme::*;
273// AUDIO / HAPTIC -- Item 14: Spatial Audio / Haptic Feedback
274// =============================================================================
275// OS-agnostic: pure trait abstractions. Platform backends via cfg in renderer.
276
277pub mod audio_haptic;
278pub use audio_haptic::{
279    AudioEngine, HapticEngine, HapticIntensity, NullAudioEngine, NullHapticEngine, haptic_error,
280    haptic_impact, haptic_selection, haptic_success, play_sound, set_audio_engine,
281    set_haptic_engine, sounds,
282};
283
284// =============================================================================
285// PARALLAX -- Depth-based scroll offset system
286// =============================================================================
287
288pub mod parallax;
289pub use parallax::{DisplayEnvironment, ParallaxModifier, PerformanceContract, Tier3Fallback};
290
291pub mod identity;
292pub use identity::*;
293
294pub mod simple_geom;
295pub use simple_geom::*;
296pub mod dirty_flags;
297pub use dirty_flags::*;
298
299// =========================================================================
300// P1-15: Subscriber List Mutex Poisoning
301// =========================================================================
302//
303// Regression tests for the audit finding: a single panicking subscriber
304// would poison the Mutex and break all future state updates forever.
305// The fix wraps each callback in catch_unwind, so panics are isolated
306// and logged without affecting other subscribers or future updates.
307
308// =========================================================================
309// P1-17: Suspense::new_async Shared Fallback Runtime
310// =========================================================================
311//
312// Regression tests for the audit finding: when no ambient tokio
313// runtime exists, new_async spawned a new OS thread + runtime per
314// call. The fix introduces a process-wide shared fallback runtime.
315
316pub mod dirty_region;
317pub use dirty_region::*;
318
319// =========================================================================
320// P1-43: Typed Event Triggers (Bevy-inspired)
321// =========================================================================
322pub mod triggers;
323pub use triggers::{EventCtx, TriggerEvent, TriggerRegistry};
324
325// =========================================================================
326// P1-43: FrameBudget -- global frame budget contract
327// =========================================================================
328//
329// The P1-43 audit found that no global frame budget contract
330// exists. Individual subsystems may exceed their time allocation
331// without coordination. P0-2 already handles per-frame
332// degradation (skipping non-essential passes when over budget)
333// but doesn't coordinate allocation across subsystems.
334//
335// This struct provides the foundation for future frame budget
336// coordination. It tracks wall-clock time per frame and per
337// subsystem, and allows callers to check whether a subsystem
338// is within its allocated time slice.
339//
340// Currently a passive observer. Future work would add:
341//  - Per-subsystem time allocation
342//  - Automatic QualityLevel adjustment when over budget
343//  - Integration with the renderer's frame loop
344pub mod virtual_window;
345pub use virtual_window::*;
346
347// Test infrastructure -- MockRenderer and test-call recording
348pub mod testing;