Source identity
| Field | Recorded value |
|---|---|
| Source type | GitHub source |
| Original record | Janady13/AI_Brain / the_tired_agi/core/src/dna_core_real.cpp |
| Date | Not specified in source |
| Repository | Janady13/AI_Brain |
| Revision | d6c309d3fa439714ca46b9d3bb94caf478ea5376 |
| Branch | main |
| Path or archive member | the_tired_agi/core/src/dna_core_real.cpp |
| Original SHA-256 | 0cff57b2fc1851c1d95d5dedf9d56e0786dba3d6002d3de24205f8436faa3492 |
| Git blob SHA | 106e02f1a20cb9533508f64235fb639816ab5426 |
| Reading-copy SHA-256 | 0cff57b2fc1851c1d95d5dedf9d56e0786dba3d6002d3de24205f8436faa3492 |
Every recorded occurrence
These 2 records contain identical original source bytes. Their paths and revisions remain part of the archive.
| Original record | Branch or archive | Revision / identifier | Original location |
|---|---|---|---|
| Janady13/AI_Brain / the_tired_agi/core/src/dna_core_real.cpp | main | d6c309d3fa439714ca46b9d3bb94caf478ea5376 | Open original |
| Janady13/AI_Brain / the_tired_agi/core/src/dna_core_real.cpp | claude/binary-helix-fibonacci-hive-011CUj7dx1WWJLVYcWCjBbYv | 527d4882c71eb041393f9d8945996177c5ac9e86 | Open original |
Recovered source transcript
Download complete source text ↓476 lines · 15.4 KB
// ==============================================================================
// The-Tired-AGI Core: DNA Core Real-Time Loop
// 1kHz Tick Rate, Fibonacci Spiral Scheduler
// ==============================================================================
#include "helix.hpp"
#include "fgtp_engine.hpp"
#include "ingest_pipeline.hpp"
#include "agent_arrays.hpp"
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <signal.h>
#include <cstring>
#include <vector>
#include <random>
#include <fstream>
// Linux real-time scheduling headers
#ifdef __linux__
#include <sched.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <cerrno>
#endif
namespace tired_agi {
// ==============================================================================
// Real-Time Configuration
// ==============================================================================
struct RealTimeConfig {
uint32_t target_tick_rate_hz = 1000; // 1kHz target
size_t agent_batch_size = 10000; // Process 10k agents per tick
bool use_fibonacci_scheduler = true; // Fibonacci spiral timing
bool strict_realtime = false; // Hard real-time (requires root)
int cpu_affinity = -1; // CPU core to pin to (-1 = no pinning)
// Growth controls
uint64_t growth_interval_ticks = 144; // Fibonacci(12) = 144 ticks
double growth_threshold_phi = 0.8; // Require phi > 0.8 for growth
// Safety limits
uint64_t max_tick_overrun_us = 500; // Max allowed overrun (500μs)
size_t max_agents_per_tick = 50000; // Safety cap
};
// ==============================================================================
// DNA Core Real-Time System
// ==============================================================================
class DNACoreRealTime {
public:
explicit DNACoreRealTime(RealTimeConfig config = {}) noexcept;
~DNACoreRealTime();
// Main entry point
int run() noexcept;
// Shutdown request
void request_shutdown() noexcept { shutdown_requested_.store(true); }
private:
RealTimeConfig config_;
// Core engines
HelixEngine helix_engine_;
FGTPEngine fgtp_engine_;
IngestPipeline ingest_pipeline_;
AgentArrays agent_arrays_;
// State
std::atomic<bool> shutdown_requested_{false};
std::atomic<uint64_t> current_tick_{0};
std::atomic<uint64_t> total_overruns_{0};
// Timing
std::chrono::high_resolution_clock::time_point start_time_;
std::chrono::microseconds tick_period_us_;
// Main loop functions
void tick() noexcept;
void process_agents() noexcept;
void process_ingestion() noexcept;
void check_growth() noexcept;
void collect_statistics() noexcept;
// Timing utilities
void wait_for_next_tick(std::chrono::high_resolution_clock::time_point tick_start) noexcept;
uint64_t get_fibonacci_schedule(uint64_t tick) const noexcept;
// Setup
bool setup_realtime() noexcept;
void setup_signal_handlers() noexcept;
};
// ==============================================================================
// Global instance for signal handler
// ==============================================================================
static DNACoreRealTime* g_instance = nullptr;
void signal_handler(int signum) {
if (g_instance != nullptr) {
std::cout << "\nShutdown requested (signal " << signum << ")" << std::endl;
g_instance->request_shutdown();
}
}
// ==============================================================================
// Constructor / Destructor
// ==============================================================================
DNACoreRealTime::DNACoreRealTime(RealTimeConfig config) noexcept
: config_(config)
, helix_engine_()
, fgtp_engine_()
, ingest_pipeline_()
, agent_arrays_()
{
// Calculate tick period in microseconds
tick_period_us_ = std::chrono::microseconds(1000000 / config_.target_tick_rate_hz);
std::cout << "=== The-Tired-AGI DNA Core RT ===" << std::endl;
std::cout << "Target tick rate: " << config_.target_tick_rate_hz << " Hz" << std::endl;
std::cout << "Tick period: " << tick_period_us_.count() << " μs" << std::endl;
std::cout << "Agent arrays: " << agent_arrays_.capacity() << " capacity" << std::endl;
}
DNACoreRealTime::~DNACoreRealTime() {
g_instance = nullptr;
}
// ==============================================================================
// Main Loop
// ==============================================================================
int DNACoreRealTime::run() noexcept {
g_instance = this;
setup_signal_handlers();
if (config_.strict_realtime) {
if (!setup_realtime()) {
std::cerr << "Failed to setup real-time scheduling" << std::endl;
return 1;
}
}
std::cout << "Starting real-time loop..." << std::endl;
start_time_ = std::chrono::high_resolution_clock::now();
// Main loop
while (!shutdown_requested_.load()) {
auto tick_start = std::chrono::high_resolution_clock::now();
tick();
wait_for_next_tick(tick_start);
}
std::cout << "\nShutdown complete" << std::endl;
collect_statistics();
return 0;
}
// ==============================================================================
// Tick Processing
// ==============================================================================
void DNACoreRealTime::tick() noexcept {
uint64_t tick = current_tick_.fetch_add(1, std::memory_order_relaxed);
// Fibonacci spiral scheduling: only process on specific ticks
if (config_.use_fibonacci_scheduler) {
uint64_t schedule_mask = get_fibonacci_schedule(tick);
if ((tick & schedule_mask) != 0) {
return; // Skip this tick
}
}
// Process agents
process_agents();
// Process ingestion (less frequently)
if (tick % 10 == 0) {
process_ingestion();
}
// Check for growth (Fibonacci interval)
if (tick % config_.growth_interval_ticks == 0) {
check_growth();
}
// Statistics (every second)
if (tick % config_.target_tick_rate_hz == 0) {
collect_statistics();
}
}
void DNACoreRealTime::process_agents() noexcept {
uint64_t tick = current_tick_.load(std::memory_order_relaxed);
// Get active agents
auto agents = agent_arrays_.get_active_agents();
// Limit batch size for safety
size_t batch_size = std::min(agents.size(), config_.agent_batch_size);
if (batch_size > config_.max_agents_per_tick) {
batch_size = config_.max_agents_per_tick;
}
// Process batch of agents
for (size_t i = 0; i < batch_size && i < agents.size(); ++i) {
Agent* agent = agents[i];
if (agent->frozen) {
continue;
}
// Compute helix state
agent->helix = helix_engine_.compute(
agent->embedding.data(),
agent->embedding.size(),
tick
);
// Compute energy field
agent->energy = fgtp_engine_.compute_energy_field(agent->helix);
// Apply driver function (evolve embedding)
auto result = fgtp_engine_.apply_driver(
agent->embedding.data(),
agent->embedding.size(),
agent->energy
);
// Update agent state
if (result.bounded) {
agent->embedding = result.embedding;
agent->fitness += result.fitness_delta;
agent->last_update_tick = tick;
agent->update_count++;
}
}
}
void DNACoreRealTime::process_ingestion() noexcept {
// Pop embeddings from ring buffer and create agents
std::vector<double> embedding;
size_t created = 0;
while (agent_arrays_.pop_embedding(embedding) && created < 100) {
uint64_t tick = current_tick_.load(std::memory_order_relaxed);
auto agent_id = agent_arrays_.create_agent(embedding, tick);
if (agent_id.has_value()) {
created++;
} else {
// No more capacity, push back to ring buffer
agent_arrays_.push_embedding(embedding);
break;
}
}
}
void DNACoreRealTime::check_growth() noexcept {
// Check if we should grow the agent array
auto agents = agent_arrays_.get_active_agents();
if (agents.empty()) {
return;
}
// Calculate average phi
double sum_phi = 0.0;
for (const auto* agent : agents) {
sum_phi += agent->helix.phi;
}
double avg_phi = sum_phi / agents.size();
// Only grow if average phi is above threshold
if (avg_phi > config_.growth_threshold_phi) {
if (agent_arrays_.can_grow()) {
agent_arrays_.request_growth_step();
std::cout << "Growth: capacity now " << agent_arrays_.capacity()
<< " (Fibonacci index " << agent_arrays_.fibonacci_index() << ")"
<< std::endl;
}
}
}
void DNACoreRealTime::collect_statistics() noexcept {
uint64_t tick = current_tick_.load(std::memory_order_relaxed);
auto agent_stats = agent_arrays_.get_statistics();
auto fgtp_stats = fgtp_engine_.get_statistics();
auto ingest_stats = ingest_pipeline_.get_statistics();
// Calculate uptime
auto now = std::chrono::high_resolution_clock::now();
auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time_).count();
double uptime_sec = uptime_ms / 1000.0;
// Calculate actual tick rate
double actual_tick_rate = tick / uptime_sec;
std::cout << "\n=== Statistics (tick " << tick << ") ===" << std::endl;
std::cout << "Uptime: " << uptime_sec << " s" << std::endl;
std::cout << "Actual tick rate: " << actual_tick_rate << " Hz" << std::endl;
std::cout << "Tick overruns: " << total_overruns_.load() << std::endl;
std::cout << "\nAgents:" << std::endl;
std::cout << " Active: " << agent_stats.active_agents << " / " << agent_stats.total_agents << std::endl;
std::cout << " Frozen: " << agent_stats.frozen_agents << std::endl;
std::cout << " Avg phi: " << agent_stats.average_phi << std::endl;
std::cout << " Avg energy: " << agent_stats.average_energy << std::endl;
std::cout << " Avg fitness: " << agent_stats.average_fitness << std::endl;
std::cout << " Fibonacci index: " << agent_stats.fibonacci_index << std::endl;
std::cout << "\nFGTP Engine:" << std::endl;
std::cout << " Total computations: " << fgtp_stats.total_computations << std::endl;
std::cout << " Driver applications: " << fgtp_stats.total_driver_applications << std::endl;
std::cout << " Bound violations: " << fgtp_stats.total_violations << std::endl;
std::cout << "\nIngest Pipeline:" << std::endl;
std::cout << " Files processed: " << ingest_stats.total_files_processed << std::endl;
std::cout << " Chunks generated: " << ingest_stats.total_chunks_generated << std::endl;
std::cout << " Embeddings: " << ingest_stats.total_embeddings_generated << std::endl;
std::cout << " Processing rate: " << ingest_stats.processing_rate_mbps << " MB/s" << std::endl;
std::cout << std::endl;
}
// ==============================================================================
// Timing Utilities
// ==============================================================================
void DNACoreRealTime::wait_for_next_tick(
std::chrono::high_resolution_clock::time_point tick_start
) noexcept {
auto tick_end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(tick_end - tick_start);
if (elapsed > tick_period_us_) {
// Tick overrun
total_overruns_.fetch_add(1, std::memory_order_relaxed);
uint64_t overrun_us = (elapsed - tick_period_us_).count();
if (overrun_us > config_.max_tick_overrun_us) {
std::cerr << "WARNING: Severe tick overrun: " << overrun_us << " μs" << std::endl;
}
} else {
// Sleep for remaining time
auto sleep_duration = tick_period_us_ - elapsed;
std::this_thread::sleep_for(sleep_duration);
}
}
uint64_t DNACoreRealTime::get_fibonacci_schedule(uint64_t tick) const noexcept {
// Use Fibonacci sequence to determine processing schedule
// Lower index = more frequent processing
// Map tick to Fibonacci index (modulo to wrap around)
size_t fib_index = tick % FibonacciSequence::fibonacci.size();
uint32_t fib_value = FibonacciSequence::fibonacci[fib_index];
// Create mask from Fibonacci value (process every N ticks)
return fib_value - 1;
}
// ==============================================================================
// Setup
// ==============================================================================
bool DNACoreRealTime::setup_realtime() noexcept {
#ifdef __linux__
// Set real-time priority (requires CAP_SYS_NICE capability)
struct sched_param param;
param.sched_priority = 80; // High priority (1-99)
if (sched_setscheduler(0, SCHED_FIFO, ¶m) != 0) {
std::cerr << "Warning: Failed to set real-time priority: " << strerror(errno) << std::endl;
std::cerr << "Run with sudo or grant CAP_SYS_NICE capability" << std::endl;
return false;
}
// Set CPU affinity if requested
if (config_.cpu_affinity >= 0) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(config_.cpu_affinity, &cpuset);
if (pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) != 0) {
std::cerr << "Warning: Failed to set CPU affinity" << std::endl;
} else {
std::cout << "Pinned to CPU " << config_.cpu_affinity << std::endl;
}
}
// Lock memory to prevent paging
if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
std::cerr << "Warning: Failed to lock memory: " << strerror(errno) << std::endl;
}
std::cout << "Real-time scheduling enabled (SCHED_FIFO priority "
<< param.sched_priority << ")" << std::endl;
return true;
#else
std::cerr << "Real-time scheduling not supported on this platform" << std::endl;
return false;
#endif
}
void DNACoreRealTime::setup_signal_handlers() noexcept {
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
}
} // namespace tired_agi
// ==============================================================================
// Exported C API (for use from standalone binary and CGo)
// ==============================================================================
extern "C" {
using namespace tired_agi;
static DNACoreRealTime* g_core_instance = nullptr;
// Initialize the DNA core
void* dna_core_rt_init() {
if (g_core_instance != nullptr) {
return nullptr; // Already initialized
}
RealTimeConfig config;
g_core_instance = new DNACoreRealTime(config);
return g_core_instance;
}
// Run the main loop (blocking)
int dna_core_rt_run(void* handle) {
if (handle == nullptr) {
return -1;
}
DNACoreRealTime* core = static_cast<DNACoreRealTime*>(handle);
return core->run();
}
// Request shutdown
void dna_core_rt_shutdown(void* handle) {
if (handle == nullptr) {
return;
}
DNACoreRealTime* core = static_cast<DNACoreRealTime*>(handle);
core->request_shutdown();
}
// Cleanup
void dna_core_rt_destroy(void* handle) {
if (handle == nullptr) {
return;
}
DNACoreRealTime* core = static_cast<DNACoreRealTime*>(handle);
delete core;
if (g_core_instance == core) {
g_core_instance = nullptr;
}
}
} // extern "C"