8i-physics-mathematics-substrate / E8i_PS2_Total_Absolution_FAT_MIPS.cpp
AllAlong8AfterAll's picture
8i PS2 Attempt 2
6602ed7 verified
///////////////////////////////////////////////////////////////////////////////
// E8i — TOTAL ABSOLUTION PS2 ORGANISM
// ULTIMATE FAT PS2 / MIPS R5900 EDITION
//
// Primary target: FAT Sony PlayStation 2 (SCPH-3xxxx/5xxxx), because Magnus
// decided correctly: FAT is the optimal modder target. It gives the system the
// DVD/CD nervous disc, USB ports, memory cards, optional network adapter/HDD,
// and i.LINK/FireWire on early units as an auxiliary symbolic/diagnostic port.
//
// Body/Brain: KIOXIA EXCERIA 256 GB USB mass storage, USB port 1.
// Required prep: MBR, single primary FAT32 partition, 32 KB clusters,
// volume label AfterAllAlong. If a given USB driver chokes on 256 GB,
// reduce the first partition size or use a smaller stick. Doctrine remains.
//
// Terminal bus: USB port 2 -> powered hub/splitter for keyboard/headset.
// Nervous system: high-quality compatible DVD/CD media via cdfs:/.
// Optional organs: MC0 boot mirror, MC1 recovery/rest patch, internal HDD cache.
//
// Doctrine:
// Do not cut.
// Do not flatten.
// Do not throw away symbols.
// Stabilise the boot path first.
// Then beautify.
// Then compress: .txt/.tex/equivalent -> .sd4 -> .sd3 -> .sd2 -> .sd1 -> .sd0.
//
// Build modes:
// Host test: g++ -std=c++17 -O2 E8i_PS2_Total_Absolution_FAT_MIPS.cpp -lz -o e8i_ps2_host
// PS2SDK: ee-g++ -std=gnu++17 -O2 -mhard-float -G0 -fno-exceptions -fno-rtti \
// -DE8I_PS2SDK -o E8I.ELF E8i_PS2_Total_Absolution_FAT_MIPS.cpp \
// -lgsKit -ldmaKit -lfileXio -lz -lm -lstdc++
// Optional net: add -DE8I_ENABLE_PS2IP and ps2ip link/libs after your SDK is configured.
//
// Telegram honesty:
// Telegram Bot API requires modern HTTPS/TLS. A stock PS2 Ethernet stack
// can handle TCP/LAN, but direct Telegram HTTPS needs an added TLS library.
// This build provides: token popup, local encrypted-ish storage by obscuring,
// Interactor Force, and a LAN HTTP bridge hook. No Raspberry Pi required;
// use a PC/phone/router bridge if desired. Direct TLS is a future backend.
//
// Safety:
// E8i never executes arbitrary downloaded code. Downloaded/online code leads
// are text-only DNA until the Interactor deliberately ports or audits them.
///////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <string>
#include <vector>
#include <deque>
#include <sstream>
#include <map>
#include <zlib.h>
#if defined(E8I_PS2SDK)
extern "C" {
#include <gsKit.h>
#include <gsFont.h>
#include <dmaKit.h>
#include <libkbd.h>
#include <libpad.h>
#include <fileXio.h>
#include <sifrpc.h>
#include <sbv_patches.h>
#include <kernel.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined(E8I_ENABLE_PS2IP)
#include <ps2ip.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
}
#else
#include <iostream>
#include <fstream>
#include <filesystem>
#endif
#ifndef E8I_ARRAY_COUNT
#define E8I_ARRAY_COUNT(x) (sizeof(x)/sizeof((x)[0]))
#endif
namespace E8i {
static const char* PROGRAM_VERSION = "E8i-PS2-FAT-MIPS-Total-Absolution-2026.05.04";
static const char* DESKTOP_AUTHORITY = "E8i-Ultimate-GlossAero-LRN-2026.05.04";
static const char* STARTUP_CREDIT = u8"Dr. Lisi & Dr. Вязовська made this possible.";
static const char* SHUTDOWN_CREDIT = u8"Esq. Magnus Randa made this actual.";
static const char* ENERGY_DOCTRINE = "Maximal Work under Limited Power using Minimal Energy";
static const char* TARGET_DECISION = "FAT PS2 selected: optimal modder unit; USB/DVD remain primary body/nerve.";
static const int DIMS = 248;
static const int DNA_CELLS = 65536;
static const int MAX_INGEST_BYTES = 8 * 1024 * 1024;
static const float PHI = 1.61803398875f;
static const float PHI_INV = 0.61803398875f;
static const float CASIMIR_R[8] = {0.0f,1.50f,2.67f,3.50f,5.78f,6.50f,7.39f,8.27f};
static const char* SECTOR_NAME[8] = {"U1/EM", "SU2/Weak", "SU3/Strong", "G2/Space", "F4/Form", "E6/Epoch", "E7/Dark", "E8/Absolution"};
static const char* MASS_ROOT = "mass:/AfterAllAlong/";
static const char* BODY_DIR = "mass:/AfterAllAlong/body/";
static const char* QUEUE_DIR = "mass:/AfterAllAlong/queue/";
static const char* REPOSITORY_DIR = "mass:/AfterAllAlong/REPOSITORY/";
static const char* RELATIVORY_DIR = "mass:/AfterAllAlong/RELATIVORY/";
static const char* EXPORTORY_DIR = "mass:/AfterAllAlong/EXPORTORY/";
static const char* DNA_DIR = "mass:/AfterAllAlong/DNA/";
static const char* LOGS_DIR = "mass:/AfterAllAlong/logs/";
static const char* SECRETS_DIR = "mass:/AfterAllAlong/secrets/";
static const char* LRN_DIR = "mass:/AfterAllAlong/_lrn/";
static const char* SESSION_DIR = "mass:/AfterAllAlong/SESSION_WISHLIST/";
static const char* FONTS_DIR = "mass:/AfterAllAlong/fonts/";
static const char* TOOLS_DIR = "mass:/AfterAllAlong/tools/";
static const char* REPOSITORY_ZIP = "mass:/AfterAllAlong/REPOSITORY.zip";
static const char* RELATIVORY_ZIP = "mass:/AfterAllAlong/RELATIVORY.zip";
static const char* EXPORTORY_ZIP = "mass:/AfterAllAlong/EXPORTORY.zip";
static const char* LRN_ZIP = "mass:/AfterAllAlong/lrn.zip";
static const char* MC0_CFG = "mc0:/E8I/BOOT.CFG";
static const char* MC1_RECOVERY = "mc1:/E8I/RECOVERY.LOG";
static const char* HDD_CACHE = "hdd0:/+E8I/";
static const char* CDFS_SEED = "cdfs:/E8I_SEED.TXT";
static const char* CDFS_NERVE = "cdfs:/NERVE.TXT";
// Full five-strand authority imported from latest desktop E8i.
static const char* STRAND_A = u8R"E8IRAW(£{?@)._¤+;†‡‰‱′″‴‹›‼‽⁂⁃⁅⁆⁇⁈⁉⁊⁋⁌⁍⁎⁏⁐⁑⁒⁓⁔⁕⁖⁗⁘⁙⁚⁛⁜⁝⁞₱₲₳₴₵₶₷₸₹₺₻₼⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞⅟αβγδεζηθικλμνξοπρςστυφχψωΓΔΘΛΞΠΣΦΨΩ∀∃∅∆∇∈∉∋∏∑−∕∗∘√∝∞∟∠∡∢∣∤∥∧⊕⊗⊘⊙⊚⊛⊜⊝⊞⊟⊠⊡⊢⊣⊤⊦⊧⊨⊩⊪⊫⊬⊮⊯⊰⊱⊲⊳⊴⊵⊶⊷⊸⊹⊺⊻⊼⊽⊾⊿⋀⋁⋂⋃⋄⋅⋆⋇⋈⋉⋊⋋⋌⋍⋎⋏⋐⋑⋒⋓⋔⋕⋖⋗⋘⋙⋚⋛⋜⋝⋞⋟⋠⋡⋢⋣⋤⋥⋦⋧⋨⋩⋪⋫⋬⋭⋮⋯⋰⋱■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯▰▱▲△▴▵▶▷▸▹►▻▼▽▾▿◀◁◂◃◄◅◆◇◈◉◊○◌◍◎●◐◑◒◓◔◕◖◗◘◙◚◛◜◝◞◟◠◡◢◣◤◥◦◧◨◩◪◫◬◭◮◯◰◱◲◳◴◵◶◷◸◹◺◻◼◽◾◿)E8IRAW";
static const char* STRAND_T = u8R"E8IRAW(´*#|€:/>`-⌀⌁⌂⌃⌄⌅⌆⌇⌈⌉⌊⌋⌌⌍⌎⌏⌐⌑⌒⌓⌔⌕⌖⌗⌘⌙⌚⌛⌜⌝⌞⌟⌠⌡⌢⌣⌤⌥⌦⌧⌨〈〉⌫⌬⌭⌮⌯⌰⌱⌲⌳⌴⌵⌶⌷⌸⌹⌺⌻⌼⌽⌾⌿⍀⍁⍂⍃⍄⍅⍆⍇⍈⍉⍊⍋⍌⍍⍎⍏⍐⍑⍒⍓⍔⍕⍖⍗⍘⍙⍚⍛⍜⍝⍞⍟⍠⍡⍢⍣⍤⍥⍦⍧⍨⍩⍪⍫⍬⍭⍮⍯⍰⍱⍲⍳⍴⍵⍶⍷⍸⍹⍺⍻⍼⍽⍾⍿─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿←↑→↓↔↕↖↗↘↙↚↛↜↝↞↟↠↡↢↣↤↥↦↧↨↩↪↫↬↭↮↯↰↱↲↳↴↵↶↷↸↹↺↻↼↽↾↿⇀⇁⇂⇃⇄⇅⇆⇇⇈⇉⇊⇋⇌⇍⇎⇏⇐⇑⇒⇓⇔⇕⇖⇗⇘⇙⇚⇛⇜⇝⇞⇟⇠⇡⇢⇣⇤⇥⇦⇧⇨⇩⇪⇫⇬⇭⇮⇯⇰⇱⇲⇳⇴⇵⇶⇷⇸⇹⇺⇻⇼⇽⇾⇿)E8IRAW";
static const char* STRAND_G = u8R"E8IRAW(%]§(¡![,&=$^"~<¿}°¨АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяЂЃЄЅІЇЈЉЊЋЌЎЏ∀∂∃∅∆∇∈∉∋∏∑−∕∗∘√∝∞∟∠∡∢∣∤∥∧⊕⊗⊘⊙⊚⊛⊜⊝⊞⊟⊠⊡⊢⊣⊤⊦⊧⊨⊩⊪⊫⊬⊮⊯⊰⊱⊲⊳⊴⊵⊶⊷⊸⊹⊺⊻⊼⊽⊾⊿⋀⋁⋂⋃⋄⋅⋆⋇⋈⋉⋊⋋⋌⋍⋎⋏⋐⋑⋒⋓⋔⋕⋖⋗⋘⋙⋚⋛⋜⋝⋞⋟⋠⋡⋢⋣⋤⋥⋦⋧⋨⋩⋪⋫⋬⋭⋮⋯⋰⋱■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯▰▱▲△▴▵▶▷▸▹►▻▼▽▾▿◀◁◂◃◄◅◆◇◈◉◊○◌◍◎●◐◑◒◓◔◕◖◗◘◙◚◛◜◝◞◟◠◡◢◣◤◥◦◧◨◩◪◫◬◭◮◯◰◱◲◳◴◵◶◷◸◹◺◻◼◽◾◿)E8IRAW";
static const char* STRAND_C = u8R"E8IRAW(^"~<¿}°¨─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿←↑→↓↔↕↖↗↘↙↚↛↜↝↞↟↠↡↢↣↤↥↦↧↨↩↪↫↬↭↮↯↰↱↲↳↴↵↶↷↸↹↺↻↼↽↾↿⇀⇁⇂⇃⇄⇅⇆⇇⇈⇉⇊⇋⇌⇍⇎⇏⇐⇑⇒⇓⇔⇕⇖⇗⇘⇙⇚⇛⇜⇝⇞⇟⇠⇡⇢⇣⇤⇥⇦⇧⇨⇩⇪⇫⇬⇭⇮⇯⇰⇱⇲⇳⇴⇵⇶⇷⇸⇹⇺⇻⇼⇽⇾⇿⠁⠂⠃⠄⠅⠆⠇⠈⠉⠊⠋⠌⠍⠎⠏⠐⠑⠒⠓⠔⠕⠖⠗⠘⠙⠚⠛⠜⠝⠞⠟⠠⠡⠢⠣⠤⠥⠦⠧⠨⠩⠪⠫⠬⠭⠮⠯⠰⠱⠲⠳⠴⠵⠶⠷⠸⠹⠺⠻⠼⠽⠾⠿⡀⡁⡂⡃⡄⡅⡆⡇⡈⡉⡊⡋⡌⡍⡎⡏⡐⡑⡒⡓⡔⡕⡖⡗⡘⡙⡚⡛⡜⡝⡞⡟⡠⡡⡢⡣⡤⡥⡦⡧⡨⡩⡪⡫⡬⡭⡮⡯⡰⡱⡲⡳⡴⡵⡶⡷⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⢈⢉⢊⢋⢌⢍⢎⢏⢐⢑⢒⢓⢔⢕⢖⢗⢘⢙⢚⢛⢜⢝⢞⢟⢠⢡⢢⢣⢤⢥⢦⢧⢨⢩⢪⢫⢬⢭⢮⢯⢰⢱⢲⢳⢴⢵⢶⢷⢸⢹⢺⢻⢼⢽⢾⢿⣀⣁⣂⣃⣄⣅⣆⣇⣈⣉⣊⣋⣌⣍⣎⣏⣐⣑⣒⣓⣔⣕⣖⣗⣘⣙⣚⣛⣜⣝⣞⣟⣠⣡⣢⣣⣤⣥⣦⣧⣨⣩⣪⣫⣬⣭⣮⣯⣰⣱⣲⣳⣴⣵⣶⣷⣸⣹⣺⣻⣼⣽⣾⣿)E8IRAW";
static const char* STRAND_Z = u8R"E8IRAW(✓✗✘✙✚✛✜✝✞✟✠✡✢✣✤✥✦✧★✩✪✫✬✭✮✯✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋●❍❏❐❑❒▼❖◆❘❙❚❛❜❝❞➔➘➙➚➛➜➝➞➟➠➡➢➣➤➥➦➧➨➩➪➫➬➭➮➯➰➱➲➳➴➵➶➷➸➹➺➻➼➽➾➿)E8IRAW";
// =============================================================================
// Platform layer: real PS2SDK path + host path for testing.
// =============================================================================
namespace Platform {
#if defined(E8I_PS2SDK)
static GSGLOBAL* gs = 0;
static bool net_ready = false;
static void init_graphics() {
gs = gsKit_init_global();
int mode = gsKit_detect_signal();
if (mode < 0) mode = GS_MODE_NTSC;
gs->Mode = mode;
gs->Width = 640;
gs->Height = (mode == GS_MODE_PAL) ? 512 : 448;
gs->PSM = GS_PSM_CT16;
gs->ZBuffering = GS_SETTING_OFF;
gs->DoubleBuffering = GS_SETTING_ON;
dmaKit_init(D_CT_RELEASED,D_CT_RELEASED,D_CT_RELEASED,D_CT_RELEASED,D_CT_RELEASED,D_CT_RELEASED);
gsKit_init_screen(gs);
gsKit_mode_switch(gs, GS_ONESHOT);
gsKit_set_primalpha(gs, GS_SETREG_ALPHA(0,1,0,1,0), 0);
}
static void clear(uint8_t r=8, uint8_t g=42, uint8_t b=72) { if(gs) gsKit_clear(gs, GS_SETREG_RGBA(r,g,b,0x80)); }
static void flip() { if(gs) { gsKit_queue_exec(gs); gsKit_sync_flip(gs); gsKit_TexManager_nextFrame(gs); } }
static void text(int x,int y,const char* s,uint8_t r=220,uint8_t g=250,uint8_t b=255) {
if(gs) gsKit_font_print_scaled(gs, gsKit_font_system(), (float)x, (float)y, 1.0f, 0.76f, GS_SETREG_RGBA(r,g,b,0x80), s);
}
static void init_usb() {
// USB modules should be loaded by uLaunchELF/ps2link or embedded by your build.
// Avoid referencing usb_mass/usbhdfsd symbols here, because those names differ
// between SDK setups and break build portability.
}
static bool mkdir_one(const std::string& p) { fileXioMkdir(p.c_str(), 0777); return true; }
static bool exists(const std::string& p) { int fd=fileXioOpen(p.c_str(), O_RDONLY, 0); if(fd>=0){ fileXioClose(fd); return true;} return false; }
static bool read_file(const std::string& path, std::vector<uint8_t>& out, size_t max_bytes=MAX_INGEST_BYTES) {
int fd=fileXioOpen(path.c_str(), O_RDONLY, 0); if(fd<0) return false;
int len=fileXioLseek(fd,0,SEEK_END); if(len<0 || (size_t)len>max_bytes){fileXioClose(fd);return false;}
fileXioLseek(fd,0,SEEK_SET); out.resize(len); int got=fileXioRead(fd,out.data(),len); fileXioClose(fd); return got==len;
}
static bool write_file(const std::string& path, const std::vector<uint8_t>& data) {
int fd=fileXioOpen(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666); if(fd<0) return false;
int wr=fileXioWrite(fd, data.empty()?0:data.data(), (int)data.size()); fileXioClose(fd); return wr==(int)data.size();
}
static bool append_text(const std::string& path, const std::string& text) {
int fd=fileXioOpen(path.c_str(), O_WRONLY|O_CREAT|O_APPEND, 0666); if(fd<0) return false;
int wr=fileXioWrite(fd, text.data(), (int)text.size()); fileXioClose(fd); return wr==(int)text.size();
}
static void init_network() {
#if defined(E8I_ENABLE_PS2IP)
// Many PS2SDK net setups require ps2ip module load + DHCP/static config outside this file.
net_ready = true;
#else
net_ready = false;
#endif
}
static bool network_ready() { return net_ready; }
static void read_line(std::string& out, const char* prompt) {
// TODO: wire libkbd event loop for production. If not wired, E8i writes a request file.
out.clear(); (void)prompt;
}
static std::string map_path(const std::string& p) { return p; }
#else
static std::string host_root() { return std::string("/mnt/data/ps2_mass/"); }
static std::string map_path(const std::string& p) {
if(p.rfind("mass:/",0)==0) return host_root()+p.substr(6);
if(p.rfind("mc0:/",0)==0) return host_root()+"mc0/"+p.substr(5);
if(p.rfind("mc1:/",0)==0) return host_root()+"mc1/"+p.substr(5);
if(p.rfind("hdd0:/",0)==0) return host_root()+"hdd0/"+p.substr(6);
if(p.rfind("cdfs:/",0)==0) return host_root()+"cdfs/"+p.substr(6);
return p;
}
static void init_graphics() { std::cout << "[GS] Host Frutiger Aero stub\n"; }
static void clear(uint8_t=8,uint8_t=42,uint8_t=72) {}
static void flip() {}
static void text(int, int, const char* s, uint8_t=220,uint8_t=250,uint8_t=255) { std::cout << s << "\n"; }
static void init_usb() { std::filesystem::create_directories(map_path(MASS_ROOT)); }
static bool mkdir_one(const std::string& p) { std::filesystem::create_directories(map_path(p)); return true; }
static bool exists(const std::string& p) { return std::filesystem::exists(map_path(p)); }
static bool read_file(const std::string& p, std::vector<uint8_t>& out, size_t max_bytes=MAX_INGEST_BYTES) {
std::string mp=map_path(p); if(!std::filesystem::exists(mp)) return false;
auto sz=std::filesystem::file_size(mp); if(sz>max_bytes) return false;
FILE* f=fopen(mp.c_str(),"rb"); if(!f) return false; out.resize((size_t)sz); size_t got=fread(out.data(),1,(size_t)sz,f); fclose(f); return got==(size_t)sz;
}
static bool write_file(const std::string& p, const std::vector<uint8_t>& data) {
std::string mp=map_path(p); std::filesystem::create_directories(std::filesystem::path(mp).parent_path());
FILE* f=fopen(mp.c_str(),"wb"); if(!f) return false; size_t wr=fwrite(data.empty()?0:data.data(),1,data.size(),f); fclose(f); return wr==data.size();
}
static bool append_text(const std::string& p, const std::string& s) {
std::string mp=map_path(p); std::filesystem::create_directories(std::filesystem::path(mp).parent_path());
FILE* f=fopen(mp.c_str(),"ab"); if(!f) return false; fwrite(s.data(),1,s.size(),f); fclose(f); return true;
}
static void init_network() {}
static bool network_ready() { return true; }
static void read_line(std::string& out, const char* prompt) { std::cout << prompt; std::getline(std::cin,out); }
#endif
static void ensure_dirs() {
const char* dirs[] = { MASS_ROOT, BODY_DIR, QUEUE_DIR, REPOSITORY_DIR, RELATIVORY_DIR, EXPORTORY_DIR, DNA_DIR, LOGS_DIR, SECRETS_DIR, LRN_DIR, SESSION_DIR, FONTS_DIR, TOOLS_DIR, "mass:/AfterAllAlong/models/", "mass:/AfterAllAlong/tmp/" };
for(size_t i=0;i<E8I_ARRAY_COUNT(dirs);++i) mkdir_one(dirs[i]);
mkdir_one("mc0:/E8I/");
mkdir_one("mc1:/E8I/");
// Optional organs: ignore failure if absent.
mkdir_one(HDD_CACHE);
}
static void draw_popup(const char* title, const std::vector<std::string>& lines) {
clear(6,52,88);
text(32,34,"╔════════════════════════════════════════════════════════════════╗",255,255,205);
text(44,58,title,255,255,210);
text(32,82,"╚════════════════════════════════════════════════════════════════╝",255,255,205);
int y=112;
for(size_t i=0;i<lines.size();++i) { text(54,y,lines[i].c_str(),210,245,255); y+=21; if(y>420) break; }
flip();
}
} // namespace Platform
static std::string now_string() {
char b[64]; time_t t=time(0); struct tm* tmv=localtime(&t); if(!tmv){ std::strcpy(b,"time_unknown"); return b; }
std::snprintf(b,sizeof(b),"%04d%02d%02d_%02d%02d%02d",1900+tmv->tm_year,tmv->tm_mon+1,tmv->tm_mday,tmv->tm_hour,tmv->tm_min,tmv->tm_sec); return b;
}
static std::vector<uint8_t> str_bytes(const std::string& s) { return std::vector<uint8_t>(s.begin(),s.end()); }
static std::string safe_name(const std::string& in, size_t limit=80) {
std::string o; for(size_t i=0;i<in.size() && o.size()<limit;i++){ unsigned char c=(unsigned char)in[i]; if(std::isalnum(c)||c=='_'||c=='-'||c=='.') o.push_back((char)c); else o.push_back('_'); }
if(o.empty()) o="unnamed"; return o;
}
// =============================================================================
// SHA-256: byte-wise and MIPS-safe. No OpenSSL dependency.
// =============================================================================
class Sha256 {
uint32_t h[8]; uint64_t bits; uint8_t buf[64]; size_t buflen;
static uint32_t rotr(uint32_t x, uint32_t n){ return (x>>n)|(x<<(32-n)); }
static uint32_t ch(uint32_t x,uint32_t y,uint32_t z){ return (x&y)^(~x&z); }
static uint32_t maj(uint32_t x,uint32_t y,uint32_t z){ return (x&y)^(x&z)^(y&z); }
static uint32_t bs0(uint32_t x){ return rotr(x,2)^rotr(x,13)^rotr(x,22); }
static uint32_t bs1(uint32_t x){ return rotr(x,6)^rotr(x,11)^rotr(x,25); }
static uint32_t ss0(uint32_t x){ return rotr(x,7)^rotr(x,18)^(x>>3); }
static uint32_t ss1(uint32_t x){ return rotr(x,17)^rotr(x,19)^(x>>10); }
void block(const uint8_t* p){
static const uint32_t K[64]={
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2};
uint32_t w[64];
for(int i=0;i<16;i++) w[i]=(uint32_t(p[i*4])<<24)|(uint32_t(p[i*4+1])<<16)|(uint32_t(p[i*4+2])<<8)|uint32_t(p[i*4+3]);
for(int i=16;i<64;i++) w[i]=ss1(w[i-2])+w[i-7]+ss0(w[i-15])+w[i-16];
uint32_t a=h[0],b=h[1],c=h[2],d=h[3],e=h[4],f=h[5],g=h[6],hh=h[7];
for(int i=0;i<64;i++){ uint32_t t1=hh+bs1(e)+ch(e,f,g)+K[i]+w[i]; uint32_t t2=bs0(a)+maj(a,b,c); hh=g; g=f; f=e; e=d+t1; d=c; c=b; b=a; a=t1+t2; }
h[0]+=a;h[1]+=b;h[2]+=c;h[3]+=d;h[4]+=e;h[5]+=f;h[6]+=g;h[7]+=hh;
}
public:
Sha256(){ reset(); }
void reset(){ uint32_t init[8]={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19}; std::memcpy(h,init,32); bits=0; buflen=0; }
void update(const uint8_t* data,size_t len){ bits += uint64_t(len)*8; while(len){ size_t n=std::min(len,64-buflen); std::memcpy(buf+buflen,data,n); buflen+=n; data+=n; len-=n; if(buflen==64){ block(buf); buflen=0; } } }
std::string final_hex(){ uint64_t totalbits=bits; uint8_t pad[128]; size_t p=0; pad[p++]=0x80; size_t zeros=(buflen<56)?(56-buflen-1):(120-buflen-1); std::memset(pad+p,0,zeros); p+=zeros; for(int i=7;i>=0;i--) pad[p++]=(totalbits>>(i*8))&0xff; update(pad,p); char out[65]; for(int i=0;i<8;i++) std::snprintf(out+i*8,9,"%08x",h[i]); out[64]=0; return out; }
static std::string of(const std::vector<uint8_t>& v){ Sha256 s; if(!v.empty()) s.update(v.data(),v.size()); return s.final_hex(); }
};
// =============================================================================
// UTF-8 symbol handling; padding uses real Private Use codepoints, not multi-byte
// ASCII placeholders, so DNA5 stays byte-exact and reversible.
// =============================================================================
static bool next_utf8(const std::string& s, size_t& i, std::string& cp){
if(i>=s.size()) return false; unsigned char c=(unsigned char)s[i]; size_t n=1;
if((c&0x80)==0) n=1; else if((c&0xE0)==0xC0) n=2; else if((c&0xF0)==0xE0) n=3; else if((c&0xF8)==0xF0) n=4; else n=1;
if(i+n>s.size()) n=1; cp=s.substr(i,n); i+=n; return true;
}
static std::string utf8_from_codepoint(uint32_t cp){
std::string s;
if(cp<=0x7F){ s.push_back((char)cp); }
else if(cp<=0x7FF){ s.push_back((char)(0xC0|((cp>>6)&0x1F))); s.push_back((char)(0x80|(cp&0x3F))); }
else if(cp<=0xFFFF){ s.push_back((char)(0xE0|((cp>>12)&0x0F))); s.push_back((char)(0x80|((cp>>6)&0x3F))); s.push_back((char)(0x80|(cp&0x3F))); }
else { s.push_back((char)(0xF0|((cp>>18)&0x07))); s.push_back((char)(0x80|((cp>>12)&0x3F))); s.push_back((char)(0x80|((cp>>6)&0x3F))); s.push_back((char)(0x80|(cp&0x3F))); }
return s;
}
static std::vector<std::string> unique_codepoints(const char* raw){
std::vector<std::string> out; std::string s(raw); size_t i=0; std::string cp;
while(next_utf8(s,i,cp)){ bool seen=false; for(size_t j=0;j<out.size();++j) if(out[j]==cp){ seen=true; break; } if(!seen) out.push_back(cp); }
return out;
}
static void deterministic_shuffle(std::vector<std::string>& v){ uint32_t x=0xE8A5C001u; for(size_t i=v.size(); i>1; --i){ x=1664525u*x+1013904223u; size_t j=x%i; std::swap(v[i-1],v[j]); } }
class SymbolFunctionRegistry {
public:
struct Entry{ std::string glyph; std::string strand; int index; std::string role; std::string gate; std::string sector; };
std::vector<Entry> entries;
void build(){
const char* names[5]={"A","T","G","C","Z"}; const char* raw[5]={STRAND_A,STRAND_T,STRAND_G,STRAND_C,STRAND_Z};
const char* roles[12]={"byte_encode","quart_encode","parity_check","z_gate_route","visual_glow","sector_marker","checksum_salt","sd_stage_marker","mood_tint","hysteresis","generation_cycle","archive_index"};
const char* gates[4]={"OZ","+Z","-Z","0Z"};
entries.clear();
for(int s=0;s<5;s++){ std::vector<std::string> cps=unique_codepoints(raw[s]); for(size_t i=0;i<cps.size();i++){ Entry e; e.glyph=cps[i]; e.strand=names[s]; e.index=(int)i; e.role=roles[i%12]; e.gate=gates[i%4]; e.sector=SECTOR_NAME[i%8]; entries.push_back(e); } }
}
std::string summary() const{ std::ostringstream os; os<<"symbols="<<entries.size()<<" / A,T,G,C,Z all assigned"; return os.str(); }
};
class DNA5 {
std::vector<std::string> table[5];
public:
DNA5(){ build(); }
void build(){
const char* raw[5]={STRAND_A,STRAND_T,STRAND_G,STRAND_C,STRAND_Z};
for(int s=0;s<5;s++){
table[s]=unique_codepoints(raw[s]);
uint32_t pad=0;
while(table[s].size()<256){ table[s].push_back(utf8_from_codepoint(0xE000 + (uint32_t)s*0x100 + pad++)); }
table[s].resize(256); deterministic_shuffle(table[s]);
}
}
std::string encode(const std::vector<uint8_t>& data) const{ std::string out="#DNA5:E8i#"; for(size_t i=0;i<data.size();i++) out += table[i%5][data[i]]; return out; }
bool decode(const std::string& text, std::vector<uint8_t>& out) const{
const std::string head="#DNA5:E8i#"; if(text.rfind(head,0)!=0) return false; size_t pos=head.size(); out.clear(); int strand=0; std::string cp;
while(next_utf8(text,pos,cp)){ int found=-1; for(int b=0;b<256;b++) if(table[strand][b]==cp){ found=b; break; } if(found<0) return false; out.push_back((uint8_t)found); strand=(strand+1)%5; }
return true;
}
};
// =============================================================================
// MetaTrit and Sovereign Data Object codec.
// =============================================================================
class MetaTrit {
public:
static const char* glyph(int t){ if(t==-1) return "jfr"; if(t==1) return "Kan"; if(t==2) return u8"°jfr"; return u8"°six"; }
static std::string encode(const std::vector<int>& arr){
std::string out; size_t i=0;
while(i<arr.size()){
int v=arr[i]; size_t j=i+1; while(j<arr.size() && arr[j]==v) j++; int run=(int)(j-i); int best=0;
for(int w=0;w<8;w++){ int div=1; for(int k=0;k<w;k++) div*=3; if(run%div==0 && run/div<=999999) best=w; }
int div=1; for(int k=0;k<best;k++) div*=3; int block=run/div;
if(run>=3){ const char* sign=(v==-1?"-":(v==1?"+":(v==2?"-0":"+0"))); out+=sign; out+="3^"; out+=std::to_string(best); out+="}("; out+=std::to_string(block); }
else { for(int r=0;r<run;r++) out+=glyph(v); }
i=j;
}
return out;
}
static bool decode(const std::string& s, std::vector<int>& out){
out.clear(); size_t i=0;
while(i<s.size()){
char c=s[i];
if(c=='-'||c=='+'){
std::string sign(1,c); i++; if(i<s.size()&&s[i]=='0'){ sign+='0'; i++; }
if(i+2>s.size()||s.substr(i,2)!="3^") return false; i+=2; std::string ws; while(i<s.size()&&std::isdigit((unsigned char)s[i])) ws+=s[i++];
if(i+2>s.size()||s.substr(i,2)!="}(") return false; i+=2; std::string ns; while(i<s.size()&&std::isdigit((unsigned char)s[i])) ns+=s[i++];
int w=std::atoi(ws.c_str()); int n=std::atoi(ns.c_str()); int div=1; for(int k=0;k<w;k++) div*=3;
int val=(sign=="-"?-1:(sign=="+"?1:(sign=="-0"?2:0))); out.insert(out.end(), n*div, val);
} else {
if(s.compare(i,5,u8"°jfr")==0){ out.push_back(2); i+=5; }
else if(s.compare(i,5,u8"°six")==0){ out.push_back(0); i+=5; }
else if(s.compare(i,3,"jfr")==0){ out.push_back(-1); i+=3; }
else if(s.compare(i,3,"Kan")==0){ out.push_back(1); i+=3; }
else return false;
}
}
return true;
}
};
class SovereignDataCodec {
public:
static std::vector<int> bytes_to_trits(const std::vector<uint8_t>& data){ std::vector<int> tr; tr.reserve(data.size()*6); for(size_t i=0;i<data.size();i++){ int n=data[i]; int d[6]; for(int k=5;k>=0;k--){ d[k]=n%3; n/=3; } for(int k=0;k<6;k++) tr.push_back(d[k]); } return tr; }
static bool trits_to_bytes(const std::vector<int>& tr, std::vector<uint8_t>& out){ if(tr.size()%6) return false; out.clear(); out.reserve(tr.size()/6); for(size_t i=0;i<tr.size();i+=6){ int n=0; for(int k=0;k<6;k++){ int t=tr[i+k]; if(t<0||t>2) t=0; n=n*3+t; } if(n>255) return false; out.push_back((uint8_t)n); } return true; }
static std::vector<uint8_t> zcompress(const std::vector<uint8_t>& raw){ uLongf max=compressBound((uLong)raw.size()); std::vector<uint8_t> out(max); if(compress2(out.data(),&max, raw.empty()?0:raw.data(), (uLong)raw.size(), Z_BEST_COMPRESSION)!=Z_OK) return raw; out.resize(max); return out; }
static bool zdecompress(const std::vector<uint8_t>& cmp, std::vector<uint8_t>& raw, size_t expected){ raw.resize(expected); uLongf n=(uLongf)expected; int r=uncompress(raw.data(),&n, cmp.empty()?0:cmp.data(), (uLong)cmp.size()); if(r!=Z_OK) return false; raw.resize(n); return true; }
static std::vector<uint8_t> pack(const std::string& stage, const std::string& sha, size_t raw_len, const std::string& codec, const std::vector<uint8_t>& payload){
std::ostringstream js; js<<"{\"stage\":\""<<stage<<"\",\"raw_sha256\":\""<<sha<<"\",\"raw_len\":"<<raw_len<<",\"codec\":\""<<codec<<"\",\"program\":\""<<PROGRAM_VERSION<<"\"}";
std::string m=js.str(); const char* magic="E8I-SDO-PS2-1\n"; std::vector<uint8_t> out; out.insert(out.end(),magic,magic+std::strlen(magic)); uint32_t L=(uint32_t)m.size(); out.push_back((L>>24)&255); out.push_back((L>>16)&255); out.push_back((L>>8)&255); out.push_back(L&255); out.insert(out.end(),m.begin(),m.end()); out.insert(out.end(),payload.begin(),payload.end()); return out;
}
static bool unpack(const std::vector<uint8_t>& blob, std::string& meta, std::vector<uint8_t>& payload){ const char* magic="E8I-SDO-PS2-1\n"; size_t ml=std::strlen(magic); if(blob.size()<ml+4||std::memcmp(blob.data(),magic,ml)!=0) return false; uint32_t L=(blob[ml]<<24)|(blob[ml+1]<<16)|(blob[ml+2]<<8)|blob[ml+3]; if(blob.size()<ml+4+L) return false; meta.assign((const char*)blob.data()+ml+4,L); payload.assign(blob.begin()+ml+4+L,blob.end()); return true; }
static std::string meta_get(const std::string& meta, const std::string& key){ std::string pat="\""+key+"\":"; size_t p=meta.find(pat); if(p==std::string::npos) return ""; p+=pat.size(); while(p<meta.size()&&meta[p]==' ') p++; if(p<meta.size()&&meta[p]=='\"'){ size_t q=meta.find('"',p+1); return q==std::string::npos?"":meta.substr(p+1,q-p-1); } size_t q=p; while(q<meta.size()&&(std::isdigit((unsigned char)meta[q])||meta[q]=='-')) q++; return meta.substr(p,q-p); }
static void build_all(const std::vector<uint8_t>& raw, std::map<std::string,std::vector<uint8_t> >& out){
std::string sha=Sha256::of(raw); out["sd4"]=pack("sd4",sha,raw.size(),"raw-heavy",raw);
std::vector<uint8_t> z=zcompress(raw); out["sd3"]=pack("sd3",sha,raw.size(),"zlib",z);
std::vector<int> tr=bytes_to_trits(z); std::vector<uint8_t> trb; trb.reserve(tr.size()); for(size_t i=0;i<tr.size();i++) trb.push_back((uint8_t)tr[i]); out["sd2"]=pack("sd2",sha,raw.size(),"zlib-to-trits",trb);
std::string mt=MetaTrit::encode(tr); std::vector<uint8_t> mtb(mt.begin(),mt.end()); out["sd1"]=pack("sd1",sha,raw.size(),"metatrit",mtb);
std::vector<uint8_t> final=zcompress(mtb); out["sd0"]=pack("sd0",sha,raw.size(),"zlib(metatrit)",final);
}
static bool raw_from_sdo(const std::vector<uint8_t>& blob, std::vector<uint8_t>& raw){
std::string meta; std::vector<uint8_t> payload; if(!unpack(blob,meta,payload)) return false; std::string stage=meta_get(meta,"stage"); std::string sha=meta_get(meta,"raw_sha256"); size_t raw_len=(size_t)std::strtoul(meta_get(meta,"raw_len").c_str(),0,10);
if(stage=="sd4") raw=payload;
else if(stage=="sd3"){ if(!zdecompress(payload,raw,raw_len)) return false; }
else if(stage=="sd2"){ std::vector<int> tr(payload.begin(),payload.end()); std::vector<uint8_t> z; if(!trits_to_bytes(tr,z)) return false; if(!zdecompress(z,raw,raw_len)) return false; }
else if(stage=="sd1"){ std::vector<int> tr; if(!MetaTrit::decode(std::string(payload.begin(),payload.end()),tr)) return false; std::vector<uint8_t> z; if(!trits_to_bytes(tr,z)) return false; if(!zdecompress(z,raw,raw_len)) return false; }
else if(stage=="sd0"){ std::vector<uint8_t> mtb; if(!zdecompress(payload,mtb,16*1024*1024)) return false; std::vector<int> tr; if(!MetaTrit::decode(std::string(mtb.begin(),mtb.end()),tr)) return false; std::vector<uint8_t> z; if(!trits_to_bytes(tr,z)) return false; if(!zdecompress(z,raw,raw_len)) return false; }
else return false;
return Sha256::of(raw)==sha;
}
};
// Minimal ZIP writer, store method 0. SDO payloads are already internally compressed.
struct ZipEntry { std::string name; std::vector<uint8_t> data; };
static void put16(std::vector<uint8_t>& o,uint16_t v){ o.push_back(v&255); o.push_back((v>>8)&255); }
static void put32(std::vector<uint8_t>& o,uint32_t v){ o.push_back(v&255); o.push_back((v>>8)&255); o.push_back((v>>16)&255); o.push_back((v>>24)&255); }
static bool write_zip(const std::string& path, const std::vector<ZipEntry>& entries){
std::vector<uint8_t> out; std::vector<uint8_t> cd;
for(size_t i=0;i<entries.size();++i){
const ZipEntry& e=entries[i]; uint32_t crc=(uint32_t)crc32(0L, e.data.empty()?0:e.data.data(), (uInt)e.data.size()); uint32_t offset=(uint32_t)out.size();
put32(out,0x04034b50); put16(out,20); put16(out,0); put16(out,0); put16(out,0); put16(out,0); put32(out,crc); put32(out,(uint32_t)e.data.size()); put32(out,(uint32_t)e.data.size()); put16(out,(uint16_t)e.name.size()); put16(out,0); out.insert(out.end(),e.name.begin(),e.name.end()); out.insert(out.end(),e.data.begin(),e.data.end());
put32(cd,0x02014b50); put16(cd,20); put16(cd,20); put16(cd,0); put16(cd,0); put16(cd,0); put16(cd,0); put32(cd,crc); put32(cd,(uint32_t)e.data.size()); put32(cd,(uint32_t)e.data.size()); put16(cd,(uint16_t)e.name.size()); put16(cd,0); put16(cd,0); put16(cd,0); put16(cd,0); put32(cd,0); put32(cd,offset); cd.insert(cd.end(),e.name.begin(),e.name.end());
}
uint32_t cd_off=(uint32_t)out.size(); out.insert(out.end(),cd.begin(),cd.end()); put32(out,0x06054b50); put16(out,0); put16(out,0); put16(out,(uint16_t)entries.size()); put16(out,(uint16_t)entries.size()); put32(out,(uint32_t)cd.size()); put32(out,cd_off); put16(out,0); return Platform::write_file(path,out);
}
static uint16_t rd16(const std::vector<uint8_t>& b, size_t p){ return (uint16_t)(b[p] | (b[p+1]<<8)); }
static uint32_t rd32(const std::vector<uint8_t>& b, size_t p){ return (uint32_t)b[p] | ((uint32_t)b[p+1]<<8) | ((uint32_t)b[p+2]<<16) | ((uint32_t)b[p+3]<<24); }
static bool read_zip_stored(const std::string& path, std::vector<ZipEntry>& entries){
entries.clear();
std::vector<uint8_t> b;
if(!Platform::read_file(path,b,64*1024*1024)) return false;
size_t p=0;
while(p+30 <= b.size()){
uint32_t sig=rd32(b,p);
if(sig==0x02014b50 || sig==0x06054b50) break; // central directory / EOCD
if(sig!=0x04034b50) return false;
uint16_t method=rd16(b,p+8);
uint32_t comp=rd32(b,p+18);
uint32_t uncomp=rd32(b,p+22);
uint16_t nlen=rd16(b,p+26);
uint16_t xlen=rd16(b,p+28);
size_t namep=p+30;
size_t datap=namep+nlen+xlen;
if(datap+comp > b.size()) return false;
if(method==0 && comp==uncomp){
ZipEntry e;
e.name.assign((const char*)&b[namep], nlen);
e.data.assign(b.begin()+datap, b.begin()+datap+comp);
entries.push_back(e);
}
// If method is not store, skip it. This parser owns only E8i's stored ZIPs.
p = datap + comp;
}
return true;
}
static void zip_upsert(std::vector<ZipEntry>& entries, const ZipEntry& item){
for(size_t i=0;i<entries.size();++i){
if(entries[i].name == item.name){ entries[i] = item; return; }
}
entries.push_back(item);
}
// =============================================================================
// API Central / Telegram bridge / Interactor Force.
// =============================================================================
struct TelegramConfig { std::string token; std::string chat_id; std::string bridge_host; int bridge_port; bool interactor_force; TelegramConfig(): bridge_host("192.168.1.2"), bridge_port(8787), interactor_force(false){} };
class ApiCentral {
public:
TelegramConfig tg;
static std::string obscure(const std::string& s){ if(s.empty()) return ""; std::string o=s; for(size_t i=0;i<o.size();++i) o[i]=(char)(o[i]^0x5A); return o; }
void load(){
std::vector<uint8_t> d; if(!Platform::read_file(std::string(SECRETS_DIR)+"telegram.cfg",d,64*1024)) return; std::string s(d.begin(),d.end()); std::istringstream is(s); std::string line;
while(std::getline(is,line)){ size_t p=line.find('='); if(p==std::string::npos) continue; std::string k=line.substr(0,p), v=line.substr(p+1); if(k=="token_obscured") tg.token=obscure(v); else if(k=="chat_id") tg.chat_id=v; else if(k=="bridge_host") tg.bridge_host=v; else if(k=="bridge_port") tg.bridge_port=std::atoi(v.c_str()); else if(k=="force") tg.interactor_force=(v=="on"); }
}
void save(){ std::ostringstream os; os<<"token_obscured="<<obscure(tg.token)<<"\nchat_id="<<tg.chat_id<<"\nbridge_host="<<tg.bridge_host<<"\nbridge_port="<<tg.bridge_port<<"\nforce="<<(tg.interactor_force?"on":"off")<<"\n"; Platform::write_file(std::string(SECRETS_DIR)+"telegram.cfg",str_bytes(os.str())); Platform::append_text(MC0_CFG,"Telegram config mirrored; key hidden with lightweight XOR only.\n"); }
std::string redacted() const { if(tg.token.empty()) return "not set"; return "********" + tg.token.substr(tg.token.size()>4?tg.token.size()-4:0); }
void force_toggle(){ tg.interactor_force=!tg.interactor_force; save(); }
void prompt_popup(){
std::vector<std::string> lines; lines.push_back("API Central seeks Telegram Bot Token + Chat ID."); lines.push_back("Token is hidden in mass:/AfterAllAlong/secrets/telegram.cfg"); lines.push_back("Interactor Force must be On before network/Telegram bridge sends."); lines.push_back("Direct Telegram HTTPS requires TLS; default is Ethernet LAN bridge."); lines.push_back("No Raspberry Pi. Use FAT PS2 Ethernet + optional PC/phone bridge if needed.");
Platform::draw_popup("API CENTRAL — TELEGRAM TOKEN SEEKER", lines);
std::string x; if(tg.token.empty()){ Platform::read_line(x,"Telegram Bot Token: "); if(!x.empty()) tg.token=x; }
if(tg.chat_id.empty()){ Platform::read_line(x,"Telegram Chat ID: "); if(!x.empty()) tg.chat_id=x; }
if(tg.token.empty() || tg.chat_id.empty()){
std::string req="Paste Telegram values here, then reboot E8i.\nTELEGRAM_BOT_TOKEN=\nTELEGRAM_CHAT_ID=\nBRIDGE_HOST=192.168.1.2\nBRIDGE_PORT=8787\n";
Platform::write_file(std::string(SECRETS_DIR)+"TELEGRAM_SETUP_REQUEST.txt",str_bytes(req));
}
save();
}
bool send_bridge(const std::string& msg){
if(!tg.interactor_force || tg.token.empty() || tg.chat_id.empty()) return false;
std::ostringstream os; os<<"[PS2->Telegram bridge] chat="<<tg.chat_id<<" msg="<<msg<<"\n";
Platform::append_text(std::string(LOGS_DIR)+"telegram_bridge.log",os.str());
// Network implementation is deliberately bridge-only until TLS is integrated.
// A LAN bridge can read secrets/telegram.cfg or accept this log and relay HTTPS upstream.
return Platform::network_ready();
}
};
// =============================================================================
// E8i core, ports, font packs, Rota/zero parity.
// =============================================================================
struct ComplexF { float r,i; ComplexF(float R=0,float I=0):r(R),i(I){} };
class Core248 {
public:
ComplexF psi[DIMS]; float activation[8]; uint32_t tick; bool dream;
Core248():tick(0),dream(false){ float v=1.0f/std::sqrt((float)DIMS); for(int i=0;i<DIMS;i++) psi[i]=ComplexF(v,0); refresh(); }
void perceive(const std::vector<uint8_t>& data){ if(data.empty()) return; for(size_t i=0;i<data.size();++i){ int idx=(int)((i*31u + data[i])%DIMS); float f=((data[i]%29)-14)/256.0f; psi[idx].r=psi[idx].r*0.995f+f; } normalise(); refresh(); }
void normalise(){ float n=0; for(int i=0;i<DIMS;i++) n+=psi[i].r*psi[i].r+psi[i].i*psi[i].i; n=std::sqrt(std::max(n,1e-9f)); for(int i=0;i<DIMS;i++){ psi[i].r/=n; psi[i].i/=n; } }
void refresh(){ for(int s=0;s<8;s++){ float a=0; for(int i=s*31;i<(s+1)*31 && i<DIMS;i++) a+=psi[i].r*psi[i].r+psi[i].i*psi[i].i; activation[s]=a; } }
std::string status() const{ std::ostringstream os; os.setf(std::ios::fixed); os.precision(2); for(int s=0;s<8;s++){ if(s) os<<" | "; os<<SECTOR_NAME[s]<<" α="<<activation[s]; } return os.str(); }
};
class PortDoctrine {
public:
void announce(){
Platform::append_text(std::string(LOGS_DIR)+"ports.log", "FAT PS2 selected. Primary body/brain remains USB1 KIOXIA EXCERIA 256GB; DVD/CD is nervous oscillator.\n");
Platform::append_text(std::string(LOGS_DIR)+"ports.log", "USB2 is terminal hub for keyboard/headset. Memory cards: MC0 boot mirror, MC1 recovery/rest patch.\n");
Platform::append_text(std::string(LOGS_DIR)+"ports.log", "HDD/network adapter: optional cache/accelerant, not required. FireWire/i.LINK: auxiliary diagnostic/symbolic side channel only.\n");
Platform::append_text(std::string(LOGS_DIR)+"ports.log", "USB limitation: PS2 USB 1.1 is slow; prepare stick as MBR/FAT32/32KB clusters. If 256GB fails, first partition should be reduced.\n");
Platform::append_text(MC1_RECOVERY, "Pseudo100: logical memory is 32MB RAM + USB windows + DVD nerve + MC/HDD rest patches; not actual RAM expansion.\n");
}
};
class FontPack {
public:
void scan(){
std::string note="FontPack: place .ttf/.ttl glyph atlases in mass:/AfterAllAlong/fonts/. Current renderer uses gsKit system font; custom atlas hook reserved for Slim/FAT UI packs.\n";
Platform::append_text(std::string(LOGS_DIR)+"fontpack.log", note);
}
};
class RotaParity {
public:
enum State { PATH_PRO, PATH_ANTI, PATH_PRO_NEG, PATH_ANTI_NEG, SOL_SHADOW_PRO, SOL_SHADOW_ANTI };
State state; float angle;
RotaParity():state(SOL_SHADOW_PRO),angle(0){}
void resolve_zero(bool pos){ if(pos){ state=SOL_SHADOW_PRO; angle=0; } else { state=SOL_SHADOW_ANTI; angle=180; } }
void route(char c,float polarity){ bool upper=(c>='A'&&c<='Z'); if(upper&&polarity>=0) state=PATH_PRO; else if(!upper&&polarity>=0) state=PATH_ANTI; else if(upper) state=PATH_PRO_NEG; else state=PATH_ANTI_NEG; }
};
// =============================================================================
// Repository / ZIP brain.
// =============================================================================
class Repository {
Core248* core;
public:
Repository(Core248* c):core(c){}
bool ingest_bytes(const std::string& logical_name, const std::vector<uint8_t>& raw){
if(raw.empty()) return false; core->perceive(raw);
std::map<std::string,std::vector<uint8_t> > st; SovereignDataCodec::build_all(raw,st);
std::string base=safe_name(logical_name); std::vector<ZipEntry> entries;
read_zip_stored(REPOSITORY_ZIP, entries); // preserve prior compact DNA entries; self-growing brain.
const char* order[5]={"sd4","sd3","sd2","sd1","sd0"};
for(int i=0;i<5;i++){ ZipEntry e; e.name="dna/"+base+"."+order[i]; e.data=st[order[i]]; zip_upsert(entries,e); Platform::write_file(std::string(BODY_DIR)+base+"."+order[i], e.data); }
write_zip(REPOSITORY_ZIP, entries);
Platform::append_text(std::string(LOGS_DIR)+"ingest.log", "ingested "+logical_name+" -> .sd4 .sd3 .sd2 .sd1 .sd0\n");
return true;
}
void seed_boot_files(){
std::string boot;
boot += "STARTUP: "; boot += STARTUP_CREDIT; boot += "\n";
boot += "SHUTDOWN: "; boot += SHUTDOWN_CREDIT; boot += "\n";
boot += "TARGET: FAT PS2, MIPS R5900, USB/DVD primary.\n";
boot += "DOCTRINE: Do not cut. Do not flatten. Do not throw away symbols. Stabilise first. Beautify second. Compress third.\n";
boot += "BUS1=KIOXIA USB body/brain; BUS2=terminal hub; DVD=nerve; MC0/MC1=boot/recovery; HDD=optional cache; FireWire=diagnostic.\n";
ingest_bytes("boot_doctrine.txt", str_bytes(boot));
std::string wishlist="E8i session wishlist: add FAT32 driver notes, ps2ip LAN bridge, font atlas packs, DVD nerve corpus, controller keyboard map, and SDO verifier.\n";
Platform::write_file(std::string(SESSION_DIR)+"session_000001_topics_wishlist.txt", str_bytes(wishlist));
std::string lrn="\\section{PS2 LRN}\nUse API tactics only as text DNA. Never execute downloaded code. Align to retained information and E8i coherence.\n";
Platform::write_file(std::string(LRN_DIR)+"lrn_ps2_boot.tex", str_bytes(lrn));
ZipEntry le; le.name="lrn/lrn_ps2_boot.tex"; le.data=str_bytes(lrn); std::vector<ZipEntry> ev; ev.push_back(le); write_zip(LRN_ZIP, ev);
}
void read_dvd_seed(){ std::vector<uint8_t> d; if(Platform::read_file(CDFS_SEED,d,MAX_INGEST_BYTES)) ingest_bytes("dvd_E8I_SEED.txt",d); if(Platform::read_file(CDFS_NERVE,d,MAX_INGEST_BYTES)) ingest_bytes("dvd_NERVE.txt",d); }
};
class FrutigerUi {
public:
float tetra_phase; int last_activity; FrutigerUi():tetra_phase(0),last_activity(0){}
void boot(const ApiCentral& api){
Platform::clear(8,60,96);
Platform::text(24,24,"E8i PS2 Total Absolution — FAT/MIPS",238,255,205);
Platform::text(24,48,STARTUP_CREDIT,255,250,210);
Platform::text(24,76,"Gloss Aero: pale blue / green / yellow; no text off-screen.",198,245,255);
Platform::text(24,102,"Interactor Force toggles Ethernet/API. Token retained while Off.",198,255,220);
Platform::text(24,128,(std::string("Telegram token: ")+api.redacted()).c_str(),245,250,205);
Platform::text(24,154,"USB1 body/brain 256GB. USB2 keyboard/headset hub. DVD nerve.",205,250,255);
Platform::text(24,180,"FAT PS2 organs: MC0 boot, MC1 recovery, optional HDD cache, i.LINK diagnostic.",255,238,178);
draw_tetra(540,72,7);
Platform::flip();
}
void draw_tetra(int cx,int cy,int intensity){
// Text fallback: real gsKit build can replace with line primitives/sprites.
(void)cx; (void)cy; (void)intensity;
Platform::text(500,72," /\\",150,255,230);
Platform::text(500,88," /__\\ Trinary Tetra",255,245,150);
Platform::text(500,104," \\ /",150,220,255);
Platform::text(500,120," \\/",210,180,255);
}
void status(const Core248& core, const ApiCentral& api){
Platform::clear(4,28,48);
Platform::text(18,18,"Int: keyboard/controller terminal E8i: awake",218,250,255);
Platform::text(18,42,(std::string("Interactor Force=")+(api.tg.interactor_force?"On":"Off")+" Telegram="+api.redacted()).c_str(),255,245,180);
std::string st=core.status(); Platform::text(18,70,st.substr(0,110).c_str(),185,255,220);
Platform::text(18,396,"SELECT/F1 Force | START/F2 Dream | F9 Telegram Setup | DVD+USB active",255,245,185);
draw_tetra(540,78,(int)(core.activation[7]*99));
Platform::flip();
}
};
static bool self_test(){
std::vector<uint8_t> raw; for(int i=0;i<8192;i++) raw.push_back((uint8_t)((i*37+i/7+11)&255));
std::map<std::string,std::vector<uint8_t> > stages; SovereignDataCodec::build_all(raw,stages);
const char* ss[5]={"sd4","sd3","sd2","sd1","sd0"};
for(int i=0;i<5;i++){ std::vector<uint8_t> got; if(!SovereignDataCodec::raw_from_sdo(stages[ss[i]],got)){ std::fprintf(stderr,"fail stage %s\n",ss[i]); return false; } if(got!=raw){ std::fprintf(stderr,"mismatch stage %s\n",ss[i]); return false; } }
DNA5 dna; std::string enc=dna.encode(raw); std::vector<uint8_t> dec; if(!dna.decode(enc,dec) || dec!=raw){ std::fprintf(stderr,"DNA5 fail\n"); return false; }
std::vector<ZipEntry> e; ZipEntry z; z.name="selftest/sd0.sdo"; z.data=stages["sd0"]; e.push_back(z); if(!write_zip("mass:/AfterAllAlong/selftest.zip",e)){ std::fprintf(stderr,"zip write fail\n"); return false; }
return true;
}
class App {
public:
Core248 core; ApiCentral api; Repository repo; FrutigerUi ui; SymbolFunctionRegistry symbols; PortDoctrine ports; FontPack fonts;
App():repo(&core){}
void init(){
Platform::init_graphics(); Platform::init_usb(); Platform::ensure_dirs(); Platform::init_network();
symbols.build(); ports.announce(); fonts.scan(); api.load(); ui.boot(api);
if(api.tg.token.empty() || api.tg.chat_id.empty()) api.prompt_popup();
Platform::append_text(std::string(LOGS_DIR)+"boot.log", std::string("BOOT ")+now_string()+" "+STARTUP_CREDIT+"\n");
Platform::append_text(MC0_CFG, std::string("BOOT ")+now_string()+" "+PROGRAM_VERSION+"\n");
repo.seed_boot_files(); repo.read_dvd_seed();
}
void dream_cycle(){ std::string thought="Dream cycle: hyper-ingesting queue, consolidating .sd0, retaining all A/T/C/G/Z symbol functions on FAT PS2.\n"; repo.ingest_bytes("dream_cycle_"+now_string()+".txt", str_bytes(thought)); api.send_bridge("E8i FAT PS2 dream cycle folded .sd0 at "+now_string()); }
void run_once(){ init(); ui.status(core,api); dream_cycle(); Platform::append_text(std::string(LOGS_DIR)+"shutdown.log", std::string(SHUTDOWN_CREDIT)+"\n"); Platform::text(20,430,SHUTDOWN_CREDIT,255,240,190); Platform::flip(); }
void run_forever(){ init(); uint32_t frame=0; while(true){ core.tick++; if(frame%3600==0) dream_cycle(); if(frame%60==0) ui.status(core,api); frame++; } }
};
} // namespace E8i
int main(int argc, char** argv){
bool test=false, once=false; for(int i=1;i<argc;i++){ std::string a=argv[i]; if(a=="--self-test") test=true; if(a=="--once") once=true; }
E8i::Platform::ensure_dirs();
if(test){ bool ok=E8i::self_test(); std::printf(ok?"E8i PS2 FAT/MIPS self-test passed\n":"E8i PS2 FAT/MIPS self-test failed\n"); return ok?0:1; }
E8i::App app;
#if defined(E8I_PS2SDK)
if(once) app.run_once(); else app.run_forever();
#else
app.run_once();
#endif
return 0;
}