DON
Paste ID: db64576b
Created at: 2026-06-21 21:58:37
Content
<?php
// ============================================================================
// DEEP OBSERVATION NETWORK – CENTRAL PHP SERVER + DASHBOARD
// ============================================================================
// Run: php -S 0.0.0.0:8000 (requires PHP 7.4+ with SQLite3 enabled)
$db_file = 'don.db';
$db = new SQLite3($db_file);
$db->exec("PRAGMA journal_mode=WAL");
// ---------- Database setup ----------
$db->exec("CREATE TABLE IF NOT EXISTS nodes (
node_id TEXT PRIMARY KEY,
trust_score REAL DEFAULT 1.0,
last_seen INTEGER
)");
$db->exec("CREATE TABLE IF NOT EXISTS information_objects (
id TEXT PRIMARY KEY,
type TEXT,
payload TEXT,
origin_node TEXT,
timestamp REAL,
propagation_path TEXT,
confidence REAL DEFAULT 0.0,
entropy REAL DEFAULT 0.0,
consensus REAL DEFAULT 0.0,
metadata TEXT DEFAULT '{}'
)");
$db->exec("CREATE TABLE IF NOT EXISTS observations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
info_id TEXT,
observer_id TEXT,
timestamp REAL,
confidence REAL,
notes TEXT,
UNIQUE(info_id, observer_id)
)");
// ---------- Helper functions ----------
function generateUUID() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
// ---------- Mathematical Engines (PHP) ----------
function computeConfidence($observations, $currentResult) {
$I = 0; $N = 0;
foreach ($observations as $obs) {
if (($obs['confidence'] >= 0.5) == $currentResult) $I += $obs['confidence'];
else $N += $obs['confidence'];
}
return ($I + $N) ? $I / ($I + $N) : 0.5;
}
function computeEntropy($observations) {
if (count($observations) == 0) return 0;
$agree = 0;
foreach ($observations as $obs) {
if ($obs['confidence'] >= 0.5) $agree++;
}
$total = count($observations);
$pAgree = $agree / $total;
$pDisagree = 1 - $pAgree;
$H = 0;
if ($pAgree > 0) $H -= $pAgree * log($pAgree, 2);
if ($pDisagree > 0) $H -= $pDisagree * log($pDisagree, 2);
return $H;
}
function computeVerification($observations, $trustScores) {
$agree = 0; $disagree = 0;
$sourceCounts = [];
foreach ($observations as $obs) {
$trust = $trustScores[$obs['observer_id']] ?? 1.0;
if ($obs['confidence'] >= 0.5) $agree += $trust;
else $disagree += $trust;
$sourceCounts[$obs['observer_id']] = ($sourceCounts[$obs['observer_id']] ?? 0) + 1;
}
$majority = $agree >= $disagree;
$total = $agree + $disagree;
$agreement = $total ? $agree / $total : 0;
if (count($observations) == 0) {
$independence = 0;
} else {
$maxProp = max($sourceCounts) / count($observations);
$independence = 1 - $maxProp;
}
return [$majority, $agreement, $independence];
}
function computeConsensus($confidence, $verificationScore) {
return $confidence * $verificationScore;
}
function computeDeepScore($confidence, $consensus) {
return $confidence * $consensus;
}
function updateObjectMetrics($db, $infoId) {
$obj = $db->querySingle("SELECT * FROM information_objects WHERE id='$infoId'", true);
if (!$obj) return;
// Get observations
$obsRes = $db->query("SELECT * FROM observations WHERE info_id='$infoId'");
$observations = [];
while ($row = $obsRes->fetchArray(SQLITE3_ASSOC)) {
$observations[] = $row;
}
// Get trust scores (simplified: all 1.0)
$trustScores = [];
foreach ($observations as $o) {
$trustScores[$o['observer_id']] = 1.0;
}
list($result, $agreement, $independence) = computeVerification($observations, $trustScores);
$V = $agreement * $independence;
$C = computeConfidence($observations, $result);
$H = computeEntropy($observations);
$G = computeConsensus($C, $V);
$D = computeDeepScore($C, $G);
$meta = json_decode($obj['metadata'], true) ?? [];
$meta['verification_result'] = $result;
$meta['agreement'] = $agreement;
$meta['independence'] = $independence;
$meta['V'] = $V;
$meta['deep_score'] = $D;
$stmt = $db->prepare("UPDATE information_objects SET confidence=:c, entropy=:e, consensus=:g, metadata=:m WHERE id=:id");
$stmt->bindValue(':c', $C, SQLITE3_FLOAT);
$stmt->bindValue(':e', $H, SQLITE3_FLOAT);
$stmt->bindValue(':g', $G, SQLITE3_FLOAT);
$stmt->bindValue(':m', json_encode($meta), SQLITE3_TEXT);
$stmt->bindValue(':id', $infoId, SQLITE3_TEXT);
$stmt->execute();
}
// ---------- SSE Event Broadcasting ----------
$sseClients = [];
// Handle SSE connection
if ($_SERVER['REQUEST_URI'] == '/stream' && $_SERVER['REQUEST_METHOD'] == 'GET') {
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('Access-Control-Allow-Origin: *');
// Register this client
$clientId = generateUUID();
$sseClients[] = $clientId;
echo "data: {\"type\":\"connected\",\"client_id\":\"$clientId\"}\n\n";
ob_flush(); flush();
// Keep connection alive and poll for new events
$lastEventId = 0;
while (true) {
// Check for new events from a simple event queue table
$db->exec("CREATE TABLE IF NOT EXISTS sse_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event TEXT
)");
$res = $db->query("SELECT id, event FROM sse_events WHERE id > $lastEventId ORDER BY id ASC");
while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
echo "data: {$row['event']}\n\n";
ob_flush(); flush();
$lastEventId = $row['id'];
}
// Clean up old events (keep last 1000)
$db->exec("DELETE FROM sse_events WHERE id NOT IN (SELECT id FROM sse_events ORDER BY id DESC LIMIT 1000)");
sleep(1); // poll interval
if (connection_aborted()) break;
}
exit;
}
// Helper to add an SSE event
function addSSEEvent($db, $event) {
$escaped = SQLite3::escapeString(json_encode($event));
$db->exec("INSERT INTO sse_events (event) VALUES ('$escaped')");
}
// ---------- REST API Endpoints ----------
$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
if ($method == 'POST' && $uri == '/submit') {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) { http_response_code(400); exit('Invalid JSON'); }
$id = $input['id'] ?? generateUUID();
$type = $input['type'] ?? 'text';
$payload = json_encode($input['payload'] ?? '');
$origin = $input['origin_node'] ?? 'anonymous';
$timestamp = $input['timestamp'] ?? microtime(true);
$path = json_encode($input['propagation_path'] ?? [$origin]);
$stmt = $db->prepare("INSERT INTO information_objects (id, type, payload, origin_node, timestamp, propagation_path)
VALUES (:id, :type, :payload, :origin, :ts, :path)");
$stmt->bindValue(':id', $id, SQLITE3_TEXT);
$stmt->bindValue(':type', $type, SQLITE3_TEXT);
$stmt->bindValue(':payload', $payload, SQLITE3_TEXT);
$stmt->bindValue(':origin', $origin, SQLITE3_TEXT);
$stmt->bindValue(':ts', $timestamp, SQLITE3_FLOAT);
$stmt->bindValue(':path', $path, SQLITE3_TEXT);
$stmt->execute();
// Notify all SSE clients about new object
addSSEEvent($db, [
'type' => 'new_object',
'info_id' => $id,
'payload' => $input['payload'],
'info_type' => $type,
'origin_node' => $origin
]);
header('Content-Type: application/json');
echo json_encode(['status' => 'ok', 'info_id' => $id]);
exit;
}
if ($method == 'POST' && $uri == '/observe') {
$input = json_decode(file_get_contents('php://input'), true);
$infoId = $input['info_id'] ?? null;
$observerId = $input['observer_id'] ?? 'anonymous';
$confidence = floatval($input['confidence'] ?? 0.5);
$notes = $input['notes'] ?? '';
if (!$infoId) { http_response_code(400); exit('Missing info_id'); }
$stmt = $db->prepare("INSERT OR REPLACE INTO observations (info_id, observer_id, timestamp, confidence, notes)
VALUES (:info_id, :observer, :ts, :conf, :notes)");
$stmt->bindValue(':info_id', $infoId, SQLITE3_TEXT);
$stmt->bindValue(':observer', $observerId, SQLITE3_TEXT);
$stmt->bindValue(':ts', microtime(true), SQLITE3_FLOAT);
$stmt->bindValue(':conf', $confidence, SQLITE3_FLOAT);
$stmt->bindValue(':notes', $notes, SQLITE3_TEXT);
$stmt->execute();
// Update metrics
updateObjectMetrics($db, $infoId);
// Get updated object
$obj = $db->querySingle("SELECT * FROM information_objects WHERE id='$infoId'", true);
$meta = json_decode($obj['metadata'], true);
$update = [
'type' => 'verification_update',
'info_id' => $infoId,
'confidence' => $obj['confidence'],
'entropy' => $obj['entropy'],
'consensus' => $obj['consensus'],
'deep_score' => $meta['deep_score'] ?? 0,
'verification_result' => $meta['verification_result'] ?? false
];
addSSEEvent($db, $update);
header('Content-Type: application/json');
echo json_encode(['status' => 'ok']);
exit;
}
// Default: serve the HTML dashboard
if ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'GET') {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Deep Observation Network Dashboard</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
body { margin: 0; font-family: Arial, sans-serif; display: flex; height: 100vh; }
#graph { flex: 2; border-right: 1px solid #ccc; }
#sidebar { flex: 1; padding: 20px; overflow-y: auto; }
.metric { margin-bottom: 15px; }
.metric span { font-weight: bold; }
form { margin-top: 20px; }
textarea { width: 100%; }
.node circle { stroke: #fff; stroke-width: 2px; }
.link { stroke: #999; stroke-opacity: 0.6; }
.label { font-size: 10px; pointer-events: none; }
</style>
</head>
<body>
<div id="graph"></div>
<div id="sidebar">
<h2>Submit Information</h2>
<form id="submitForm">
<label>Type: <select id="infoType">
<option value="text">text</option>
<option value="transaction">transaction</option>
<option value="event">event</option>
<option value="sensor">sensor</option>
<option value="file">file</option>
</select></label>
<label>Payload (JSON for transaction):</label>
<textarea id="payload" rows="4">{"sender":"Alice","receiver":"Bob","amount":100,"currency":"USD"}</textarea>
<button type="submit">Submit</button>
</form>
<div id="metrics">
<h3>Selected Node Metrics</h3>
<p id="nodeInfo">Click a node to see details</p>
</div>
<div id="legend">
<h3>Legend</h3>
<p>Color: Confidence (green=high, red=low)</p>
<p>Size: Number of observations</p>
</div>
</div>
<script>
// ==================== D3 Graph Setup ====================
const width = document.getElementById('graph').clientWidth;
const height = window.innerHeight;
const svg = d3.select('#graph').append('svg')
.attr('width', width)
.attr('height', height);
const simulation = d3.forceSimulation()
.force('link', d3.forceLink().id(d => d.id).distance(100))
.force('charge', d3.forceManyBody().strength(-300))
.force('center', d3.forceCenter(width / 2, height / 2));
let graph = { nodes: [], links: [] };
const link = svg.append('g')
.selectAll('line');
const node = svg.append('g')
.selectAll('circle');
const label = svg.append('g')
.selectAll('text');
function updateGraph() {
// Re-bind data
link = svg.selectAll('.link')
.data(graph.links, d => d.source.id + '-' + d.target.id);
link.exit().remove();
link = link.enter().append('line')
.attr('class', 'link')
.merge(link);
node = svg.selectAll('.node')
.data(graph.nodes, d => d.id);
node.exit().remove();
const nodeEnter = node.enter().append('circle')
.attr('class', 'node')
.attr('r', 10)
.call(d3.drag()
.on('start', dragstarted)
.on('drag', dragged)
.on('end', dragended))
.on('click', (event, d) => showNodeInfo(d));
node = nodeEnter.merge(node);
// Update node attributes
node.attr('fill', d => d.color || '#69b3a2')
.attr('r', d => Math.max(5, (d.influence || 1) * 3));
label = svg.selectAll('.label')
.data(graph.nodes, d => d.id);
label.exit().remove();
label = label.enter().append('text')
.attr('class', 'label')
.text(d => d.id.substring(0, 8))
.merge(label);
simulation.nodes(graph.nodes);
simulation.force('link').links(graph.links);
simulation.alpha(0.3).restart();
simulation.on('tick', () => {
link.attr('x1', d => d.source.x)
.attr('y1', d => d.source.y)
.attr('x2', d => d.target.x)
.attr('y2', d => d.target.y);
node.attr('cx', d => d.x)
.attr('cy', d => d.y);
label.attr('x', d => d.x + 12)
.attr('y', d => d.y + 4);
});
}
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
// ==================== Data Management ====================
const serverUrl = window.location.origin;
let localNodeId = 'client_' + Math.random().toString(36).substr(2, 9);
const knownObjects = {};
function addOrUpdateNode(id, type, confidence = 0.5, influence = 0) {
let existing = graph.nodes.find(n => n.id === id);
if (!existing) {
graph.nodes.push({
id: id,
type: type,
confidence: confidence,
influence: influence,
color: confidenceColor(confidence)
});
} else {
existing.confidence = confidence;
existing.influence = influence;
existing.color = confidenceColor(confidence);
}
updateGraph();
}
function confidenceColor(conf) {
// green at 1.0, red at 0.0
const r = Math.round((1 - conf) * 255);
const g = Math.round(conf * 255);
return `rgb(${r},${g},0)`;
}
function showNodeInfo(d) {
const info = document.getElementById('nodeInfo');
if (d.type === 'info') {
const obj = knownObjects[d.id];
if (obj) {
info.innerHTML = `<b>ID:</b> ${d.id}<br>
<b>Type:</b> ${obj.type}<br>
<b>Confidence:</b> ${obj.confidence.toFixed(3)}<br>
<b>Entropy:</b> ${obj.entropy.toFixed(3)}<br>
<b>Consensus:</b> ${obj.consensus.toFixed(3)}<br>
<b>Deep Score:</b> ${obj.deep_score?.toFixed(3) || 'N/A'}<br>
<b>Observers:</b> ${obj.observer_count || 0}`;
}
} else {
info.innerHTML = `<b>Node:</b> ${d.id}<br><b>Type:</b> client`;
}
}
// ==================== SSE Connection ====================
const evtSource = new EventSource(serverUrl + '/stream');
evtSource.onmessage = function(event) {
try {
const data = JSON.parse(event.data);
if (data.type === 'new_object') {
// Create local info object
knownObjects[data.info_id] = {
id: data.info_id,
type: data.info_type,
payload: data.payload,
origin_node: data.origin_node,
confidence: 0.5,
entropy: 0,
consensus: 0,
deep_score: 0,
observer_count: 0
};
addOrUpdateNode(data.info_id, 'info', 0.5, 0);
// Automatically send an observation (simulate client verification)
sendObservation(data.info_id, 0.8); // default confidence
// Add link from origin to info
if (!graph.links.find(l => l.source.id === data.origin_node && l.target.id === data.info_id)) {
graph.links.push({ source: data.origin_node, target: data.info_id });
addOrUpdateNode(data.origin_node, 'client', 0.5, 0);
updateGraph();
}
}
else if (data.type === 'verification_update') {
if (knownObjects[data.info_id]) {
knownObjects[data.info_id].confidence = data.confidence;
knownObjects[data.info_id].entropy = data.entropy;
knownObjects[data.info_id].consensus = data.consensus;
knownObjects[data.info_id].deep_score = data.deep_score;
knownObjects[data.info_id].observer_count = (knownObjects[data.info_id].observer_count || 0) + 1;
// Update node
let node = graph.nodes.find(n => n.id === data.info_id);
if (node) {
node.confidence = data.confidence;
node.color = confidenceColor(data.confidence);
node.influence = knownObjects[data.info_id].observer_count;
updateGraph();
}
}
}
} catch(e) { console.error(e); }
};
// ==================== Helper: Send observation ====================
function sendObservation(infoId, confidence) {
fetch(serverUrl + '/observe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
info_id: infoId,
observer_id: localNodeId,
confidence: confidence,
notes: 'Client observation'
})
}).catch(console.error);
}
// ==================== Submit new information ====================
document.getElementById('submitForm').addEventListener('submit', function(e) {
e.preventDefault();
const type = document.getElementById('infoType').value;
let payload = document.getElementById('payload').value;
if (type === 'transaction') {
try { payload = JSON.parse(payload); } catch(e) { alert('Invalid JSON'); return; }
}
fetch(serverUrl + '/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type: type,
payload: payload,
origin_node: localNodeId
})
}).then(r => r.json()).then(d => {
console.log('Submitted:', d.info_id);
}).catch(console.error);
});
// ==================== Initial load of existing objects ====================
// (Optional: fetch from a /objects endpoint if you add one)
// For now, only objects created after connection appear.
</script>
</body>
</html>
<?php
exit;
}
// Fallback
http_response_code(404);
echo 'Not found';