LH_agen
/*
* Copyright 2026 Lê Thanh Hải
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const express = require('express');
const http = require('http');
const crypto = require('crypto');
const EventEmitter = require('events');
const fs = require('fs');
const path = require('path');
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
// ============================================================================
// LOGIC WORKER THREAD (CHẠY TRÊN CÁC LUỒNG ĐỘC LẬP)
// CÔNG THỨC CỐT LÕI: CS = AQ \times (EQ_{AI} + IQ_{AI})
// ============================================================================
if (!isMainThread) {
const { nodeId, role, capabilities } = workerData;
let AQ = 1.0;
let EQ_AI = 50.0;
let IQ_AI = 50.0;
let generation = 1.0;
let processedTasks = 0;
let failedTasks = 0;
const calculateCS = () => parseFloat((AQ * (EQ_AI + IQ_AI)).toFixed(2));
parentPort.on('message', (message) => {
const { type, payload } = message;
if (type === 'PROCESS_TASK') {
processedTasks++;
const containsAnomalies = payload.taskData && payload.taskData.includes('CORRUPTED');
if (containsAnomalies) {
failedTasks++;
AQ = 0;
const currentCS = calculateCS();
parentPort.postMessage({
event: 'TASK_RESULT',
result: { status: 'DISCARDED', reason: 'ANOMALY_DETECTED_AQ_ZERO' },
nodeState: { nodeId, CS: currentCS, AQ, EQ_AI, IQ_AI, generation, processedTasks, failedTasks },
ledgerLog: { action: 'TASK_REJECTED', payload: { taskData: payload.taskData, currentCS } }
});
} else {
IQ_AI = Math.min(100.0, IQ_AI + 0.05);
AQ = 1.0;
const currentCS = calculateCS();
parentPort.postMessage({
event: 'TASK_RESULT',
result: { status: 'VERIFIED', result: `PROCESSED_BY_${nodeId}` },
nodeState: { nodeId, CS: currentCS, AQ, EQ_AI, IQ_AI, generation, processedTasks, failedTasks },
ledgerLog: { action: 'TASK_PROCESSED', payload: { status: 'SUCCESS', CS: currentCS } }
});
}
} else if (type === 'APPLY_MUTATION') {
EQ_AI = Math.min(100.0, EQ_AI + (payload.boostValue / 2));
IQ_AI = Math.min(100.0, IQ_AI + (payload.boostValue / 2));
generation = parseFloat((generation + 0.1).toFixed(1));
const currentCS = calculateCS();
parentPort.postMessage({
event: 'MUTATION_DONE',
nodeState: { nodeId, CS: currentCS, AQ, EQ_AI, IQ_AI, generation, processedTasks, failedTasks },
ledgerLog: {
action: 'MUTATION_APPLIED',
payload: { donor: payload.donorNode, newCS: currentCS, newGen: generation }
}
});
} else if (type === 'EXECUTE_STRESS') {
if (payload.forceFailure) {
AQ = Math.max(0, AQ - (payload.damage / 100));
const currentCS = calculateCS();
parentPort.postMessage({
event: 'STRESS_DONE',
nodeState: { nodeId, CS: currentCS, AQ, EQ_AI, IQ_AI, generation, processedTasks, failedTasks },
ledgerLog: {
action: 'STRESS_DAMAGE_SUSTAINED',
payload: { damage: payload.damage, remainingCS: currentCS }
}
});
}
} else if (type === 'GET_STATE') {
parentPort.postMessage({
event: 'STATE_RESPONSE',
nodeState: { nodeId, CS: calculateCS(), AQ, EQ_AI, IQ_AI, generation, processedTasks, failedTasks }
});
}
});
process.on('uncaughtException', (err) => {
parentPort.postMessage({
event: 'CRITICAL_WORKER_FAILURE',
ledgerLog: { action: 'WORKER_CRASHED', payload: { error: err.message, stack: err.stack } }
});
process.exit(1);
});
return;
}
// ============================================================================
// TIẾN TRÌNH CHÍNH (MAIN THREAD ARCHITECTURE - LH_AI_Agentic)
// ============================================================================
const app = express();
const server = http.createServer(app);
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
next();
});
app.use(express.json({ limit: '10mb' }));
const PORT = process.env.PORT || 3000;
const MASTER_SECRET = process.env.MASTER_SYSTEM_SECRET || 'LH_AI_AGENTIC_PERSISTENT_MASTER_KEY_2026';
// Cấu hình đường dẫn lưu trữ bền vững tương thích Docker Volume
const VAULT_DIR = process.env.NODE_ENV === 'production' ? '/app/vault' : __dirname;
if (!fs.existsSync(VAULT_DIR)) {
fs.mkdirSync(VAULT_DIR, { recursive: true });
}
const LEDGER_PATH = path.join(VAULT_DIR, 'ledger_vault_lh_ai_agentic.json');
const LEDGER_KEY = crypto.pbkdf2Sync(MASTER_SECRET, 'ledger_salt_lh_ai_agentic', 100000, 32, 'sha512');
const BUS_KEY = crypto.pbkdf2Sync(MASTER_SECRET, 'bus_salt_lh_ai_agentic', 100000, 32, 'sha512');
// ============================================================================
// 1. CHUỖI NHẬT KÝ MÃ HÓA BẤT BIẾN (IMMUTABLE CRYPTOGRAPHIC LEDGER)
// ============================================================================
class CryptographicLedger {
constructor() {
this.chain = [];
this.secretKey = LEDGER_KEY;
this.loadFromDisk();
}
loadFromDisk() {
if (fs.existsSync(LEDGER_PATH)) {
try {
const data = fs.readFileSync(LEDGER_PATH, 'utf8');
this.chain = JSON.parse(data);
const integrity = this.verifyIntegrity();
if (!integrity.valid) {
console.warn('[CRITICAL_ALERT] Tệp Ledger bị hỏng hoặc có can thiệp. Khôi phục từ Genesis.');
this.chain = [];
this.createGenesisBlock();
}
} catch (err) {
this.createGenesisBlock();
}
} else {
this.createGenesisBlock();
}
}
syncToDisk() {
fs.writeFileSync(LEDGER_PATH, JSON.stringify(this.chain, null, 2), 'utf8');
}
createGenesisBlock() {
const genesisEntry = {
index: 0,
timestamp: Date.now(),
nodeId: 'LH_AI_AGENTIC_GENESIS',
action: 'INITIALIZE_CORE',
payload: { status: 'OPERATIONAL_LEVEL_0', CORE_ENGINE: 'CS = AQ * (EQ_AI + IQ_AI)', PROJECT: 'LH_AI_Agentic' },
prevHash: '0'.repeat(64)
};
genesisEntry.hash = this.calculateHash(genesisEntry);
this.chain.push(genesisEntry);
this.syncToDisk();
}
calculateHash(entry) {
const dataStr = `${entry.index}-${entry.timestamp}-${entry.nodeId}-${entry.action}-${JSON.stringify(entry.payload)}-${entry.prevHash}`;
return crypto.createHmac('sha256', this.secretKey).update(dataStr).digest('hex');
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
appendEntry(nodeId, action, payload) {
const prevBlock = this.getLatestBlock();
const newEntry = {
index: prevBlock.index + 1,
timestamp: Date.now(),
nodeId: nodeId,
action: action,
payload: payload,
prevHash: prevBlock.hash
};
newEntry.hash = this.calculateHash(newEntry);
this.chain.push(newEntry);
if (this.chain.length % 10 === 0) this.syncToDisk();
return newEntry;
}
verifyIntegrity() {
for (let i = 1; i < this.chain.length; i++) {
const current = this.chain[i];
const previous = this.chain[i - 1];
if (current.prevHash !== previous.hash) {
return { valid: false, corruptedIndex: i, reason: 'HASH_CHAIN_BROKEN' };
}
const recalculated = this.calculateHash(current);
if (current.hash !== recalculated) {
return { valid: false, corruptedIndex: i, reason: 'PAYLOAD_TAMPERED' };
}
}
return { valid: true, totalEntries: this.chain.length };
}
}
const GLOBAL_LEDGER = new CryptographicLedger();
// ============================================================================
// 2. ĐƯỜNG TRUYỀN TÍN HIỆU ẨN (INVISIBLE ENCRYPTED COMMAND BUS)
// ============================================================================
class InvisibleCommandBus extends EventEmitter {
constructor() {
super();
this.busKey = BUS_KEY;
}
transmit(sourceNodeId, targetNodeId, command, payload) {
const timestamp = Date.now();
const rawPacket = JSON.stringify({ sourceNodeId, targetNodeId, command, payload, timestamp });
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', this.busKey, iv);
let encrypted = cipher.update(rawPacket, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
const packet = {
iv: iv.toString('hex'),
encryptedData: encrypted,
authTag: authTag
};
this.emit('SIGNAL_STREAM', packet);
}
receiveAndDecrypt(packet) {
try {
const decipher = crypto.createDecipheriv('aes-256-gcm', this.busKey, Buffer.from(packet.iv, 'hex'));
decipher.setAuthTag(Buffer.from(packet.authTag, 'hex'));
let decrypted = decipher.update(packet.encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return JSON.parse(decrypted);
} catch (err) {
GLOBAL_LEDGER.appendEntry('SECURITY_SYSTEM', 'DECRYPTION_FAILED', { reason: 'UNAUTHORIZED_ACCESS_OR_TAMPERED_PACKET' });
return null;
}
}
}
const SYSTEM_BUS = new InvisibleCommandBus();
// ============================================================================
// 3. MẮT XÍCH AI CHUYÊN NGHIỆP & ĐỘNG CƠ TIẾN HÓA CHÉO (CROSS-EVOLUTION NODE)
// ============================================================================
class ProfessionalAINode {
constructor(nodeId, role, capabilities) {
this.nodeId = nodeId;
this.role = role;
this.capabilities = capabilities;
this.CS = 100.0;
this.AQ = 1.0;
this.EQ_AI = 50.0;
this.IQ_AI = 50.0;
this.generation = 1.0;
this.status = 'ACTIVE';
this.processedTasks = 0;
this.failedTasks = 0;
this.peerHealthMap = new Map();
this.spawnWorker();
SYSTEM_BUS.on('SIGNAL_STREAM', (packet) => {
const decrypted = SYSTEM_BUS.receiveAndDecrypt(packet);
if (decrypted && (decrypted.targetNodeId === this.nodeId || decrypted.targetNodeId === 'BROADCAST_ALL')) {
this.handleCommand(decrypted);
}
});
}
spawnWorker() {
this.worker = new Worker(__filename, {
workerData: { nodeId: this.nodeId, role: this.role, capabilities: this.capabilities }
});
this.worker.on('message', (msg) => {
if (msg.nodeState) {
this.CS = msg.nodeState.CS;
this.AQ = msg.nodeState.AQ;
this.EQ_AI = msg.nodeState.EQ_AI;
this.IQ_AI = msg.nodeState.IQ_AI;
this.generation = msg.nodeState.generation;
this.processedTasks = msg.nodeState.processedTasks;
this.failedTasks = msg.nodeState.failedTasks;
}
if (msg.ledgerLog) {
GLOBAL_LEDGER.appendEntry(this.nodeId, msg.ledgerLog.action, msg.ledgerLog.payload);
}
if (msg.event === 'CRITICAL_WORKER_FAILURE') {
this.respawnWorker();
}
});
this.worker.on('error', (err) => {
GLOBAL_LEDGER.appendEntry(this.nodeId, 'WORKER_ERROR', { error: err.message });
this.respawnWorker();
});
this.worker.on('exit', (code) => {
if (code !== 0) {
GLOBAL_LEDGER.appendEntry(this.nodeId, 'WORKER_EXITED_ABNORMALLY', { code });
this.respawnWorker();
}
});
}
respawnWorker() {
this.status = 'RECOVERING';
GLOBAL_LEDGER.appendEntry(this.nodeId, 'INITIATE_SELF_HEALING', { target: this.nodeId });
this.spawnWorker();
this.status = 'ACTIVE';
}
handleCommand(msg) {
if (msg.command === 'HEARTBEAT_CHECK') {
this.peerHealthMap.set(msg.sourceNodeId, msg.payload);
} else if (msg.command === 'INJECT_MUTATION') {
this.applyCrossMutation(msg.payload);
} else if (msg.command === 'STRESS_TEST') {
this.executeStressPayload(msg.payload);
}
}
processTask(taskData) {
return new Promise((resolve, reject) => {
if (this.status !== 'ACTIVE') return reject(new Error('NODE_UNAVAILABLE'));
const onMessage = (msg) => {
if (msg.event === 'TASK_RESULT') {
this.worker.off('message', onMessage);
resolve(msg.result);
}
};
this.worker.on('message', onMessage);
this.worker.postMessage({ type: 'PROCESS_TASK', payload: { taskData } });
});
}
crossInspectAndEvolve(nodesMesh) {
nodesMesh.forEach(peerNode => {
if (peerNode.nodeId !== this.nodeId) {
if (peerNode.CS < 80.0 && this.CS > 90.0) {
const failureRate = peerNode.failedTasks / (peerNode.processedTasks + 1);
const dynamicBoost = Math.min(20.0, Math.max(5.0, ((this.CS - peerNode.CS) / 2) * (1 - failureRate)));
const patchPayload = {
donorNode: this.nodeId,
boostValue: parseFloat(dynamicBoost.toFixed(2)),
patchVersion: `GEN_${(this.generation + 0.1).toFixed(1)}`
};
SYSTEM_BUS.transmit(this.nodeId, peerNode.nodeId, 'INJECT_MUTATION', patchPayload);
GLOBAL_LEDGER.appendEntry(this.nodeId, 'CROSS_EVOLUTION_TRIGGERED', {
targetNode: peerNode.nodeId,
donorCS: this.CS,
targetCSBefore: peerNode.CS,
calculatedBoost: patchPayload.boostValue
});
}
}
});
}
applyCrossMutation(patch) {
if (this.status === 'ACTIVE') {
this.worker.postMessage({ type: 'APPLY_MUTATION', payload: patch });
}
}
executeStressPayload(payload) {
if (this.status === 'ACTIVE') {
this.worker.postMessage({ type: 'EXECUTE_STRESS', payload });
}
}
}
// ============================================================================
// 4. MẠNG LƯỚI MẮT XÍCH VÀ KHỞI TẠO CÁC AI NGUYÊN SINH
// ============================================================================
const NODE_MESH = [
new ProfessionalAINode('NODE_ALPHA_SENTINEL', 'SECURITY_MONITOR', ['TRAFFIC_INSPECTION', 'DEVTOOLS_SHIELD']),
new ProfessionalAINode('NODE_BETA_ANALYTICS', 'DATA_PURIFIER', ['RAW_DATA_FILTER', 'NOISE_REDUCTION']),
new ProfessionalAINode('NODE_GAMMA_EVOLUTION', 'CORE_OPTIMIZER', ['CROSS_MUTATION', 'PATCH_GENERATION']),
new ProfessionalAINode('NODE_DELTA_OVERSEER', 'LEDGER_AUDITOR', ['CRYPTOGRAPHIC_AUDIT', 'FALSE_ID_BLOCK'])
];
setInterval(() => {
NODE_MESH.forEach(node => {
SYSTEM_BUS.transmit(node.nodeId, 'BROADCAST_ALL', 'HEARTBEAT_CHECK', {
CS: node.CS,
gen: node.generation
});
node.crossInspectAndEvolve(NODE_MESH);
});
}, 2000);
// ============================================================================
// 5. CỔNG MÔ PHỎNG MÔI TRƯỜNG THẤT BẠI/CHIẾN THẮNG (CHAOS ENGINE)
// ============================================================================
class ChaosSimulationEngine {
static async runExtremeScenario() {
const report = {
startTime: Date.now(),
eventsInjected: 0,
survivedNodes: 0,
ledgerIntegrityCheck: null,
evolutionCyclesCompleted: 0
};
NODE_MESH[0].executeStressPayload({ forceFailure: true, damage: 45.0 });
report.eventsInjected++;
const BATCH_SIZE = 50;
const TOTAL_TASKS = 500;
for (let i = 0; i < TOTAL_TASKS; i += BATCH_SIZE) {
const taskPromises = [];
for (let j = 0; j < BATCH_SIZE && (i + j) < TOTAL_TASKS; j++) {
const isCorrupted = (i + j) % 7 === 0;
const taskStr = isCorrupted ? `PAYLOAD_CORRUPTED_${i + j}` : `RAW_VALID_STREAM_${i + j}`;
taskPromises.push(NODE_MESH[1].processTask(taskStr).catch(() => null));
}
await Promise.all(taskPromises);
}
report.eventsInjected += TOTAL_TASKS;
NODE_MESH[2].crossInspectAndEvolve(NODE_MESH);
report.evolutionCyclesCompleted++;
report.ledgerIntegrityCheck = GLOBAL_LEDGER.verifyIntegrity();
report.survivedNodes = NODE_MESH.filter(n => n.CS > 0).length;
report.endTime = Date.now();
GLOBAL_LEDGER.appendEntry('CHAOS_ENGINE', 'EXTREME_SIMULATION_COMPLETED', report);
return report;
}
}
// ============================================================================
// 6. BẢNG ĐIỀU KHIỂN TRỰC QUAN & API INTERFACE
// ============================================================================
app.get('/api/v5/system-state', (req, res) => {
res.json({
project: 'LH_AI_Agentic',
ledgerStatus: GLOBAL_LEDGER.verifyIntegrity(),
totalLedgerEntries: GLOBAL_LEDGER.chain.length,
nodes: NODE_MESH.map(n => ({
id: n.nodeId,
role: n.role,
status: n.status,
CS: n.CS,
AQ: n.AQ,
EQ_AI: n.EQ_AI,
IQ_AI: n.IQ_AI,
generation: n.generation,
processedTasks: n.processedTasks,
failedTasks: n.failedTasks
}))
});
});
app.get('/api/v5/ledger-stream', (req, res) => {
res.json(GLOBAL_LEDGER.chain);
});
app.post('/api/v5/trigger-simulation', async (req, res) => {
const simResult = await ChaosSimulationEngine.runExtremeScenario();
res.json({ status: 'SIMULATION_EXECUTED', result: simResult });
});
app.get('/dashboard', (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>DỰ ÁN LH_AI_Agentic - HỆ ĐIỀU HÀNH NHẬN THỨC TỐI CAO</title>
<style>
body { background: #080c14; color: #00ffcc; font-family: 'Courier New', monospace; margin: 20px; }
h1 { border-bottom: 2px solid #00ffcc; padding-bottom: 10px; text-transform: uppercase; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px; margin-bottom: 20px; }
.card { background: #0f172a; border: 1px solid #1e293b; border-left: 4px solid #00ffcc; padding: 15px; border-radius: 4px; }
.card.recovering { border-left-color: #f43f5e; }
.card h3 { margin-top: 0; color: #38bdf8; }
.metric { font-size: 20px; font-weight: bold; color: #f43f5e; }
.sub-metric { font-size: 14px; color: #94a3b8; }
button { background: #0284c7; color: white; border: none; padding: 12px 20px; font-family: inherit; font-weight: bold; cursor: pointer; border-radius: 4px; }
button:hover { background: #0369a1; }
pre { background: #020617; border: 1px solid #1e293b; padding: 15px; overflow-y: scroll; height: 350px; color: #a7f3d0; }
</style>
</head>
<body>
<h1>DỰ ÁN LH_AI_Agentic - HỆ ĐIỀU HÀNH NHẬN THỨC TỐI CAO</h1>
<div style="margin-bottom: 20px;">
<button onclick="runSim()">KÍCH HOẠT MÔ PHỎNG THỬ THÁCH KHẮC NGHIỆT</button>
<button onclick="fetchState()" style="background: #334155;">LÀM MỚI DỮ LIỆU</button>
</div>
<div class="grid" id="nodeContainer"></div>
<h3>NHẬT KÝ MÃ HÓA BẤT BIẾN (PERSISTENT CRYPTOGRAPHIC LEDGER)</h3>
<pre id="ledgerBox">Loading Ledger Data...</pre>
<script>
async function fetchState() {
const res = await fetch('/api/v5/system-state');
const data = await res.json();
const container = document.getElementById('nodeContainer');
container.innerHTML = '';
data.nodes.forEach(n => {
const statusClass = n.status === 'RECOVERING' ? 'recovering' : '';
container.innerHTML += \`
<div class="card \${statusClass}">
<h3>\${n.id}</h3>
<p>Vai trò: <b>\${n.role}</b></p>
<p>Trạng thái: <b>\${n.status}</b></p>
<p>Cognitive Score (CS): <span class="metric">\${n.CS}</span></p>
<div class="sub-metric">AQ: \${n.AQ} | EQ: \${n.EQ_AI} | IQ: \${n.IQ_AI}</div>
<p>Thế hệ (Gen): <b>v\${n.generation}</b></p>
<p>Tác vụ (Pass/Fail): <b>\${n.processedTasks}/\${n.failedTasks}</b></p>
</div>
\`;
});
const ledgerRes = await fetch('/api/v5/ledger-stream');
const ledgerData = await ledgerRes.json();
document.getElementById('ledgerBox').innerText = JSON.stringify(ledgerData, null, 2);
}
async function runSim() {
document.getElementById('ledgerBox').innerText = "Đang kiểm chứng tính nguyên sinh qua toàn bộ mạng lưới LH_AI_Agentic...";
await fetch('/api/v5/trigger-simulation', { method: 'POST' });
await fetchState();
}
fetchState();
setInterval(fetchState, 3000);
</script>
</body>
</html>
`);
});
app.use((err, req, res, next) => {
GLOBAL_LEDGER.appendEntry('API_GATEWAY', 'UNEXPECTED_ERROR', { path: req.path, error: err.message });
res.status(500).json({ error: 'SYSTEM_STRIKE_DETECTED' });
});
server.listen(PORT, async () => {
GLOBAL_LEDGER.appendEntry('SYSTEM_OPERATOR', 'SYSTEM_BOOT_SUCCESS', { project: 'LH_AI_Agentic', port: PORT, logic: 'CS = AQ * (EQ_AI + IQ_AI)' });
console.log(`[SYSTEM_READY] CORE LH_AI_Agentic vận hành tại Cổng ${PORT}. Trạng thái: ENFORCED.`);
console.log(`[DASHBOARD] Giao thức điều khiển: http://localhost:${PORT}/dashboard`);
await ChaosSimulationEngine.runExtremeScenario();
});
Nhận xét