State Management
Relevant source files
The following files were used as context for generating this wiki page:
State Management in the TAMV Digital Nexus project is handled through a centralized, persistent global store that orchestrates diverse domains including authentication, economy (TCEP/TAU), XR environments (Dream Spaces), and AI interactions. The architecture prioritizes a single source of truth for critical structural components while allowing modular interaction through specialized React hooks.
The system is built on Zustand for global state and relies on Supabase for persistent backend synchronization. It adheres to strict "Constitutional Quality Control" (QC-TAMV-01) laws which mandate that global state and service initializations occur only in explicit layers to prevent architectural degradation.
Sources: src/stores/tamvStore.ts:1-10, PLAN-TAMV-MODULAR.md:12-18, 02_MODULOS/M05_IA_TAMVAI/INTERNO/QC-TAMV-01-v1.1.md:105-115
Global Store Architecture
The core of the state management system is the tamvStore, which serves as the centralized hub for the MD-X4™ ecosystem. It utilizes middleware for persistence, ensuring that user sessions, wallet balances, and environmental coherence levels survive browser refreshes.
Store Domains and Data Models
The store is divided into several logical domains, each governed by specific interfaces:
| Domain | Key Data Structures | Purpose |
|---|---|---|
| Auth | User | Manages identity, dignity scores, and trust levels. |
| Economy | Wallet | Tracks TCEP/TAU balances and membership tiers (Celestial, Elite, etc.). |
| XR / Dream | DreamSpace | Controls active environments, participants, and coherence requirements. |
| AI | Message | Stores chat history with Isabella AI, including emotional context. |
| Notifications | Notification | Queues system, social, and achievement alerts. |
| University | CourseProgress | Tracks enrollment and completion status for TAMV courses. |
Sources: src/stores/tamvStore.ts:15-80
State Persistence and Security
The store uses localStorage via the persist middleware. To optimize performance and security, only a subset of the state is persisted, such as user data, wallet info, and the last 50 chatMessages.
The diagram shows how the UI triggers actions that update the global store, which is then synchronized with local storage and the Supabase backend.
Sources: src/stores/tamvStore.ts:265-285, PLAN-TAMV-MODULAR.md:200-215
Functional Integration Hooks
Rather than components accessing the store directly for every operation, the architecture uses a layer of specialized hooks (useTAMVSystems) to bridge the gap between raw state and domain-specific logic.
Specialized System Hooks
useQuantumState: An enhanced hook that provides access to the globalquantumCoherencelevel, active Dream Spaces, and authentication status. It serves as the primary interface for UI components to interact with the core ecosystem state.useEconomy: Interfaces with theEconomySystemto manage credit transfers, ticket purchases for lotteries, and membership upgrades.useNotifications: Provides a standardnotifyfunction to push typed alerts (info, success, warning, error) into the global state.useWebSocket: Manages real-time connectivity, specifically for chat messages and presence updates, mapping incoming data to store actions.
Sources: src/hooks/useTAMVSystems.ts:180-260, PLAN-TAMV-MODULAR.md:85-95
Data Flow for Real-time Updates
The project implements a "Unified WebSocket" strategy to ensure that state updates across multiple clients are handled efficiently.
The sequence diagram illustrates how local store updates are broadcast via WebSockets to maintain synchronization across the ecosystem.
Sources: src/hooks/useTAMVSystems.ts:255-290, PLAN-TAMV-MODULAR.md:90-105
Architectural Invariants (QC-TAMV-01)
State management is strictly governed by "Invariant Laws" to prevent spaghetti architecture. These rules are enforced via automated scripts and custom ESLint plugins.
- L5 – Pages without Domain Logic: React pages in
src/pages/are prohibited from containing persistent side-effects or direct service initializations. They must use modules or domains to manipulate state. - L7 – Controlled Initialization: Global services (Supabase, AI Gateway, Logging) must be initialized exactly once in explicit layers (
integrations/*orcore/*), never within a page. - Dependency Constraints: Modules (
src/modules/*) are agnostic of navigation; they cannot import the router or pages, ensuring that state-manipulating logic remains portable.
Sources: 02_MODULOS/M05_IA_TAMVAI/INTERNO/QC-TAMV-01-v1.1.md:65-95, scripts/check-architecture.ts:150-185
State and API Synchronization
The tamv-unified-api acts as the orchestrator for state transitions that require server-side validation, particularly for the Economy and DAO modules.
Transaction Flow Logic
When a user performs an economic action (e.g., TCEP transfer), the following state-api flow occurs:
- Client Validation: The
useEconomyhook checks the local store balance. - API Call: The client calls
/economy/transferon the Unified API. - MSR Logging: The API generates an evidence hash and logs a "Modular System Registry" (MSR) event for auditability.
- State Update: Upon success, the client store is updated via
updateBalanceor a fresh fetch from theid_nvidaidentity table.
Sources: supabase/functions/tamv-unified-api/index.ts:110-150, src/hooks/useTAMVSystems.ts:150-175
Summary of State Features
| Component | Logic Source | State Target |
|---|---|---|
| Auth | useQuantumState | user, isAuthenticated |
| Quantum Coherence | useTAMVStore | quantumCoherence (0-100 range) |
| Audio Config | useKAOSAudio | KAOSAudioSystem instance |
| Security Metrics | useAnubisSecurity | AnubisSecuritySystem metrics |
| Chat Logic | useWebSocket | chatMessages (last 50 persisted) |
Sources: src/hooks/useTAMVSystems.ts:30-220, src/stores/tamvStore.ts:150-200
State Management in the TAMV project is a hybrid of local persistence, real-time synchronization, and strict architectural enforcement. By centralizing core state in the tamvStore while abstracting access through specialized hooks, the system maintains a high degree of coherence and auditability across its modular domains.