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