File size: 5,785 Bytes
9425aed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
 * Ahmad Orchestrator β€” Sovereign Event Bus Orchestrator
 * Integrates BOB VOYAGER telemetry + verification + WORM sealing
 * NORAD 25544 Β· ISS ZARYA
 * Apache 2.0 Β· SnapKitty Collective 2026
 */

import http from 'http';
import { OrbitalOracle } from './orbital_oracle.mjs';

const PORT = process.env.AHMAD_PORT || 5555;
const VOYAGER_URL = process.env.VOYAGER_URL || 'http://localhost:4299';

const oracle = new OrbitalOracle({ voyagerUrl: VOYAGER_URL });
let orchestrationLog = [];
let eventCount = 0;

/**
 * Ahmad State Machine
 * Tracks verification state and decisions
 */
class AhmadOrchestrator {
  constructor() {
    this.state = 'INIT';
    this.lastVerification = null;
    this.lastDecision = null;
    this.anomalies = [];
    this.startTime = Date.now();
  }

  async verify() {
    const result = await oracle.verify();

    if (!result.ok) {
      this.state = 'ERROR';
      this.lastDecision = { type: 'ERROR', message: result.error };
      return result;
    }

    this.state = 'VERIFIED';
    this.lastVerification = result;

    // Decision logic: if all invariants pass, seal as valid
    if (result.valid && Object.values(result.invariants).every(Boolean)) {
      this.lastDecision = {
        type: 'ACCEPT',
        timestamp: new Date().toISOString(),
        position: result.position,
        altitude: result.altitude,
        invariants_passed: result.invariants_passed,
      };
    } else {
      // Flag anomaly
      this.lastDecision = {
        type: 'ANOMALY',
        timestamp: new Date().toISOString(),
        errors: result.errors,
        warnings: result.warnings,
      };
      this.anomalies.push(this.lastDecision);
    }

    orchestrationLog.push({
      seq: eventCount++,
      timestamp: new Date().toISOString(),
      decision: this.lastDecision,
      verification: result,
    });

    return {
      ok: true,
      verification: result,
      decision: this.lastDecision,
      state: this.state,
    };
  }

  getStatus() {
    return {
      state: this.state,
      uptime_s: Math.floor((Date.now() - this.startTime) / 1000),
      events_processed: eventCount,
      anomalies_detected: this.anomalies.length,
      last_verification: this.lastVerification,
      last_decision: this.lastDecision,
    };
  }

  getLog(limit = 50) {
    return orchestrationLog.slice(-limit);
  }

  getAnomalies(limit = 50) {
    return this.anomalies.slice(-limit);
  }
}

const ahmad = new AhmadOrchestrator();

/**
 * HTTP Server β€” Ahmad Orchestrator API
 */
function cors(res) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
}

function json(res, data, status = 200) {
  cors(res);
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(data, null, 2));
}

const server = http.createServer(async (req, res) => {
  if (req.method === 'OPTIONS') {
    cors(res);
    res.writeHead(204);
    res.end();
    return;
  }

  const url = req.url.split('?')[0];

  // ─ GET /status β€” Current orchestrator state
  if (url === '/status') {
    json(res, ahmad.getStatus());
    return;
  }

  // ─ POST /verify β€” Run verification cycle
  if (url === '/verify' && req.method === 'POST') {
    const result = await ahmad.verify();
    json(res, result, result.ok ? 200 : 400);
    return;
  }

  // ─ GET /log β€” Orchestration log
  if (url === '/log') {
    const limit = parseInt(new URL(`http://localhost${req.url}`).searchParams.get('limit') || 50);
    json(res, {
      ok: true,
      count: orchestrationLog.length,
      entries: ahmad.getLog(limit),
    });
    return;
  }

  // ─ GET /anomalies β€” Detected anomalies
  if (url === '/anomalies') {
    json(res, {
      ok: true,
      count: ahmad.anomalies.length,
      anomalies: ahmad.getAnomalies(),
    });
    return;
  }

  // ─ GET /health β€” Service health
  if (url === '/health') {
    json(res, {
      ok: true,
      service: 'ahmad-orchestrator',
      version: '1.0.0',
      state: ahmad.state,
      uptime_s: Math.floor((Date.now() - ahmad.startTime) / 1000),
      events_total: eventCount,
    });
    return;
  }

  cors(res);
  res.writeHead(404);
  res.end('Not found');
});

// ─ Boot
console.log(`
╔════════════════════════════════════════════╗
β•‘  Ahmad Orchestrator v1.0                   β•‘
β•‘  Sovereign Event Bus Orchestrator           β•‘
β•‘  NORAD 25544 Β· ISS ZARYA                   β•‘
β•‘  http://localhost:${PORT}                      β•‘
β•‘  Apache 2.0 Β· SnapKitty Collective 2026    β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

  API endpoints:
    GET  /status               orchestrator state + last decision
    POST /verify               run verification cycle
    GET  /log?limit=50         orchestration log
    GET  /anomalies            detected anomalies
    GET  /health               service health
`);

server.listen(PORT, () => {
  console.log(`Ahmad Orchestrator listening on port ${PORT}`);
});

// ─ Polling loop: verify every 5 seconds
console.log('Starting orbital verification loop (5s interval)...\n');
setInterval(async () => {
  const result = await ahmad.verify();
  if (result.ok) {
    const status = result.decision.type === 'ACCEPT' ? 'βœ“' : 'βœ—';
    console.log(
      `[AHMAD] ${status} LAT ${result.verification.position[0].toFixed(2)}Β° ALT ${result.verification.altitude.toFixed(0)}km | ${result.decision.type}`
    );
  } else {
    console.error(`[AHMAD] ERROR: ${result.error}`);
  }
}, 5000);