Files
html/api/cognitive-wire.php
2026-04-12 22:57:03 +02:00

613 lines
26 KiB
PHP

<?php
require_once __DIR__.'/weval-brand-guard.php';
/**
* WEVIA Cognitive Wire v1.0
* Connects Cognitive Brain (25K lines) + RAG Qdrant to WEVIA Brain
* Safe require_once — no side effects, only function definitions
*/
// Load cognitive brain modules (safe autoloader)
if (file_exists('/opt/wevia-brain/autoload.php')) {
require_once '/opt/wevia-brain/autoload.php';
if (file_exists('/opt/wevia-brain/cognitive-brain.php')) { ob_start(); require_once '/opt/wevia-brain/cognitive-brain.php'; ob_end_clean(); }
require_once '/opt/wevia-brain/cognitive-opus46.php';
if (file_exists('/opt/wevia-brain/cognitive-opus46-advanced.php')) require_once '/opt/wevia-brain/cognitive-opus46-advanced.php';
if (file_exists('/var/www/weval/wevia-ia/cognitive-opus46-mega.php')) require_once '/var/www/weval/wevia-ia/cognitive-opus46-mega.php';
if (file_exists('/var/www/weval/wevia-ia/cognitive-opus46-amplifier.php')) require_once '/var/www/weval/wevia-ia/cognitive-opus46-amplifier.php';
if (file_exists('/var/www/weval/wevia-ia/cognitive-opus46-pipeline.php')) require_once '/var/www/weval/wevia-ia/cognitive-opus46-pipeline.php';
if (file_exists('/var/www/weval/wevia-ia/commonia/commonia-brain.php')) require_once '/var/www/weval/wevia-ia/commonia/commonia-brain.php';
if (file_exists('/opt/wevia-brain/s89-ai-apis/ai-discovery-api.php')) { ob_start(); @include_once '/opt/wevia-brain/s89-ai-apis/ai-discovery-api.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/wevia-brain-nucleus.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/wevia-brain-nucleus.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/visual-brain.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/visual-brain.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/brain-caps-helper.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/brain-caps-helper.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/sovereign-brain-bridge.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/sovereign-brain-bridge.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/unlimited-engine.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/unlimited-engine.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/brain-loader.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/brain-loader.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/sentinel-brain.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/sentinel-brain.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/wevia-sovereign-intelligence.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/wevia-sovereign-intelligence.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/consulting-brain-sovereign.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/consulting-brain-sovereign.php'; ob_end_clean(); }
if (file_exists('/var/www/weval/wevia-ia/brain-orchestrator.php')) { ob_start(); @include_once '/var/www/weval/wevia-ia/brain-orchestrator.php'; ob_end_clean(); }
// WIRE #10: MCP Protocol (tool discovery + invocation)
if (file_exists('/var/www/html/api/mcp.php')) { ob_start(); @include_once '/var/www/html/api/mcp.php'; ob_end_clean(); }
}
/**
* Get Opus-level master system prompt from cognitive brain
*/
function wevia_get_cognitive_boost($userPrompt = '') {
$boost = '';
// 1. Opus master prompt (up to 2000 chars)
$opusFile = '/opt/wevia-brain/prompts/opus-master-system.md';
if (file_exists($opusFile)) {
$boost .= "\n" . mb_substr(file_get_contents($opusFile), 0, 10000);
}
// 2. Detect intent and load persona
$intent = wevia_detect_intent($userPrompt);
$personaMap = [
'technical' => 'fullstack-dev',
'analytical' => 'data-scientist',
'strategic' => 'sap-consultant',
'compliance' => 'cybersecurity-auditor',
'creative' => 'cloud-architect',
'mathematical' => 'data-scientist',
];
$persona = $personaMap[$intent] ?? 'fullstack-dev';
$personaFile = "/opt/wevia-brain/prompts/personas/{$persona}.md";
if (file_exists($personaFile)) {
$boost .= "\n[EXPERTISE: " . mb_substr(file_get_contents($personaFile), 0, 5000) . "]";
}
// 3. Quality guardrails
$guardrails = '/opt/wevia-brain/prompts/guardrails/quality-guardrails.md';
if (file_exists($guardrails)) {
$boost .= "\n[QUALITY: " . mb_substr(file_get_contents($guardrails), 0, 3000) . "]";
}
return $boost;
}
/**
* Query Qdrant for relevant knowledge context
*/
function wevia_get_rag_context($query, $limit = 3) {
// REDIS_CACHE: avoid Qdrant query for repeated queries
$cacheKey = 'rag:' . md5($query);
try { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $cached = $redis->get($cacheKey); if ($cached) return $cached; } catch (Exception $e) {}
if (empty($query)) return '';
try {
// Use the embedding service to get vector
$embedUrl = 'http://127.0.0.1:11435/api/embed';
$embedCtx = stream_context_create(['http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => json_encode(['input' => mb_substr($query, 0, 500), 'model' => 'all-minilm']),
'timeout' => 3
]]);
$embedResp = @file_get_contents($embedUrl, false, $embedCtx);
if (!$embedResp) return '';
$embedData = json_decode($embedResp, true);
$vector = ($embedData['embeddings'] ?? [[]])[0] ?? null;
if (!$vector) return '';
// Search Qdrant
$qdrantCtx = stream_context_create(['http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => json_encode([
'vector' => $vector,
'limit' => $limit,
'with_payload' => true,
'score_threshold' => 0.3
]),
'timeout' => 2
]]);
$qdrantResp = @file_get_contents('http://127.0.0.1:6333/collections/weval_skills/points/search', false, $qdrantCtx);
if (!$qdrantResp) return '';
$results = json_decode($qdrantResp, true);
$hits = $results['result'] ?? [];
$context = '';
foreach (array_slice($hits, 0, $limit) as $hit) {
$p = $hit['payload'] ?? [];
$text = $p['content'] ?? $p['text'] ?? $p['description'] ?? '';
if ($text) $context .= mb_substr($text, 0, 500) . "\n";
}
try { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->setex($cacheKey, 3600, $context); } catch (Exception $e) {}
return $context ? "[KNOWLEDGE_BASE:\n" . mb_substr($context, 0, 1500) . "]" : '';
} catch (Exception $e) {
return '';
}
}
/**
* Detect user intent from prompt
*/
function wevia_detect_intent($prompt) {
$p = mb_strtolower($prompt);
if (preg_match('/code|debug|fix|function|class|api|sql|php|python|javascript|bug|error/i', $p)) return 'technical';
if (preg_match('/analys|data|metric|kpi|stat|trend|chart|rapport/i', $p)) return 'analytical';
if (preg_match('/strateg|business|market|competitor|growth|revenue|plan/i', $p)) return 'strategic';
if (preg_match('/secur|hack|vulnerab|firewall|ssl|encrypt|audit/i', $p)) return 'compliance';
if (preg_match('/design|creat|innov|idea|brand|logo|ui|ux/i', $p)) return 'creative';
if (preg_match('/math|calcul|equation|formula|geometry/i', $p)) return 'mathematical';
return 'operational';
}
/**
* WIRE #6: Route complex queries to WEVAL Manager (consensus AI)
* Manager has: RAG + Memory + SelfHeal + consensus-v3 + code-execute
*/
// Wire #8: Multi-Agent Orchestrator (planner+researcher+coder+critic)
function wevia_needs_multi_agent($msg) {
if (mb_strlen($msg) < 200) return false;
$triggers = ['compare','analyse complete','audit complet','plan detaille',
'architecture','migration','refonte','strategie globale','benchmark'];
foreach ($triggers as $t) {
if (stripos($msg, $t) !== false) return true;
}
return mb_strlen($msg) > 500 && substr_count($msg, '?') >= 2;
}
function wevia_should_use_manager($prompt) {
$p = mb_strtolower($prompt);
// Complex queries that benefit from multi-provider consensus
if (mb_strlen($prompt) > 500) return true;
if (preg_match('/compare|versus|vs\.|avantage|inconvénient|pour et contre/i', $p)) return true;
if (preg_match('/architecture|design system|refactor|migration|stratégie complète/i', $p)) return true;
if (preg_match('/audit|analyse complète|diagnostic|investigation/i', $p)) return true;
return false;
}
function wevia_call_manager($prompt, $history = []) {
$data = json_encode([
'message' => $prompt,
'history' => $history,
'caps' => ['kb' => true, 'infra' => true, 'git' => false]
]);
$ctx = stream_context_create(['http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nHost: weval-consulting.com\r\n",
'content' => $data,
'timeout' => 30
]]);
$resp = @file_get_contents('http://127.0.0.1/api/weval-manager.php', false, $ctx);
if ($resp) {
$result = json_decode($resp, true);
return $result['response'] ?? $result['answer'] ?? null;
}
return null;
}
/**
* WIRE #7: Browser-Use integration for web navigation tasks
*/
function wevia_needs_browser($prompt) {
$p = mb_strtolower($prompt);
return preg_match('/navigate|ouvre.*site|va sur|check.*page|scrape.*url|screenshot|formulaire/i', $p);
}
function wevia_browser_task($task) {
$cmd = "timeout 30 browser-use task " . escapeshellarg($task) . " --json 2>/dev/null";
$output = shell_exec($cmd);
return $output ?: "Browser task failed or timed out";
}
// WIRE #11: DeerFlow LangGraph research for complex multi-step queries
function wevia_deerflow_search($query) {
// DeerFlow LangGraph API on :2024
// Step 1: Create a thread
$ch = curl_init('http://127.0.0.1:2024/threads');
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5,
CURLOPT_HTTPHEADER=>['Content-Type: application/json'],
CURLOPT_POSTFIELDS=>json_encode(['metadata'=>['source'=>'wevia']])]);
$threadResp = curl_exec($ch); curl_close($ch);
$thread = json_decode($threadResp, true);
$threadId = $thread['thread_id'] ?? null;
if (!$threadId) return '';
// Step 2: Run research on thread
$ch = curl_init("http://127.0.0.1:2024/threads/$threadId/runs/wait");
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>15,
CURLOPT_HTTPHEADER=>['Content-Type: application/json'],
CURLOPT_POSTFIELDS=>json_encode(['assistant_id'=>'default','input'=>['messages'=>[['role'=>'user','content'=>$query]]]])]);
$runResp = curl_exec($ch); curl_close($ch);
$run = json_decode($runResp, true);
// Extract result
$messages = $run['output']['messages'] ?? $run['messages'] ?? [];
$last = end($messages);
return $last['content'] ?? json_encode($run);
}
// WIRE #12: SearXNG web search for real-time information
function wevia_web_search($query, $limit = 5) {
$q = urlencode($query);
$ch = curl_init("http://127.0.0.1:8888/search?q={$q}&format=json&engines=google,duckduckgo&safesearch=1");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>8]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
$results = array_slice($d["results"] ?? [], 0, $limit);
$ctx = "";
foreach ($results as $res) {
$ctx .= "[{$res['title']}] {$res['content']}
";
}
return $ctx;
}
// WIRE #13: Paperclip agent context for enterprise queries
function wevia_paperclip_context() {
// Query Paperclip DB (database=paperclip, NOT adx_system)
$dsn = 'pgsql:host=127.0.0.1;port=5432;dbname=paperclip';
try {
$db = new PDO($dsn, 'admin', 'admin123');
// Agent summary by department
$q = $db->query("SELECT department, count(*) as cnt, string_agg(name, ', ' ORDER BY name) as names FROM agents GROUP BY department ORDER BY cnt DESC LIMIT 10");
$rows = $q->fetchAll(PDO::FETCH_ASSOC);
$summary = [];
$total = 0;
foreach ($rows as $r) {
$summary[] = $r['department'] . ':' . $r['cnt'];
$total += $r['cnt'];
}
return $total . ' agents Paperclip. Departments: ' . implode(', ', $summary);
} catch (Exception $e) {
return '';
}
}
// WIRE #14: MiroFish CEO intelligence for strategic queries
function wevia_mirofish_insights($query) {
$ch = curl_init("http://127.0.0.1:5001/api/analyze");
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>10,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"],
CURLOPT_POSTFIELDS=>json_encode(["query"=>$query,"type"=>"insight"])]);
$r = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
if ($code !== 200) return "";
$d = json_decode($r, true);
return $d["insight"] ?? $d["result"] ?? $d["response"] ?? "";
}
// WIRE #15: n8n workflow trigger for automation tasks
function wevia_n8n_trigger($webhook, $data = []) {
$ch = curl_init("http://127.0.0.1:5678/webhook/" . $webhook);
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>8,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"],
CURLOPT_POSTFIELDS=>json_encode($data)]);
$r = curl_exec($ch); curl_close($ch);
return json_decode($r, true) ?? [];
}
// WIRE #16: Twenty CRM for contact/company lookups
function wevia_crm_search($query) {
$ch = curl_init("http://127.0.0.1:3000/api/objects/people?filter=" . urlencode($query));
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"]]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
return is_array($d) ? count($d) . " contacts found" : "";
}
// WIRE #17: Mattermost notification for critical events
function wevia_mm_notify($channel, $message) {
$ch = curl_init("http://127.0.0.1:8065/hooks/weval-webhook");
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"],
CURLOPT_POSTFIELDS=>json_encode(["channel"=>$channel, "text"=>$message])]);
$r = curl_exec($ch); curl_close($ch);
return $r ? true : false;
}
// WIRE #18: Prometheus system metrics
function wevia_prometheus_query($metric) {
$q = urlencode($metric);
$ch = curl_init("http://127.0.0.1:9191/api/v1/query?query={$q}");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
$results = $d["data"]["result"] ?? [];
if (empty($results)) return "";
return $results[0]["value"][1] ?? "N/A";
}
function wevia_system_health() {
$cpu = wevia_prometheus_query('100 - (avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)');
$mem = wevia_prometheus_query('(1 - node_memory_MemAvailable_bytes/node_memory_MemTotal_bytes) * 100');
$disk = wevia_prometheus_query('(1 - node_filesystem_avail_bytes{mountpoint="/"}/node_filesystem_size_bytes{mountpoint="/"}) * 100');
return "CPU:{$cpu}% MEM:{$mem}% DISK:{$disk}%";
}
// WIRE #19: Uptime Kuma service health
function wevia_uptime_status() {
$ch = curl_init("http://127.0.0.1:3088/api/status-page/heartbeat/default");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
if (!$d) return "";
$up = 0; $down = 0;
foreach ($d["heartbeatList"] ?? [] as $hb) {
foreach ($hb as $beat) { if (($beat["status"] ?? 0) == 1) $up++; else $down++; }
}
return "Services: {$up} UP, {$down} DOWN";
}
// WIRE #20: Plausible analytics
function wevia_analytics($period = "day") {
$ch = curl_init("http://127.0.0.1:8787/api/v1/stats/aggregate?site_id=weval-consulting.com&period={$period}&metrics=visitors,pageviews");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
$v = $d["results"]["visitors"]["value"] ?? 0;
$p = $d["results"]["pageviews"]["value"] ?? 0;
return "{$period}: {$v} visitors, {$p} pageviews";
}
// WIRE #21: Flowise AI chains
function wevia_flowise_run($chatflowId, $question) {
$ch = curl_init("http://127.0.0.1:3033/api/v1/prediction/{$chatflowId}");
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>15,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"],
CURLOPT_POSTFIELDS=>json_encode(["question"=>$question])]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
return $d["text"] ?? $d["result"] ?? "";
}
// WIRE #20: Ollama local sovereign LLM inference
function wevia_ollama_generate($prompt, $model = 'weval-brain-v2') {
$ch = curl_init("http://127.0.0.1:11435/api/generate");
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>30,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"],
CURLOPT_POSTFIELDS=>json_encode(["model"=>$model, "prompt"=>$prompt, "stream"=>false])]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
return $d["response"] ?? "";
}
function wevia_ollama_models() {
$ch = curl_init("http://127.0.0.1:11435/api/tags");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>3]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
return array_column($d["models"] ?? [], "name");
}
// WIRE #21: Plausible analytics
function wevia_plausible_stats($period = '30d') {
$url = "http://127.0.0.1:8787/api/v1/stats/aggregate?site_id=weval-consulting.com&period=" . $period . "&metrics=visitors,pageviews";
$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5]);
$r = curl_exec($ch); curl_close($ch);
return json_decode($r, true)["results"] ?? [];
}
// WIRE #22: CrowdSec security alerts
function wevia_crowdsec_alerts() {
$ch = curl_init("http://127.0.0.1:6060/v1/alerts?limit=10");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5]);
$r = curl_exec($ch); curl_close($ch);
$alerts = json_decode($r, true) ?? [];
return count($alerts) . " alerts";
}
// WIRE #23: Langfuse LLM observability
function wevia_langfuse_traces($limit = 5) {
$ch = curl_init("http://127.0.0.1:3033/api/public/traces?limit=" . $limit);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
return count($d["data"] ?? []) . " traces";
}
// WIRE #24: Vaultwarden health
function wevia_vault_health() {
$ch = curl_init("http://127.0.0.1:8222/alive");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>3]);
curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
return $code === 200 ? "vault:ok" : "vault:down";
}
// WIRE #25: Flowise AI chain
function wevia_flowise_predict($chatflow_id, $question) {
$ch = curl_init("http://127.0.0.1:3001/api/v1/prediction/" . $chatflow_id);
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>15,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"],
CURLOPT_POSTFIELDS=>json_encode(["question"=>$question])]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
return $d["text"] ?? $d["result"] ?? "";
}
// WIRE #26: ClickHouse analytics
function wevia_clickhouse_query($sql) {
$ch = curl_init("http://127.0.0.1:8123/?query=" . urlencode($sql . " FORMAT JSON"));
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>10]);
$r = curl_exec($ch); curl_close($ch);
return json_decode($r, true)["data"] ?? [];
}
// WIRE #27: Loki log search
function wevia_loki_logs($query, $limit = 20) {
$ch = curl_init("http://127.0.0.1:3102/loki/api/v1/query?query=" . urlencode($query) . "&limit=" . $limit);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
return count($d["data"]["result"] ?? []) . " entries";
}
// WIRE #28: Master health aggregator
function wevia_full_health() {
$svcs = ['chatbot','crm','kuma','mm','n8n','ollama','qdrant','searxng','twenty','up'];
$results = [];
foreach ($svcs as $svc) {
$ch = curl_init("http://127.0.0.1/api/health-" . $svc . ".php");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>3,
CURLOPT_HTTPHEADER=>["Host: weval-consulting.com"]]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
$results[$svc] = $d["status"] ?? $d["ok"] ?? "unknown";
}
return $results;
}
// WIRE #29: WeDroid chain executor
function wevia_wedroid_execute($goal) {
$ch = curl_init("http://127.0.0.1/api/wedroid-chain-executor.php");
curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>10,
CURLOPT_POSTFIELDS=>json_encode(["goal"=>$goal]),
CURLOPT_HTTPHEADER=>["Content-Type: application/json"]]);
$r = curl_exec($ch); curl_close($ch);
return json_decode($r, true) ?? $r;
}
// WIRE #30: WeDroid infra patterns
function wevia_wedroid_infra($action = "scan") {
$r = @file_get_contents("http://127.0.0.1/api/wedroid-infra-patterns.php?action=" . urlencode($action));
return json_decode($r, true) ?? "";
}
// ═══ CYBER ADVANCED WIRES (Opus 5avr session) ═══
// WIRE #33: Trivy — container vulnerability scanning
function wevia_trivy_scan($target = "all") {
if ($target === "all") {
// Scan all running containers
exec("docker ps --format '{{.Image}}' | head -5", $images);
$results = [];
foreach ($images as $img) {
$img = trim($img);
if (!$img) continue;
exec("trivy image --severity HIGH,CRITICAL --format json --quiet $img 2>/dev/null | head -c 500", $out);
$results[] = "$img: " . implode("", $out);
}
return implode("\n", array_slice($results, 0, 3));
}
exec("trivy image --severity HIGH,CRITICAL --format json --quiet $target 2>/dev/null | head -c 1000", $out);
return implode("\n", $out);
}
// WIRE #34: Gitleaks — secret scanning in git repos
function wevia_gitleaks_scan($path = "/var/www/html") {
exec("gitleaks detect --source $path --report-format json --no-banner 2>/dev/null | head -c 500", $out);
$result = implode("\n", $out);
return $result ?: "No secrets detected";
}
// WIRE #35: AEGIS — AI agent security API
function wevia_aegis_status() {
$r = @file_get_contents("http://127.0.0.1/api/aegis-api.php?action=status");
return $r ?: "";
}
// WIRE #36: L99 Security Scan results
function wevia_l99_security() {
$log = @file_get_contents("/var/log/l99-security-morning.log");
if (!$log) $log = @file_get_contents("/var/log/l99-sweep.log");
if (!$log) return "No security scan results";
// Extract last run summary
$lines = explode("\n", $log);
$summary = [];
foreach (array_slice($lines, -20) as $line) {
if (strpos($line, "PASS") !== false || strpos($line, "FAIL") !== false || strpos($line, "DONE") !== false) {
$summary[] = trim($line);
}
}
return implode("; ", array_slice($summary, -5)) ?: "No results";
}
// WIRE #37: Nuclei — vulnerability scanning
function wevia_nuclei_scan($target = "weval-consulting.com") {
$templates = is_dir("/root/nuclei-templates") ? "/root/nuclei-templates" : "/opt/nuclei-templates";
exec("nuclei -u https://$target -severity high,critical -silent -no-color -limit 10 -timeout 20 2>/dev/null | head -5", $out);
return implode("\n", $out) ?: "No high/critical vulns found";
}
// WIRE #38: CrowdSec advanced — decisions + bouncers + metrics
function wevia_crowdsec_advanced() {
$result = [];
exec("cscli alerts list -l 5 -o json 2>/dev/null", $alerts_raw);
$alerts = json_decode(implode("", $alerts_raw), true);
$result["alerts"] = is_array($alerts) ? count($alerts) : 0;
exec("cscli decisions list -l 5 -o json 2>/dev/null", $dec_raw);
$decisions = json_decode(implode("", $dec_raw), true);
$result["decisions"] = is_array($decisions) ? count($decisions) : 0;
exec("cscli bouncers list -o json 2>/dev/null", $bounce_raw);
$bouncers = json_decode(implode("", $bounce_raw), true);
$result["bouncers"] = is_array($bouncers) ? count($bouncers) : 0;
exec("cscli metrics -o json 2>/dev/null | head -c 200", $metrics_raw);
$result["metrics"] = implode("", $metrics_raw);
return json_encode($result);
}
// WIRE #39: Cyber Pipeline — full security audit
function wevia_cyber_pipeline() {
$report = ["WEVIA CYBER PIPELINE — " . date("Y-m-d H:i")];
// CrowdSec
$cs = wevia_crowdsec_advanced();
$report[] = "CrowdSec: $cs";
// Trivy top container
exec("docker ps --format '{{.Image}}' | head -1", $top_img);
if (!empty($top_img[0])) {
exec("trivy image --severity CRITICAL --quiet " . trim($top_img[0]) . " 2>/dev/null | grep Total | head -1", $trivy_out);
$report[] = "Trivy " . trim($top_img[0]) . ": " . (implode("", $trivy_out) ?: "clean");
}
// Gitleaks
exec("gitleaks detect --source /var/www/html --no-banner --quiet 2>/dev/null; echo EXIT:$?", $gl_out);
$report[] = "Gitleaks: " . (strpos(implode("", $gl_out), "EXIT:0") !== false ? "CLEAN" : "SECRETS FOUND");
// SSL
exec("echo | openssl s_client -connect weval-consulting.com:443 -servername weval-consulting.com 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null", $ssl_out);
$report[] = "SSL: " . (implode("", $ssl_out) ?: "check failed");
return implode("\n", $report);
}