### Clone and Run VIVIM App (Bash) Source: https://github.com/owenservera/vivim-app/blob/main/docs/development/guide.md Clones the VIVIM app repository, installs dependencies using Bun, and starts all services. It also shows how to start individual services like the PWA, API server, network engine, and admin panel. ```bash # Clone the repository git clone https://github.com/vivim/vivim-app.git cd vivim-app # Install dependencies bun run setup # Start all services bun run dev # Or start individually bun run dev:pwa # Frontend (http://localhost:5173) bun run dev:server # API (http://localhost:3000) bun run dev:network # Network engine bun run dev:admin # Admin panel (http://localhost:5174) ``` -------------------------------- ### Database Setup SQL Commands Source: https://github.com/owenservera/vivim-app/blob/main/docs/deployment/guide.md SQL commands for setting up the PostgreSQL database for VIVIM. Includes database creation, extension setup (uuid-ossp, pg_trgm, vector), and a placeholder for running migrations. ```sql -- Create database CREATE DATABASE vivim; -- Create extensions CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; CREATE EXTENSION IF NOT EXISTS "pg_trgm"; CREATE EXTENSION IF NOT EXISTS "vector"; -- Run migrations -- bun run db:migrate ``` -------------------------------- ### Compile and Run C Code Guide Source: https://github.com/owenservera/vivim-app/blob/main/server/debug-chatgpt-1771911885291.html Provides instructions on how to compile and run C code on various operating systems. It covers installing a C compiler (GCC/Clang), saving the code, compiling using GCC with the math library, and executing the program. It also details the expected output and suggests parameter tuning. ```bash sudo apt update sudo apt install build-essential ``` ```bash brew install gcc ``` ```bash gcc -o reasoning_engine reasoning_engine.c -lm ``` ```bash ./reasoning_engine ``` ```bash reasoning_engine.exe ``` -------------------------------- ### Backend (Server) Development Commands with Bun Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/CONTEXT/AI_CONTEXT.md Details the commands required for the backend server development using Bun. It covers dependency installation, Prisma client generation and database schema management, and starting the development server. ```bash cd server # Install dependencies bun install # Generate Prisma client bun run db:generate # Push schema to database bun run db:push # Start development server bun run dev ``` -------------------------------- ### Frontend (PWA) Development Commands with Bun Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/CONTEXT/AI_CONTEXT.md Provides essential commands for managing the frontend PWA using Bun. This includes installing dependencies, starting the development server, building for production, running tests, performing type checking, and linting. ```bash cd pwa # Install dependencies bun install # Start development server bun run dev # Build for production bun run build # Run tests bun run test # Type check bun run typecheck # Lint bun run lint ``` -------------------------------- ### MFA Setup and Enablement Source: https://github.com/owenservera/vivim-app/blob/main/server/temp_test2.txt This section covers the Multi-Factor Authentication (MFA) setup and enablement process. It includes API calls for initiating MFA setup, which returns a secret, and for enabling MFA, which provides backup codes. These operations are part of the user security features. ```bash ✅ GET /me/api-keys successful. User has 1 keys. ✅ MFA Setup successful. Secret: GIMCGLD3AUYQOWLE ✅ MFA Enable successful. Received backup codes: [ "bf56e2ee", "7ae2b324", "ddde9618", "7be78e76", "6f5f16a5", "bc284603", "808ddc67", "355bf8bd" ] ``` -------------------------------- ### MFA Setup and Enablement Source: https://github.com/owenservera/vivim-app/blob/main/server/temp_test3.txt This section covers the Multi-Factor Authentication (MFA) setup and enablement process. It includes API calls for initiating MFA setup, which returns a secret, and for enabling MFA, which provides backup codes. ```http POST /me/mfa/setup POST /me/mfa/enable ``` -------------------------------- ### API Call Debugging (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND_DEBUGGING_GUIDE.md Provides example code for debugging API calls by logging the initiation of a request, the completion of a request with status and duration, and details of any request failures. ```typescript // Before API call debug.debug('API', 'Request initiated', { endpoint, method, data }); // After response debug.info('API', 'Request completed', { endpoint, status: response.status, duration }); // On error debug.error('API', 'Request failed', error, { endpoint, status: response?.status, responseData }); ``` -------------------------------- ### Vivim App Database Setup and Schema Application (SQL) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/PITCH/OPERATIONS/README.md This snippet details the process of setting up the Vivim App database. It includes commands to create the database and then apply all schema files in the correct order. Dependencies include a PostgreSQL client and the schema SQL files. ```sql createdb vivim_costs_db psql -d vivim_costs_db -f schemas/01_people_labor_schema.sql psql -d vivim_costs_db -f schemas/02_tools_infrastructure_schema.sql psql -d vivim_costs_db -f schemas/03_users_operations_schema.sql psql -d vivim_costs_db -f schemas/04_governance_legal_schema.sql psql -d vivim_costs_db -f schemas/05_dao_governance_schema.sql psql -d vivim_costs_db -f schemas/06_ai_wiki_schema.sql psql -d vivim_costs_db -f schemas/07_work_management_schema.sql psql -d vivim_costs_db -f schemas/08_ai_agents_schema.sql psql -d vivim_costs_db -f schemas/09_community_schema.sql psql -d vivim_costs_db -f schemas/10_operations_management_schema.sql ``` -------------------------------- ### Get and Log Performance Metrics (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND_DEBUGGING_GUIDE.md Retrieves current performance metrics like memory usage, network latency, and response time using the unifiedDebugService. It then logs these metrics to the console and includes a conditional warning for slow response times. ```typescript import { unifiedDebugService } from './lib/unified-debug-service'; // Get current performance metrics const metrics = unifiedDebugService.getPerformanceMetrics(); console.log('Memory Usage:', metrics.memoryUsage); console.log('Network Latency:', metrics.networkLatency); console.log('Response Time:', metrics.responseTime); // Report performance issues if (responseTime > 5000) { debug.warn('Performance', 'Slow response detected', { endpoint, responseTime, threshold: 5000 }); } ``` -------------------------------- ### Automatic Flow Tracking with Unified Debug Service (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND_DEBUGGING_GUIDE.md This example showcases automatic tracking of common operations like API requests and database operations using helper methods from the unified debug service. It simplifies the process of instrumenting these flows. ```typescript import { unifiedDebugService } from './lib/unified-debug-service'; // Track API requests automatically const users = await unifiedDebugService.trackApiRequest( '/api/users', 'GET', async () => { const response = await fetch('/api/users'); return response.json(); }, { filters: { status: 'active' } } ); // Track database operations automatically const result = await unifiedDebugService.trackDatabaseOperation( 'INSERT', 'users', async () => { return await db.user.create({ data: userData }); }, { query: userData } ); ``` -------------------------------- ### VIVIM Icon Library CLI Examples Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/ICONS/README.md Illustrates common commands for the VIVIM Icon Library CLI, including listing all icons, searching for icons by term, retrieving icon information, and previewing icon usage in code. ```bash # List all icons bun ./cli.mjs list # Search for home-related icons bun ./cli.mjs search "home" # Get information about a specific icon bun ./cli.mjs info "home-feed" # Preview how to use an icon in code bun ./cli.mjs preview "settings-cog" ``` -------------------------------- ### Basic Logging with Unified Debug Service (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND_DEBUGGING_GUIDE.md This example shows how to perform basic logging (trace, debug, info, warn, error) using the unified debug service. It highlights how to specify a source and provide relevant data for each log entry. ```typescript import { debug } from './lib/unified-debug-service'; // Trace - Very detailed diagnostic info debug.trace('Router', 'Route matched', { path: '/users', params: { id: 1 } }); // Debug - Debugging information debug.debug('API', 'Request started', { endpoint: '/api/users', method: 'GET' }); // Info - General operational info debug.info('Auth', 'User logged in', { userId: user.id, method: 'google' }); // Warn - Potential issues debug.warn('Storage', 'Storage quota nearly exceeded', { used: 4.8, limit: 5 }); // Error - Actual errors debug.error('Database', 'Query failed', error, { query: sql, params }); ``` -------------------------------- ### Project Build and Development Commands Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND/FRONTEND.md Lists essential commands for developing, building, linting, testing, and type-checking the project using Bun. It covers starting development servers, creating production builds, running linters, executing tests with coverage, and performing TypeScript type checks. ```bash # Development bun run dev # Start dev server bun run dev:vite # Start Vite dev server # Build bun run build # Production build bun run build:tsc # TypeScript compilation only bun run build:vite # Vite build # Linting bun run lint # Run ESLint bun run lint:fix # Fix ESLint issues # Testing bun run test # Run tests bun run test:ui # Run tests with UI bun run test:coverage # Run tests with coverage # Type checking bun run typecheck # TypeScript type check ``` -------------------------------- ### Set Up VIVIM Database with Prisma (Bash) Source: https://github.com/owenservera/vivim-app/blob/main/docs/development/guide.md Commands to set up the VIVIM application's database using Prisma. This includes generating the Prisma client, running database migrations, and seeding the database with sample data. ```bash # Generate Prisma client cd server && bun run db:generate # Run migrations cd server && bun run db:migrate # Seed with sample data cd server && bun run db:seed ``` -------------------------------- ### Sync Operation Debugging (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND_DEBUGGING_GUIDE.md Demonstrates debugging synchronization processes. It includes starting a sync flow with a unique ID and tracking individual steps within that sync operation, marking them as pending or successful. ```typescript // Start sync flow const syncId = debug.startFlow(); // Track sync steps debug.trackStep(syncId, 'sync', 'pending', { direction: 'push' }); // ... sync operation debug.trackStep(syncId, 'sync', 'success', { changesPushed: 5 }); ``` -------------------------------- ### State Management Debugging (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND_DEBUGGING_GUIDE.md Illustrates how to debug state management operations. It shows logging the start of a state update with relevant payload and logging the state change with previous and new state details. ```typescript // Before state update debug.trace('Store', 'State update started', { store: 'user', action: 'SET_NAME', payload }); // After state update debug.debug('Store', 'State updated', { store: 'user', previousState, newState }); ``` -------------------------------- ### Data Flow Tracking with Unified Debug Service (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND_DEBUGGING_GUIDE.md This TypeScript code illustrates how to track the complete journey of data through your application using the unified debug service. It demonstrates starting a flow, tracking individual steps with their status, and handling errors. ```typescript import { debug } from './lib/unified-debug-service'; async function fetchData(endpoint: string) { // Start a new flow const requestId = debug.startFlow(); try { // Track each step debug.trackStep(requestId, 'request', 'pending', { endpoint }); const response = await fetch(endpoint); debug.trackStep(requestId, 'request', 'success', { status: response.status }); debug.trackStep(requestId, 'validation', 'pending'); const data = await response.json(); debug.trackStep(requestId, 'validation', 'success', { size: data.length }); debug.trackStep(requestId, 'processing', 'pending'); const processed = processData(data); debug.trackStep(requestId, 'processing', 'success', { resultSize: processed.length }); debug.trackStep(requestId, 'database', 'pending', { operation: 'INSERT' }); await saveToDatabase(processed); debug.trackStep(requestId, 'database', 'success', { rowsAffected: 1 }); debug.trackStep(requestId, 'response', 'success', { duration: Date.now() - startTime }); return processed; } catch (error) { debug.trackStep(requestId, 'error', 'error', {}, error.message); throw error; } } ``` -------------------------------- ### Session-Based Authentication Example (Bash) Source: https://github.com/owenservera/vivim-app/blob/main/docs/api/overview.md Demonstrates how to initiate session-based authentication using Google OAuth and highlights the structure of the session cookie returned. ```bash # Login with Google GET /api/v1/auth/google # Redirects to Google OAuth # Session cookie (HttpOnly, Secure) Set-Cookie: connect.sid=s%3A...; Path=/; HttpOnly; Secure ``` -------------------------------- ### Vivim-App Main Execution Function Source: https://github.com/owenservera/vivim-app/blob/main/server/debug-chatgpt-1771914943820.html The 'main' function serves as the entry point for the Vivim-App simulation. It initializes the random number generator and the system state, then runs the simulation for a predefined number of steps (STEPS). After the simulation, it prints a snapshot of the final signal values for each node. Dependencies include init_genrand, init_system, step_system, and diagnostics functions, along with the STEPS constant. ```c++ int main() { init_genrand(5489UL); init_system(); for (int t = 0; t < STEPS; t++) { step_system(); diagnostics(t); } printf("\nFinal signal snapshot:\n"); for (int i = 0; i < NODES; i++) { printf("node %02d : %.6f\n", i, signal[i]); } return 0; } ``` -------------------------------- ### Troubleshoot Port Already in Use (Bash) Source: https://github.com/owenservera/vivim-app/blob/main/docs/development/guide.md Provides commands to identify and terminate processes that are using a specific port, which is a common issue when starting development servers. ```bash # Find process using port lsof -i :3000 # Kill process kill -9 ``` -------------------------------- ### Working with Promises Source: https://github.com/owenservera/vivim-app/blob/main/server/tests/html-dls-cli/deepseek-cli.html Shows how to create and consume Promises for handling asynchronous operations. Provides a cleaner way to manage callbacks. ```javascript function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function runWithDelay() { console.log('Starting...'); await delay(1000); console.log('...Finished after 1 second.'); } runWithDelay(); ``` -------------------------------- ### OpenAI API Integration Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/AI_API/ai-models-integration-2026.md This section details the integration of OpenAI's models, including recommended models, API endpoints, and a TypeScript code example for chat completions. ```APIDOC ## OpenAI API Integration ### Description This section provides details on integrating with OpenAI's models, including recommended models like GPT-5.2 and GPT-5 mini, their use cases, context windows, and pricing. It also includes the API base URL and specific endpoints for Chat Completions and a new Response API. ### Method POST ### Endpoint `https://api.openai.com/v1/chat/completions` ### Parameters #### Query Parameters None #### Request Body - **model** (string) - Required - The model to use for completion. - **messages** (array) - Required - An array of message objects representing the conversation history. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate in the completion. - **temperature** (number) - Optional - Controls randomness. Lower values make the output more deterministic. - **stream** (boolean) - Optional - Whether to stream back partial progress. ### Request Example ```json { "model": "gpt-5.2", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ], "max_tokens": 100, "temperature": 0.7, "stream": false } ``` ### Response #### Success Response (200) - **choices** (array) - An array of completion choices. - **message** (object) - The generated message. - **role** (string) - The role of the author of the message (e.g., 'assistant'). - **content** (string) - The content of the message. #### Response Example ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1700000000, "model": "gpt-5.2", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 10, "completion_tokens": 15, "total_tokens": 25 } } ``` ### Key Features - Function calling v3 - Structured outputs (JSON mode) - Vision capabilities - Web search integration - Code interpreter - Prompt caching - Batch processing ``` -------------------------------- ### Neural Network Training and Testing Main Function (C) Source: https://github.com/owenservera/vivim-app/blob/main/server/debug-chatgpt-1771913454730.html This C code demonstrates the main execution flow for training and testing a neural network. It sets up XOR problem data, initializes weights, and iterates through epochs, applying packet loss simulation, signal correction, feedforward, backpropagation, and SOM. Finally, it tests the trained network. ```c int main() { // XOR problem input data with packet loss simulation float inputs[4][INPUT_NEURONS] = {{0, 0, 1, 0}, {0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 1, 0}}; float expected_outputs[4] = {0, 1, 1, 0}; // Initialize weights for hidden layer and output layer float hidden_weights[INPUT_NEURONS * HIDDEN_NEURONS]; float output_weights[HIDDEN_NEURONS]; float som_weights[OUTPUT_NEURONS][INPUT_NEURONS]; // Weights for SOM initialize_weights(hidden_weights, INPUT_NEURONS * HIDDEN_NEURONS); initialize_weights(output_weights, HIDDEN_NEURONS); initialize_weights(&som_weights[0][0], OUTPUT_NEURONS * INPUT_NEURONS); // Training the network with feedback loop and packet loss simulation for (int epoch = 0; epoch < ITERATIONS; epoch++) { for (int i = 0; i < 4; i++) { float hidden_layer[HIDDEN_NEURONS]; float output; // Simulate packet loss on inputs introduce_packet_loss(inputs[i], INPUT_NEURONS); // Perform signal correction float corrected_data[INPUT_NEURONS]; signal_correction(inputs[i], corrected_data, INPUT_NEURONS); // Feedforward propagation feedforward(corrected_data, hidden_weights, output_weights, hidden_layer, &output); // Backpropagation (feedback loop) backpropagation(corrected_data, hidden_weights, output_weights, hidden_layer, &output, expected_outputs[i]); // Apply Self-Organizing Map (SOM) for clustering som(corrected_data, som_weights); } } // Test the trained network printf("Testing the trained network:\n"); for (int i = 0; i < 4; i++) { float hidden_layer[HIDDEN_NEURONS]; float output; introduce_packet_loss(inputs[i], INPUT_NEURONS); // Packet loss during test float corrected_data[INPUT_NEURONS]; signal_correction(inputs[i], corrected_data, INPUT_NEURONS); feedforward(corrected_data, hidden_weights, output_weights, hidden_layer, &output); printf("Input: %.0f,\",{\"_140\":863,\"_142\":864,\"_144\":-5,\"_145\":865,\"_151\":12,\" } return 0; } ``` -------------------------------- ### Create Context Bundle (Context API) Source: https://context7.com/owenservera/vivim-app/llms.txt Creates a new context bundle, which can group topics, entities, and ACUs for a specific purpose like a project. Requires a name, description, and relevant IDs. Requires authentication. ```bash curl -X POST "https://api.vivim.app/api/v2/context/bundles" \ -H "Content-Type: application/json" \ -H "x-did: did:key:z6Mk..." \ -d '{ "name": "Machine Learning Project", "description": "Context for ML development", "topicIds": ["topic-1", "topic-2"], "entityIds": ["entity-1"], "acuIds": ["acu-1", "acu-2"], "bundleType": "project" }' ``` -------------------------------- ### Create and Deploy Prisma Schema Migration (Bash) Source: https://github.com/owenservera/vivim-app/blob/main/server/prisma/SCHEMA_MIGRATION_GUIDE.md This snippet demonstrates how to create a new database migration for the extended Prisma schema and then deploy it. It assumes you are in the 'apps/server' directory and have Prisma installed. ```bash cd apps/server bunx prisma migrate dev --name add_acu_tables --schema prisma/schema-extended.prisma bunx prisma migrate deploy bunx prisma generate --schema prisma/schema-extended.prisma ``` -------------------------------- ### Error Statistics API Response (JSON) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/ERROR_REPORTING.md Provides an example of the JSON response structure for the GET /api/v1/errors/stats endpoint. This response includes aggregated statistics about errors, categorized by level, component, and severity. ```json { "success": true, "data": { "total": 1000, "byLevel": { "error": 500, "warning": 300, "info": 200 }, "byComponent": { "pwa": 400, "server": 300, "network": 300 }, "bySeverity": { "critical": 50, "high": 200, "medium": 400, "low": 350 }, "recent": 50, "trending": [...], "topErrors": [...] } } ``` -------------------------------- ### MFA Setup and Enablement Source: https://github.com/owenservera/vivim-app/blob/main/server/temp_test.txt This section details the process of setting up and enabling Multi-Factor Authentication (MFA) for a user. It includes API calls to '/me/mfa/setup' and '/me/mfa/enable'. The output shows the generated MFA secret and backup codes, which are crucial for user account security. ```shell # Testing POST /me/mfa/setup... # MFA Setup successful. Secret: IU2AYNJUJ5FBKABA # Testing POST /me/mfa/enable... # MFA Enable successful. Received backup codes: [ "01286a38", "fb119225", "5af56753", # "0fbdaf88", "295eb812", "b82f51f3", "33ac74e8", "58007b00" ] ``` -------------------------------- ### xAI (Grok) API Integration Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/AI_API/ai-models-integration-2026.md This section covers the integration with xAI's Grok models, including recommended models, API endpoints for chat and deferred completions, and a TypeScript code example. ```APIDOC ## xAI (Grok) API Integration ### Description This section details the integration with xAI's Grok models, recommending Grok 4.1 and Grok 3 for various use cases. It provides the API base URL and endpoints for Chat Completions, Deferred Completions, and the Batch API. ### Method POST ### Endpoint `https://api.x.ai/v1/chat/completions` ### Parameters #### Query Parameters None #### Request Body - **model** (string) - Required - The model to use for completion. - **messages** (array) - Required - An array of message objects representing the conversation history. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate in the completion. - **temperature** (number) - Optional - Controls randomness. Lower values make the output more deterministic. ### Request Example ```json { "model": "grok-4.1", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain the concept of quantum entanglement."} ], "max_tokens": 500, "temperature": 0.7 } ``` ### Response #### Success Response (200) - **choices** (array) - An array of completion choices. - **message** (object) - The generated message. - **role** (string) - The role of the author of the message (e.g., 'assistant'). - **content** (string) - The content of the message. #### Response Example ```json { "id": "chatcmpl-xyz789", "object": "chat.completion", "created": 1700000001, "model": "grok-4.1", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Quantum entanglement is a phenomenon where two or more quantum particles become linked in such a way that they share the same fate, regardless of the distance separating them..." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 20, "completion_tokens": 150, "total_tokens": 170 } } ``` ### Key Features - Reasoning models for scientific problems - Agent Tools API (server & client-side tool calling) - Real-time search from X - Enterprise security (SSO, audit logs) - OpenAI-compatible endpoints via some proxies ``` -------------------------------- ### RAG Neural Network Training Example (C) Source: https://github.com/owenservera/vivim-app/blob/main/server/debug-chatgpt-1771911565367.html Demonstrates the training process for a RAG neural network using the XOR problem. It initializes the Mersenne Twister, sets up input and expected output data for the XOR problem, initializes network weights, and then enters a training loop where feedforward and backpropagation are applied iteratively. ```c int main() { init_genrand(5489UL); // Initialize Mersenne Twister with a seed // XOR problem input and expected output float inputs[4][INPUT_NEURONS] = {{0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}}; float expected_outputs[4][OUTPUT_NEURONS] = {{1, 0}, {0, 1}, {0, 1}, {1, 0}}; // Initialize weights with random connections float weights[INPUT_NEURONS][HIDDEN_NEURONS]; // Weights between input and hidden layer float output_weights[HIDDEN_NEURONS][OUTPUT_NEURONS]; // Weights between hidden and output layer initialize_weights(weights, INPUT_NEURONS, HIDDEN_NEURONS, CONNECTION_PROB); initialize_weights(output_weights, HIDDEN_NEURONS, OUTPUT_NEURONS, CONNECTION_PROB); // Variables for storing hidden layer and output layer values float hidden_layer[HIDDEN_NEURONS]; float outputs[OUTPUT_NEURONS]; // Training the network // ... (Training loop would follow here, calling feedforward and backpropagation) ``` -------------------------------- ### Minimal C Implementation of Pre-Cognitive Signal Substrate Source: https://github.com/owenservera/vivim-app/blob/main/server/debug-chatgpt-1771911885291.html A single-file, from-scratch C program implementing a pre-cognitive signal substrate. It demonstrates emergent phase behavior without external libraries beyond the C standard library. The code does not enforce phases but allows them to emerge from the system's dynamics. ```c #include #include #include /* ============================ MT19937 (compact inclusion) ============================ */ #define N_MT 624 #define M_MT 397 #define MATRIX_A 0x9908b0dfUL #define UPPER_MASK 0x80000000UL #define LOWER_MASK 0x7fffffffUL static unsigned long mt[N_MT]; static int mti = N_MT + 1; void init_genrand(unsigned long s) { mt[0] = s & 0xffffffffUL; for (mti = 1; mti < N_MT; mti++) { mt[mti] = (1812433253UL * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti); mt[mti] &= 0xffffffffUL; } } unsigned long genrand_int32(void) { unsigned long y; static unsigned long mag01[2] = {0x0UL, MATRIX_A}; if (mti >= N_MT) { int kk; for (kk = 0; kk < N_MT - M_MT; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M_MT] ^ (y >> 1) ^ mag01[y & 1]; } for (; kk < N_MT - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M_MT-N_MT)] ^ (y >> 1) ^ mag01[y & 1]; } y = (mt[N_MT-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N_MT-1] = mt[M_MT-1] ^ (y >> 1) ^ mag01[y & 1]; mti = 0; } y = mt[mti++]; y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } double rnd() { return genrand_int32() * (1.0 / 4294967296.0); } /* ============================ System parameters ============================ */ #define NODES 64 #define STEPS 5000 #define PACKET_LOSS 0.15 #define LAMBDA 0.96 #define EDGE_DELTA 0.001 #define EDGE_CUTOFF 0.0 /* ============================ Node state ============================ */ double signal[NODES]; double memory[NODES]; double entropy[NODES]; double edges[NODES][NODES]; /* ============================ Initialization ============================ */ void init_system() { for (int i = 0; i < NODES; i++) { signal[i] = rnd() * 2.0 - 1.0; memory[i] = signal[i]; entropy[i] = 0.0; for (int j = 0; j < NODES; j++) { edges[i][j] = (rn ``` -------------------------------- ### Tracking Data Flows for Important Operations Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/UNIFIED_DEBUGGING.md Reinforces the practice of tracking the complete flow of critical operations. This example shows how to use `startFlow` and `trackStep` to monitor an `importantOperation` from start to finish, including potential errors. ```typescript // Always track the complete flow of important operations async function importantOperation() { const requestId = debug.startFlow(); try { debug.trackStep(requestId, 'request', 'pending'); // ... operation debug.trackStep(requestId, 'request', 'success'); debug.trackStep(requestId, 'validation', 'pending'); // ... validation debug.trackStep(requestId, 'validation', 'success'); debug.trackStep(requestId, 'response', 'success'); } catch (error) { debug.trackStep(requestId, 'error', 'error', {}, error.message); throw error; } } ``` -------------------------------- ### Pre-Cognitive Signal Substrate Simulation in C Source: https://github.com/owenservera/vivim-app/blob/main/server/debug-chatgpt-1771914943820.html A single-file, from-scratch C program implementing a pre-cognitive signal substrate. It evolves through emergent phases (random diffusion, local stabilization, coherent regions, topology pruning, persistent structures) without explicit phase enforcement. No external libraries beyond the C standard library are used. Entropy is structural and packet loss is fundamental. ```c #include #include #include /* ============================ MT19937 (compact inclusion) ============================ */ #define N_MT 624 #define M_MT 397 #define MATRIX_A 0x9908b0dfUL #define UPPER_MASK 0x80000000UL #define LOWER_MASK 0x7fffffffUL static unsigned long mt[N_MT]; static int mti = N_MT + 1; void init_genrand(unsigned long s) { mt[0] = s & 0xffffffffUL; for (mti = 1; mti < N_MT; mti++) { mt[mti] = (1812433253UL * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti); mt[mti] &= 0xffffffffUL; } } unsigned long genrand_int32(void) { unsigned long y; static unsigned long mag01[2] = {0x0UL, MATRIX_A}; if (mti >= N_MT) { int kk; for (kk = 0; kk < N_MT - M_MT; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M_MT] ^ (y >> 1) ^ mag01[y & 1]; } for (; kk < N_MT - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M_MT-N_MT)] ^ (y >> 1) ^ mag01[y & 1]; } y = (mt[N_MT-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N_MT-1] = mt[M_MT-1] ^ (y >> 1) ^ mag01[y & 1]; mti = 0; } y = mt[mti++]; y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } double rnd() { return genrand_int32() * (1.0 / 4294967296.0); } /* ============================ System parameters ============================ */ #define NODES 64 #define STEPS 5000 #define PACKET_LOSS 0.15 #define LAMBDA 0.96 #define EDGE_DELTA 0.001 #define EDGE_CUTOFF 0.0 /* ============================ Node state ============================ */ double signal[NODES]; double memory[NODES]; double entropy[NODES]; double edges[NODES][NODES]; /* ============================ Initialization ============================ */ void init_system() { for (int i = 0; i < NODES; i++) { signal[i] = rnd() * 2.0 - 1.0; memory[i] = signal[i]; entropy[i] = 0.0; for (int j = 0; j < NODES; j++) { edges[i][j] = (rnd() < 0.5) ? (rnd() * 0.1) : 0.0; } } } /* ============================ Update step ============================ */ void step_system() { double new_signal[NODES]; for (int i = 0; i < NODES; i++) { double acc = 0.0; for (int j = 0; j < NODES; j++) { ``` -------------------------------- ### xAI (Grok) API Integration (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/AI_API/ai-models-integration-2026.md Provides a TypeScript example for integrating with the xAI (Grok) API. This function allows sending chat completions, specifying the model, messages, and other options. Authentication is handled via an API key. ```typescript const xAIClient = { async complete(model: string, messages: Message[], options: CompletionOptions) { const response = await fetch('https://api.x.ai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': `Bearer ${config.xaiApiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model, messages, max_tokens: options.maxTokens || 4096, temperature: options.temperature || 0.7 }) }); return response.json(); } }; ``` -------------------------------- ### Create Notebook (Context API) Source: https://context7.com/owenservera/vivim-app/llms.txt Creates a new notebook for organizing research notes or findings. Allows specifying a name, description, and color. Requires authentication. ```bash curl -X POST "https://api.vivim.app/api/v2/context/notebooks" \ -H "Content-Type: application/json" \ -H "x-did: did:key:z6Mk..." \ -d '{"name": "Research Notes", "description": "Collection of research findings", "color": "#4A90D9"}' ``` -------------------------------- ### Set User and Session Context for Logging (TypeScript) Source: https://github.com/owenservera/vivim-app/blob/main/VIVIM.docs/FRONTEND_DEBUGGING_GUIDE.md Sets the user ID and session ID using the debug service. All subsequent log messages will automatically include this context, aiding in tracking user-specific events and sessions. ```typescript import { debug } from './lib/unified-debug-service'; // Set user context (all subsequent logs will include this) debug.setUserId(user.id); debug.setSessionId(session.id); // Now all logs include user and session context debug.info('Auth', 'User performed action', { action: 'capture' }); ```