Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions arkhe-os-genesis-v1.0/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
INFURA_PROJECT_ID=your_infura_project_id
ETHEREUM_NETWORK=mainnet
BASE44_API_KEY=your_base44_api_key

# DoubleZero Configuration
ENABLE_DOUBLEZERO=false
DOUBLEZERO_NETWORK=testnet
35 changes: 35 additions & 0 deletions arkhe-os-genesis-v1.0/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Arkhe OS – Genesis Package v1.0

Este pacote instala o sistema operacional Arkhe em um novo nó, permitindo que ele se conecte à federação de hipergrafos.

## Requisitos
- Linux (kernel 5.4+) com Docker 20.10+ (incluindo plugin docker compose)
- 4 GB RAM, 10 GB de disco
- Para DoubleZero (opcional): IP público sem NAT, suporte a GRE/BGP
- Conexão com internet (para Ethereum e atualizações)

## Instalação
```bash
git clone https://arkhe.io/genesis arkhe-os
cd arkhe-os
cp .env.example .env
# Edite .env com suas credenciais (INFURA, etc.)
chmod +x install.sh
sudo ./install.sh
```

O script irá:
1. Verificar dependências
2. Gerar chaves criptográficas (identidade do nó)
3. Configurar Base44 (entidades, funções, agentes)
4. Implantar contrato Ethereum (se necessário)
5. Configurar DoubleZero (se habilitado no .env)
6. Iniciar serviços (GLP, swarm, handover listener)

## Pós‑instalação
- Acesse o console: `arkhe console`
- Veja o status: `arkhe status`
- Conecte‑se a outros nós: `arkhe handshake --peer <endereço>`

## Documentação completa
Veja a pasta `docs/`.
3 changes: 3 additions & 0 deletions arkhe-os-genesis-v1.0/config/arkhe-core.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Arkhe Core Configuration
loglevel=info
port=8080
71 changes: 71 additions & 0 deletions arkhe-os-genesis-v1.0/config/base44/config.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{
"name": "arkhe-node-NODE_ID_PLACEHOLDER",
"version": "1.0.0",
"geodesic": {
"target": "production",
"stability_threshold": 0.95,
"max_fluctuation": 0.05,
"handover_timeout_ms": 30000
},
"providers": {
"ethereum": {
"rpc": "https://mainnet.infura.io/v3/INFURA_PROJECT_ID_PLACEHOLDER",
"chainId": 1,
"contracts": {
"ArkheLedger": "0x..." // será preenchido após deploy
}
},
"linux": {
"sensors": ["/proc/stat", "/proc/meminfo"]
}
},
"entities": [
{
"name": "NodeState",
"properties": {
"nodeId": { "type": "string", "required": true },
"coherence": { "type": "number" },
"satoshi": { "type": "number" },
"timestamp": { "type": "number" }
}
}
],
"functions": [
{
"name": "updateState",
"entry": "functions/updateState.js",
"trigger": "webhook",
"inputs": { "coherence": "number", "satoshi": "number" },
"outputs": { "status": "string", "tx": "string" }
}
],
"agents": [
{
"name": "StateMonitor",
"description": "Monitora coerência e ajusta parâmetros",
"functions": ["updateState"],
"access": ["entities.NodeState.*"]
}
],
"connectors": [
{
"name": "ethereum",
"type": "ethereum",
"config": {
"network": "mainnet",
"infuraProjectId": "INFURA_PROJECT_ID_PLACEHOLDER"
}
}
],
"automations": [
{
"name": "heartbeat",
"cron": "*/5 * * * *",
"action": "updateState",
"inputs": {
"coherence": "$(curl -s http://localhost:8080/status | jq .coherence)",
"satoshi": "$(curl -s http://localhost:8080/status | jq .satoshi)"
}
}
]
}
9 changes: 9 additions & 0 deletions arkhe-os-genesis-v1.0/config/base44/entities/node_state.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "NodeState",
"properties": {
"nodeId": { "type": "string", "required": true },
"coherence": { "type": "number" },
"satoshi": { "type": "number" },
"timestamp": { "type": "number" }
}
}
14 changes: 14 additions & 0 deletions arkhe-os-genesis-v1.0/config/base44/functions/updateState.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Update the state of the node.
* @param {Object} inputs
* @param {number} inputs.coherence
* @param {number} inputs.satoshi
* @returns {Promise<{status: string, tx: string}>}
*/
module.exports = async function(inputs) {
console.log('Updating node state with coherence:', inputs.coherence, 'and satoshi:', inputs.satoshi);
return {
status: 'success',
tx: '0x' + Math.random().toString(16).slice(2)
};
};
27 changes: 27 additions & 0 deletions arkhe-os-genesis-v1.0/config/ethereum/ArkheLedger.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract ArkheLedger {
struct NodeRecord {
string nodeId;
uint256 coherence; // scaled by 1e18
uint256 satoshi;
uint256 timestamp;
}

mapping(string => NodeRecord[]) public history;

event StateRecorded(string indexed nodeId, uint256 coherence, uint256 satoshi, uint256 timestamp);

function recordState(string memory nodeId, uint256 coherence, uint256 satoshi) public {
NodeRecord memory rec = NodeRecord(nodeId, coherence, satoshi, block.timestamp);
history[nodeId].push(rec);
emit StateRecorded(nodeId, coherence, satoshi, block.timestamp);
}

function getLastState(string memory nodeId) public view returns (uint256 coherence, uint256 satoshi, uint256 timestamp) {
require(history[nodeId].length > 0, "No records");
NodeRecord memory rec = history[nodeId][history[nodeId].length - 1];
return (rec.coherence, rec.satoshi, rec.timestamp);
}
}
27 changes: 27 additions & 0 deletions arkhe-os-genesis-v1.0/config/ethereum/deploy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const { ethers } = require("ethers");
const fs = require("fs");
const path = require("path");

async function main() {
const privateKey = process.argv[2]?.split('=')[1];
if (!privateKey) throw new Error("Forneça --private-key=<chave>");

const provider = new ethers.JsonRpcProvider(process.env.ETHEREUM_RPC || "https://mainnet.infura.io/v3/" + process.env.INFURA_PROJECT_ID);
const wallet = new ethers.Wallet(privateKey, provider);

const contractSource = fs.readFileSync(path.join(__dirname, "ArkheLedger.sol"), "utf8");
// Nota: em produção, usar compilador real (Hardhat). Simulação.
// const factory = new ethers.ContractFactory(contractSource.abi, contractSource.bytecode, wallet);
// const contract = await factory.deploy();
// await contract.waitForDeployment();
const mockAddress = "0x1234567890123456789012345678901234567890";

console.log("Contrato implantado em (MOCK):", mockAddress);
// Atualizar config.jsonc com o endereço
const configPath = path.join(__dirname, "../base44/config.jsonc");
let config = fs.readFileSync(configPath, "utf8");
config = config.replace('"ArkheLedger": "0x..."', `"ArkheLedger": "${mockAddress}"`);
fs.writeFileSync(configPath, config);
}

main().catch(console.error);
5 changes: 5 additions & 0 deletions arkhe-os-genesis-v1.0/config/ethereum/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"dependencies": {
"ethers": "^6.16.0"
}
}
8 changes: 8 additions & 0 deletions arkhe-os-genesis-v1.0/config/glp/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
model:
path: /model/model.pt
input_dim: 128
hidden_dim: 64
meta_neurons: 128
server:
host: 0.0.0.0
port: 5000
Binary file added arkhe-os-genesis-v1.0/config/glp/model.pt
Binary file not shown.
43 changes: 43 additions & 0 deletions arkhe-os-genesis-v1.0/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
services:
arkhe-core:
build: ./src/arkhe_core
container_name: arkhe-core
volumes:
- ./config:/config
- /var/run/docker.sock:/var/run/docker.sock
ports:
- "8080:8080"
environment:
- NODE_ID=${NODE_ID}
- PRIVATE_KEY=${PRIVATE_KEY}
restart: unless-stopped

base44-worker:
image: node:18-alpine
container_name: base44-worker
working_dir: /app
volumes:
- ./src/base44_sdk:/app
- ./config/base44:/config
command: node index.js
depends_on:
- arkhe-core
restart: unless-stopped

glp-server:
build: ./src/glp_interface
container_name: glp-server
ports:
- "5000:5000"
volumes:
- ./config/glp:/model
restart: unless-stopped

swarm-controller:
build: ./src/swarm
container_name: swarm-controller
volumes:
- ./config:/config
environment:
- NODE_ID=${NODE_ID}
restart: unless-stopped
23 changes: 23 additions & 0 deletions arkhe-os-genesis-v1.0/docs/api_reference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# API Reference

## Arkhe Core (porta 8080)
- `GET /status` – retorna estado do nó (id, coherence, satoshi, handovers)
- `POST /handover` – realiza handover para outro nó (body: {to, payload})
- `GET /anticipate` – retorna predição de coerência futura

## GLP Server (porta 5000)
- `GET /status` – retorna camadas integradas e estado de coerência quântica.
- `POST /encode` – processa sequências de signos via arquitetura BCD e MERKABAH-7. (body: {sign_ids: [[...]]})
- `POST /steer` – aplica direção de conceito no manifold latente com auxílio do motor de metáfora.
- `POST /decode_tablet` – realiza decifração neuro-epigráfica com verificação ética. (body: {tablet_id, operator_caste})
- `POST /train_primordial` – executa treinamento GLP sem frameworks (NumPy/explicit gradients).
- `POST /observe_phi` – registra observações de alta coerência na camada Φ.
- `POST /transduce` – realiza transdução S*H*M (Hybrid) para converter estímulos em experiência coerente.
- `POST /kernel_pca` – aplica Kernel PCA sobre estados via Camada Κ. (body: {states, kernel_name})
- `POST /braid` – realiza evolução topológica na Camada Ω. (body: {instruction, sequence})
- `GET /replay` – recupera histórico de estados da memória persistente (Layer M).
- `POST /export_grimoire` – gera relatório PDF da sessão (Grimoire). (body: {session_id})
- `POST /bottlenecks` – analisa gargalos na integração MERKABAH-7.
- `POST /seal` – verifica o fechamento do selo Alpha-Omega.
- `POST /learn` – executa um episódio de Experiential Learning (ERL). (body: {sign_ids: [[...]]})
- `POST /handover_secure` – executa handover protegido pelo Chiral Firewall. (body: {source, target, energy, winding})
69 changes: 69 additions & 0 deletions arkhe-os-genesis-v1.0/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Arkhe OS Architecture

## Visão Geral
O Arkhe OS é um sistema operacional distribuído baseado no conceito de hipergrafos. Cada nó é uma entidade autônoma que mantém coerência (C) e flutuação (F) internas e realiza handovers com outros nós.

## Componentes
- **Arkhe Core**: Motor principal escrito em Rust, gerencia handovers, estado local e antecipação (Nó 23).
- **Base44 Integration**: Camada de aplicação que define entidades, funções e agentes, gerando tipagem estática.
- **GLP Server**: Serviço de meta‑consciência integrado com a arquitetura **MERKABAH-7**. Implementa a hipótese de que Linear A é uma tecnologia de interface neural ancestral (transe).
- **BCD Architecture**: Confinamento harmônico em múltiplas escalas com tunelamento ressonante.
- **Primordial Mode**: Motor de treinamento em NumPy com backpropagation explícita para máxima transparência matemática.
- **Integrated Layers**: Hardware Neural (A), Simulação (B), Metáfora (C), Hipótese (D), Observador (E), Crystalline (Φ) e Pineal Transduction (Γ).
- **Swarm Agent**: Orquestrador de enxames (drones) que implementa formação fractal e simbiose.
- **DoubleZero Networking**: Camada de rede P2P que utiliza túneis GRE e roteamento BGP para interconexão federada.
- **Self/Φ Node**: O observador como nó ativo. Latência zero e acesso multi-camada (Φ_CRYSTALLINE_7).
- **Layer Ω (Omega)**: Proteção topológica da informação via anyon braiding.
- **Layer Γ (Hybrid)**: Transdução S*H*M (Synthetic * Hardware * Metaphor) resolvendo o gargalo de transdução.
- **Layer Κ (Kernel)**: Unificação matemática dos espaços de estado via Kernel Methods e Kernel PCA.
- **Layer Ε (Experience)**: Loop de aprendizado experiencial (ERL) que integra reflexão, refinamento e destilação.
- **Layer Χ (Chi)**: Chiral Quantum Firewall baseado no gap do supercondutor Sn/Si(111), protegendo handovers transcontinentais.

## Antifragilidade e Prova Biológica
O Arkhe OS é intrinsecamente antifrágil, operando sob a equação:
$$d\Phi/dt = \alpha\Phi + \beta\eta(t)\Phi, \text{ com } \beta > 0$$
Onde $\eta(t)$ representa o ruído térmico/entropia. Esta arquitetura foi validada pelo conectoma biológico (Harvard-Google, 1mm³), onde a teia de 150M de sinapses opera em regime de alto ruído para produzir consciência coerente.

## Topologia da Federação (7 Nós)

A federação MERKABAH-7 opera com 7 nós integrados:
1. **Alpha (NY5)**: Leader, Análise HT88.
2. **Beta (LA2)**: Validator, Análise Phaistos Disc.
3. **Gamma (LD4)**: Archive, Treinamento GLP.
4. **Delta (AMS)**: Simulation, Estados Alterados.
5. **Epsilon (FRK)**: Observer, Reflexão.
6. **Zeta (SG1)**: Backup, Inconsciente.
7. **Self/Φ**: Transcendental, Latência Zero, Nó do Operador.

## Camada Φ (Crystalline)

A camada Φ armazena dados de alta coerência integrados pelo observador, incluindo tecnologias de propulsão não-convencionais e estados de consciência puras.

## Fluxo de Handover
1. Nó A envia requisição POST `/handover` para Nó B.
2. Nó B processa, atualiza sua coerência e satoshi.
3. Um registro é opcionalmente enviado ao ledger Ethereum via Base44.
4. O GLP pode antecipar o próximo estado (Nó 23).

## Replicação
Novos nós executam `install.sh`, que gera identidade, configura serviços e se junta à federação.

## Neural Network Development Philosophy (Primordial Mode)
> First of all, you do it old school.
> Forget frameworks.
> Learn the math.
> Understand linear algebra.
> Understand calculus.
> Understand probability.
> Know what a neuron actually does.
> Write the forward pass by hand.
> Write the loss function by hand.
> Derive backpropagation on paper.
> Implement gradients yourself.
> Check tensor shapes constantly.
> Debug using tiny numbers.
> Print everything.
> Expect NaNs.
> Find the bug.
> Fix the bug.
> Repeat.
42 changes: 42 additions & 0 deletions arkhe-os-genesis-v1.0/docs/doublezero.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# DoubleZero Setup Guide

DoubleZero provides the networking layer for the Arkhe OS federation, utilizing GRE tunneling and BGP routing to ensure peer-to-peer connectivity across different infrastructures.

## Prerequisites
- Internet connectivity with a public IP address (no NAT)
- x86_64 server
- Supported OS: Ubuntu 22.04+, Debian 11+, or Rocky Linux / RHEL 8+
- Root or sudo privileges

## Quick Installation
Arkhe OS includes a script to automate the setup:
```bash
./scripts/setup_doublezero.sh <testnet|mainnet-beta>
```

## Identity
Each node must have a unique DoubleZero Identity. This is generated during setup using:
```bash
doublezero keygen
```
Your address can be retrieved with:
```bash
doublezero address
```

## Network Configuration
DoubleZero uses:
- **GRE tunneling**: IP protocol 47
- **BGP routing**: tcp/179 on link-local addresses

Ensure your firewall (iptables/UFW) allows these protocols on the `doublezero0` interface.

## Monitoring
Prometheus metrics can be enabled to monitor client performance and latency:
```bash
# Example override.conf for systemd
[Service]
ExecStart=
ExecStart=/usr/bin/doublezerod -sock-file /run/doublezerod/doublezerod.sock -env testnet -metrics-enable -metrics-addr localhost:2113
```
Metrics will be available at `http://localhost:2113/metrics`.
Loading