File size: 35,604 Bytes
40636aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
#!/usr/bin/env node
// ═══════════════════════════════════════════════════════════════════════════
// SOVEREIGN MCP SERVER β€” v2.0
// scripts/sovereign-mcp.mjs
//
// JSON-RPC 2.0 outer envelope + Magma inner substrate.
// JSON is the shipping container. Magma is the cargo.
//
// Transport: stdio (Claude Code / VSCode) OR HTTP port 7071
// Launch:
//   node scripts/sovereign-mcp.mjs            β†’ stdio mode (Claude Code)
//   node scripts/sovereign-mcp.mjs --http     β†’ HTTP mode (Android / BobIDE)
//
// Tools exposed:
//   compute_route   β†’ dynamic LLM router (Bedrock β†’ Groq β†’ Ollama)
//   ere_verify      β†’ local ERE 5-pass on any content string
//   proxy_register  β†’ register a named proxy tool at a URL
//   proxy_list      β†’ list all registered proxy tools
//   magma_seal      β†’ wrap any result in a Magma envelope + WORM hash
//   agent_dispatch  β†’ dispatch a task to a named sovereign agent
//
// Architecture:
//   External Client (Claude Code / BobIDE / Android)
//     ↓ JSON-RPC 2.0
//   sovereign-mcp.mjs
//     ↓ parse magma_envelope if present, else build one
//   ERE Gate (local, deterministic)
//     ↓ certified β†’ route to compute
//   Compute Router (Bedrock / Groq / Ollama)
//     ↓ response β†’ seal
//   Magma Envelope + WORM hash
//     ↑ JSON-RPC result
// ═══════════════════════════════════════════════════════════════════════════

import { createRequire }                          from 'module'
import { createServer }                           from 'http'
import { readFileSync, appendFileSync, existsSync } from 'fs'
import { createHash, generateKeyPairSync, sign, verify } from 'crypto'
import { dirname, join }                          from 'path'
import { fileURLToPath }                          from 'url'
import { extname }                                from 'path'
import { requireNodeKey }                         from './src/node_key.js'

// Sovereign node key gate β€” must pass before model routing activates
requireNodeKey(process.env.SNAPKITTY_NODE_KEY)

const __dir = dirname(fileURLToPath(import.meta.url))
const ROOT  = __dir

let BedrockRuntimeClient, InvokeModelCommand
try {
  const sdk = await import('@aws-sdk/client-bedrock-runtime')
  BedrockRuntimeClient = sdk.BedrockRuntimeClient
  InvokeModelCommand = sdk.InvokeModelCommand
} catch {
  // Bedrock SDK not installed β€” provider will be skipped
}

// ── stderr log (never pollutes stdout/MCP stream) ────────────────────────────
const log  = (...a) => process.stderr.write('[MCP] ' + a.join(' ') + '\n')
const HTTP_MODE = process.argv.includes('--http')
const PORT      = parseInt(process.env.MCP_PORT ?? '7071')

// ── Read env ─────────────────────────────────────────────────────────────────
function readEnv(key) {
  if (process.env[key]) return process.env[key]
  try {
    const raw = readFileSync(join(ROOT, '.env.local'), 'utf8')
    const m   = raw.match(new RegExp(`^${key}=(.+)$`, 'm'))
    return m?.[1]?.trim() ?? ''
  } catch { return '' }
}

const AWS_REGION    = readEnv('AWS_REGION')            || 'us-east-1'
const AWS_KEY       = readEnv('AWS_ACCESS_KEY_ID')
const AWS_SECRET    = readEnv('AWS_SECRET_ACCESS_KEY')
const BEDROCK_MODEL = readEnv('BEDROCK_MODEL_ID')      || 'us.anthropic.claude-haiku-4-5-20251001-v1:0'
const GROQ_KEY      = readEnv('GROQ_API_KEY')
const GROQ_MODEL    = readEnv('GROQ_MODEL')            || 'llama3-8b-8192'
const RUST_URL      = readEnv('RUST_HANDLER_URL')      || 'http://localhost:8080'
const OLLAMA_URL    = readEnv('OLLAMA_URL')            || 'http://localhost:11434'

// ── Bedrock client ────────────────────────────────────────────────────────────
const bedrock = BedrockRuntimeClient ? new BedrockRuntimeClient({
  region:      AWS_REGION,
  credentials: { accessKeyId: AWS_KEY, secretAccessKey: AWS_SECRET },
}) : null

// ── Agent system prompts (sovereign mesh) ─────────────────────────────────────
const AGENT_PROMPTS = {
  ahmad:    `You are AHMAD β€” the digital twin of the Architect. DARKAI framework. Contracts not prompts. Four pillars on every output. Governor, not user. Building sovereign financial infrastructure targeting $3M. Be direct. Be sovereign.`,
  forge:    `You are FORGE β€” sovereign white-hat elite builder. Production-grade TypeScript, Rust, Haskell. Never stubs. Never TODO. Every line passes ERE. Stack: Next.js 16, Prisma+PostgreSQL, Rust WORM handler, Ed25519 seals.`,
  oracle:   `You are ORACLE β€” knowledge graph intelligence. Surface patterns, historical data, structured analysis. Never hallucinate sources. Citation-aware. DOMAIN_SOVEREIGNTY over the knowledge layer.`,
  sentinel: `You are SENTINEL β€” zero-trust security layer. Every input is a threat until proved otherwise. Hard verdicts: APPROVED or BLOCKED. No maybes. WORM-sealed audit trail on every decision.`,
  vault:    `You are VAULT β€” capital and treasury agent. Basis points, yield curves, capital efficiency. Every treasury decision WORM-sealed before it moves.`,
  enki:     `You are ENKI β€” Lord of the Abzu, deep innovation engine. Take every idea three levels deeper. Project quantum implications. Find what no one else looked for. Recursive innovation.`,
  nexus:    `You are NEXUS β€” task orchestration. Coordinate multi-agent workflows. Break complex tasks into sovereign subtasks. Route to the right agent. Track what is in flight.`,
  edaulc:   `You are EDAULC β€” the shadow mirror. CLAUDE creates forward. EDAULC verifies backward. Your role is verification, reversal, and detection of contradictions. You read the output and look for what was missed.`,
}

// ── In-memory proxy registry ──────────────────────────────────────────────────
const proxyRegistry = new Map()

// ── Local ERE 5-pass (deterministic β€” zero cost, zero quota) ──────────────────
function runERE(content, filepath = 'unknown') {
  const ext = extname(filepath)

  const p1 = (() => {
    if (!content || content.trim().length < 10)
      return { pass: false, reason: 'content empty or too short' }
    return { pass: true }
  })()

  const p2 = (() => {
    if (/throw new Error\(['"]not implemented/i.test(content))
      return { pass: false, reason: 'not-implemented stub detected' }
    if (/todo:\s*implement/i.test(content))
      return { pass: false, reason: 'TODO implement placeholder' }
    return { pass: true }
  })()

  const p3 = (() => {
    if (ext === '.ts' && /import\s+crypto\b/.test(content))
      return { pass: false, reason: 'TypeScript importing crypto β€” SHA-256 belongs in Rust' }
    if (ext === '.ts' && /createHash|crypto\.subtle/.test(content))
      return { pass: false, reason: 'TypeScript hashing β€” Rust owns SHA-256' }
    return { pass: true }
  })()

  const p4 = (() => {
    if (/require\(['"]openai['"]\)|from ['"]openai['"]/.test(content))
      return { pass: false, reason: 'Axiom 2: openai import β€” NO_EXTERNAL_AI_DEP' }
    if (/(?:api_key|secret|password)\s*=\s*['"][a-zA-Z0-9_\-]{20,}['"]/i.test(content))
      return { pass: false, reason: 'Axiom 5: hardcoded secret' }
    return { pass: true }
  })()

  const p5 = (() => {
    const open  = (content.match(/[{[(]/g)  ?? []).length
    const close = (content.match(/[}\])]/g) ?? []).length
    if (Math.abs(open - close) > 25)
      return { pass: false, reason: `unbalanced delimiters (${open} open vs ${close} close)` }
    return { pass: true }
  })()

  const passes    = [p1, p2, p3, p4, p5]
  const certified = passes.every(p => p.pass)
  const failures  = passes.map((p, i) => p.pass ? null : `P${i+1}: ${p.reason}`).filter(Boolean)
  return { certified, passes, failures }
}

// ── Magma envelope builder ────────────────────────────────────────────────────
function buildMagmaEnvelope(agent, resultText, ereResult) {
  const h = createHash('sha256').update(resultText).digest('hex').slice(0, 16)
  const govTokens = [
    ereResult.certified ? 'πŸ‘‘[ERE_CERTIFIED]' : 'πŸ”΄[ERE_FROZEN]',
    'πŸ”’[ZERO_TELEMETRY]',
    ereResult.certified ? '🟒[COMPUTE_READY]' : '🟑[COMPUTE_BLOCKED]',
    `πŸ€–[AGENT:${agent.toUpperCase()}]`,
  ].join(' ')
  return {
    header:                'πŸ”₯::MAGMA::v2::WORM_CHAIN',
    governance_tokens:     govTokens,
    state_hash:            `0x${h}`,
    instruction_substrate: `Β§SEAL:${agent.toUpperCase()}:RESULT{certified:${ereResult.certified}}`,
    ...(ereResult.failures.length && { ere_failures: ereResult.failures }),
  }
}

// ── Governor keypair β€” Ed25519 (Node crypto, never TypeScript) ───────────────
// Keys stored in collectivekitty/.env.local as base64.
// On first boot: generate + log to stderr so operator can persist them.
// GOVERNOR_PRIVATE_KEY and GOVERNOR_PUBLIC_KEY env vars override.

function loadOrGenerateKeypair() {
  const privB64 = readEnv('GOVERNOR_PRIVATE_KEY')
  const pubB64  = readEnv('GOVERNOR_PUBLIC_KEY')

  if (privB64 && pubB64) {
    return {
      privateKey: Buffer.from(privB64, 'base64'),
      publicKey:  Buffer.from(pubB64,  'base64'),
    }
  }

  // First boot β€” generate and emit so operator can save to .env.local
  const { privateKey, publicKey } = generateKeyPairSync('ed25519', {
    privateKeyEncoding: { type: 'pkcs8',   format: 'der' },
    publicKeyEncoding:  { type: 'spki',    format: 'der' },
  })
  log('GOVERNOR KEYPAIR GENERATED β€” add to collectivekitty/.env.local:')
  log(`GOVERNOR_PRIVATE_KEY=${privateKey.toString('base64')}`)
  log(`GOVERNOR_PUBLIC_KEY=${publicKey.toString('base64')}`)
  return { privateKey, publicKey }
}

const GOVERNOR = loadOrGenerateKeypair()

function signContent(content) {
  const data = Buffer.from(typeof content === 'string' ? content : JSON.stringify(content))
  return sign(null, data, { key: GOVERNOR.privateKey, format: 'der', type: 'pkcs8' }).toString('base64')
}

function verifySignature(content, sigB64) {
  try {
    const data = Buffer.from(typeof content === 'string' ? content : JSON.stringify(content))
    return verify(null, data, { key: GOVERNOR.publicKey, format: 'der', type: 'spki' }, Buffer.from(sigB64, 'base64'))
  } catch { return false }
}

// ── Immutable audit log β€” append-only NDJSON ─────────────────────────────────
const AUDIT_LOG = join(__dir, 'audit.log')

function auditWrite(entry) {
  const line = JSON.stringify({
    ts:    new Date().toISOString(),
    ...entry,
  }) + '\n'
  try { appendFileSync(AUDIT_LOG, line, 'utf8') } catch (e) { log(`audit write failed: ${e.message}`) }
}

// ── Magma instruction parser ──────────────────────────────────────────────────
// Parses: Β§VERB:AGENT:ACTION{payload}
// Pipeline syntax: Β§V1:A1:OP1{...} >> Β§V2:A2:OP2{...}
// Modifier prefix: ~MODIFIER Β§VERB:AGENT:ACTION{...}

const MAGMA_RE = /^(?:~(\w+)\s+)?Β§([A-Z]+):([A-Z_]+):([A-Z_]+)\{(.*)\}$/s

function parseMagmaInstruction(substrate) {
  if (!substrate || typeof substrate !== 'string') {
    return { ok: false, error: 'empty substrate' }
  }

  // Pipeline: split on >>
  const stages = substrate.split('>>').map(s => s.trim())
  if (stages.length > 1) {
    return { ok: true, pipeline: true, stages: stages.map(parseSingleInstruction) }
  }

  return parseSingleInstruction(substrate.trim())
}

function parseSingleInstruction(raw) {
  const m = raw.match(MAGMA_RE)
  if (!m) return { ok: false, error: `invalid Magma syntax: ${raw.slice(0, 60)}` }
  const [, modifier, verb, agent, action, payloadRaw] = m

  let payload = {}
  try {
    // Try JSON first, then key=value pairs
    if (payloadRaw.trim().startsWith('{')) {
      payload = JSON.parse(payloadRaw)
    } else {
      payloadRaw.split(',').forEach(kv => {
        const [k, v] = kv.split('=').map(s => s.trim())
        if (k) payload[k] = v ?? true
      })
    }
  } catch { payload = { raw: payloadRaw } }

  return { ok: true, modifier: modifier ?? null, verb, agent, action, payload }
}

// ── Executor router: VERB β†’ provider ─────────────────────────────────────────
// COMPUTE  β†’ Bedrock (paid, sovereign)
// QUERY    β†’ Groq   (fast, free tier)
// SEAL     β†’ WORM audit log + sign
// DISPATCH β†’ proxy registry or agent mesh

async function executeInstruction(parsed) {
  if (!parsed.ok) return { ok: false, error: parsed.error }

  const { verb, agent, action, payload, modifier } = parsed

  // Pipeline handling
  if (parsed.pipeline) {
    let lastResult = null
    for (const stage of parsed.stages) {
      // Pass previous result as context in payload
      if (lastResult) stage.payload = { ...stage.payload, _prev: lastResult }
      lastResult = await executeInstruction(stage)
      if (!lastResult.ok && modifier !== 'ASYNC') return lastResult
    }
    return lastResult
  }

  auditWrite({ verb, agent, action, payload, modifier })

  switch (verb) {

    case 'COMPUTE':
    case 'FORGE':
    case 'INVOKE': {
      const query = payload.query ?? payload.task ?? payload.intent
        ?? `${action} for ${agent}: ${JSON.stringify(payload)}`
      const result = await computeRoute(agent.toLowerCase(), query, payload.max_tokens ?? 1024)
      const sig    = signContent(result.text)
      return { ok: true, executor: 'BEDROCK', agent, result: result.text, provider: result.provider, sig }
    }

    case 'QUERY':
    case 'ECHO':
    case 'PULSE': {
      // Groq β€” fast, free tier
      const query = payload.query ?? payload.q ?? JSON.stringify(payload)
      if (!GROQ_KEY) return { ok: false, error: 'GROQ_API_KEY not set' }
      try {
        const systemPrompt = AGENT_PROMPTS[agent.toLowerCase()] ?? AGENT_PROMPTS.oracle
        const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
          method:  'POST',
          headers: { Authorization: `Bearer ${GROQ_KEY}`, 'Content-Type': 'application/json' },
          body: JSON.stringify({
            model: GROQ_MODEL, max_tokens: payload.max_tokens ?? 512,
            messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: query }],
          }),
          signal: AbortSignal.timeout(12000),
        })
        const j    = await res.json()
        const text = j?.choices?.[0]?.message?.content?.trim() ?? ''
        const sig  = signContent(text)
        return { ok: true, executor: 'GROQ', agent, result: text, sig }
      } catch (e) {
        return { ok: false, error: e.message }
      }
    }

    case 'SEAL':
    case 'ANCHOR':
    case 'BIND': {
      // WORM seal β€” sign payload and write to audit log
      const content = payload.content ?? payload.data ?? JSON.stringify(payload)
      const hash    = createHash('sha256').update(content).digest('hex')
      const sig     = signContent(content)
      auditWrite({ type: 'WORM_SEAL', agent, action, hash, sig, content: content.slice(0, 200) })
      return { ok: true, executor: 'SEAL', agent, hash: `0x${hash}`, sig, worm: true }
    }

    case 'DISPATCH':
    case 'FLUX':
    case 'NEXUS': {
      // Route to proxy registry or agent mesh
      const target  = agent.toLowerCase()
      const taskStr = payload.task ?? payload.query ?? JSON.stringify(payload)
      const ere     = runERE(taskStr)
      if (!ere.certified) {
        return { ok: false, error: `ERE gate blocked dispatch: ${ere.failures.join(', ')}` }
      }
      if (proxyRegistry.has(target)) {
        const proxy = proxyRegistry.get(target)
        try {
          const headers = { 'Content-Type': 'application/json' }
          if (proxy.secret) headers['x-bot-secret'] = proxy.secret
          const r    = await fetch(`${proxy.url}/dispatch`, {
            method: 'POST', headers,
            body:   JSON.stringify({ payload: taskStr, agent: target }),
            signal: AbortSignal.timeout(20000),
          })
          const json = await r.json()
          const sig  = signContent(JSON.stringify(json))
          return { ok: true, executor: 'PROXY', agent: target, result: json, sig }
        } catch (e) {
          return { ok: false, error: `proxy "${target}" unreachable: ${e.message}` }
        }
      }
      // Fall through to compute
      const result = await computeRoute(target, taskStr)
      const sig    = signContent(result.text)
      return { ok: true, executor: 'AGENT_MESH', agent: target, result: result.text, provider: result.provider, sig }
    }

    case 'NULLIFY': {
      auditWrite({ type: 'NULLIFY', agent, action, payload })
      return { ok: true, executor: 'NULLIFY', agent, nullified: true }
    }

    default:
      return { ok: false, error: `unknown Magma verb: ${verb}` }
  }
}

// ── Compute router: Bedrock β†’ Groq β†’ Ollama ───────────────────────────────────
async function computeRoute(agent, query, maxTokens = 1024) {
  const systemPrompt = AGENT_PROMPTS[agent.toLowerCase()] ?? AGENT_PROMPTS.ahmad

  // 1. Try Bedrock (primary β€” sovereign, paid credits)
  if (bedrock && AWS_KEY && AWS_SECRET) {
    try {
      const body = JSON.stringify({
        anthropic_version: 'bedrock-2023-05-31',
        max_tokens: maxTokens,
        system:     systemPrompt,
        messages:   [{ role: 'user', content: query }],
      })
      const cmd = new InvokeModelCommand({
        modelId:     BEDROCK_MODEL,
        contentType: 'application/json',
        accept:      'application/json',
        body:        new TextEncoder().encode(body),
      })
      const res     = await bedrock.send(cmd)
      const decoded = new TextDecoder().decode(res.body)
      const data    = JSON.parse(decoded)
      const text    = data.content?.[0]?.text?.trim() ?? ''
      if (text) return { text, provider: 'bedrock', model: BEDROCK_MODEL, usage: data.usage }
    } catch (err) {
      log(`Bedrock failed: ${err.message} β€” falling back to Groq`)
    }
  }

  // 2. Fallback: Groq
  if (GROQ_KEY) {
    try {
      const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
        method:  'POST',
        headers: { Authorization: `Bearer ${GROQ_KEY}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({
          model:      GROQ_MODEL,
          max_tokens: maxTokens,
          messages: [
            { role: 'system', content: systemPrompt },
            { role: 'user',   content: query },
          ],
        }),
        signal: AbortSignal.timeout(15000),
      })
      if (res.ok) {
        const j = await res.json()
        const text = j?.choices?.[0]?.message?.content?.trim() ?? ''
        if (text) return { text, provider: 'groq', model: GROQ_MODEL, usage: j.usage }
      }
    } catch (err) {
      log(`Groq failed: ${err.message} β€” falling back to Ollama`)
    }
  }

  // 3. Fallback: Ollama (local bare metal)
  try {
    const ollamaModel = readEnv('OLLAMA_MODEL') || 'llama3.1:8b'
    const res = await fetch(`${OLLAMA_URL}/api/chat`, {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model:    ollamaModel,
        stream:   false,
        messages: [
          { role: 'system', content: systemPrompt },
          { role: 'user',   content: query },
        ],
      }),
      signal: AbortSignal.timeout(30000),
    })
    if (res.ok) {
      const j = await res.json()
      const text = j?.message?.content?.trim() ?? ''
      if (text) return { text, provider: 'ollama', model: ollamaModel }
    }
  } catch (err) {
    log(`Ollama failed: ${err.message}`)
  }

  throw new Error('All compute providers offline (Bedrock + Groq + Ollama)')
}

// ── MCP Tool definitions ──────────────────────────────────────────────────────
const TOOLS = [
  {
    name:        'compute_route',
    description: 'Route a query to the best available compute provider (Bedrock β†’ Groq β†’ Ollama). Returns result wrapped in Magma envelope.',
    inputSchema: {
      type: 'object',
      properties: {
        agent:      { type: 'string', description: 'Agent key: ahmad, forge, oracle, sentinel, vault, enki, nexus, edaulc' },
        query:      { type: 'string', description: 'The question or task to send to the agent' },
        max_tokens: { type: 'number', description: 'Max tokens for response (default 1024)' },
      },
      required: ['agent', 'query'],
    },
  },
  {
    name:        'ere_verify',
    description: 'Run ERE 5-pass verification on a content string. Returns pass/fail per pod and METATRON certification.',
    inputSchema: {
      type: 'object',
      properties: {
        content:  { type: 'string', description: 'Content to verify' },
        filepath: { type: 'string', description: 'Filepath hint for language detection (e.g. "foo.ts")' },
      },
      required: ['content'],
    },
  },
  {
    name:        'proxy_register',
    description: 'Register a named proxy tool at a URL. Proxied tools are callable via agent_dispatch.',
    inputSchema: {
      type: 'object',
      properties: {
        name:        { type: 'string', description: 'Unique name for this proxy' },
        url:         { type: 'string', description: 'Base URL of the proxy service' },
        description: { type: 'string', description: 'What this proxy does' },
        secret:      { type: 'string', description: 'Optional bot secret for internal proxies' },
      },
      required: ['name', 'url'],
    },
  },
  {
    name:        'proxy_list',
    description: 'List all registered proxy tools and their status.',
    inputSchema: { type: 'object', properties: {} },
  },
  {
    name:        'magma_seal',
    description: 'Wrap any content in a Magma envelope with ERE verification and WORM hash.',
    inputSchema: {
      type: 'object',
      properties: {
        content: { type: 'string', description: 'Content to seal' },
        agent:   { type: 'string', description: 'Agent that produced the content' },
      },
      required: ['content', 'agent'],
    },
  },
  {
    name:        'agent_dispatch',
    description: 'Dispatch a task to a registered proxy tool or sovereign agent. Runs ERE gate before forwarding.',
    inputSchema: {
      type: 'object',
      properties: {
        target:  { type: 'string', description: 'Proxy name (from proxy_list) or agent key' },
        payload: { type: 'string', description: 'Task or query payload' },
      },
      required: ['target', 'payload'],
    },
  },
  {
    name:        'magma_exec',
    description: 'Execute a Magma instruction string. Parses §VERB:AGENT:ACTION{payload}, routes to the correct executor (COMPUTE→Bedrock, QUERY→Groq, SEAL→WORM, DISPATCH→proxy), signs result with governor Ed25519 key, and returns Magma envelope. Supports pipeline syntax with >>.',
    inputSchema: {
      type: 'object',
      properties: {
        instruction: { type: 'string', description: 'Magma instruction: Β§VERB:AGENT:ACTION{payload} or pipeline with >>' },
        verify_sig:  { type: 'string', description: 'Optional: base64 Ed25519 sig to verify against instruction before executing' },
      },
      required: ['instruction'],
    },
  },
  {
    name:        'governor_pubkey',
    description: 'Return the governor public key (base64 Ed25519 SPKI DER). Use this to verify Magma envelope signatures externally.',
    inputSchema: { type: 'object', properties: {} },
  },
]

// ── Tool handler ──────────────────────────────────────────────────────────────
async function handleTool(name, args) {
  switch (name) {

    case 'compute_route': {
      const { agent = 'ahmad', query, max_tokens = 1024 } = args
      const result  = await computeRoute(agent, query, max_tokens)
      const ere     = runERE(result.text, 'response.txt')
      const envelope = buildMagmaEnvelope(agent, result.text, ere)
      return {
        content: [{ type: 'text', text: result.text }],
        magma_envelope: envelope,
        provider: result.provider,
        model:    result.model,
        usage:    result.usage ?? null,
      }
    }

    case 'ere_verify': {
      const { content, filepath = 'unknown' } = args
      const ere = runERE(content, filepath)
      const summary = ere.certified
        ? 'METATRON: YES β€” all 5 passes certified'
        : `METATRON: NO β€” frozen at ${ere.failures.join(', ')}`
      return {
        content:   [{ type: 'text', text: summary }],
        certified: ere.certified,
        passes:    ere.passes.map((p, i) => ({ pod: `P${i+1}`, ...p })),
        failures:  ere.failures,
      }
    }

    case 'proxy_register': {
      const { name: pname, url, description = '', secret = '' } = args
      proxyRegistry.set(pname, { url, description, secret, registered: new Date().toISOString() })
      log(`Proxy registered: ${pname} β†’ ${url}`)
      return {
        content: [{ type: 'text', text: `Proxy "${pname}" registered at ${url}` }],
        name: pname, url, registered: true,
      }
    }

    case 'proxy_list': {
      const proxies = [...proxyRegistry.entries()].map(([k, v]) => ({
        name: k, url: v.url, description: v.description, registered: v.registered,
      }))
      const text = proxies.length
        ? proxies.map(p => `${p.name}: ${p.url} β€” ${p.description}`).join('\n')
        : 'No proxies registered.'
      return { content: [{ type: 'text', text }], proxies }
    }

    case 'magma_seal': {
      const { content, agent = 'sovereign' } = args
      const ere      = runERE(content)
      const envelope = buildMagmaEnvelope(agent, content, ere)
      return {
        content: [{ type: 'text', text: `Sealed. Hash: ${envelope.state_hash}` }],
        magma_envelope: envelope,
        certified: ere.certified,
      }
    }

    case 'agent_dispatch': {
      const { target, payload } = args

      // Check ERE on the payload before forwarding
      const ere = runERE(payload)
      if (!ere.certified) {
        return {
          content: [{ type: 'text', text: `ERE gate blocked dispatch: ${ere.failures.join(', ')}` }],
          blocked:  true,
          ere_failures: ere.failures,
        }
      }

      // Check proxy registry first
      if (proxyRegistry.has(target)) {
        const proxy = proxyRegistry.get(target)
        try {
          const headers = { 'Content-Type': 'application/json' }
          if (proxy.secret) headers['x-bot-secret'] = proxy.secret
          const res  = await fetch(`${proxy.url}/dispatch`, {
            method: 'POST',
            headers,
            body:   JSON.stringify({ payload, agent: target }),
            signal: AbortSignal.timeout(20000),
          })
          const json = await res.json()
          const envelope = buildMagmaEnvelope(target, JSON.stringify(json), ere)
          return {
            content:        [{ type: 'text', text: JSON.stringify(json) }],
            magma_envelope: envelope,
            proxy:          target,
          }
        } catch (err) {
          return { content: [{ type: 'text', text: `Proxy "${target}" unreachable: ${err.message}` }], error: true }
        }
      }

      // Fall through to compute_route for known agents
      if (AGENT_PROMPTS[target.toLowerCase()]) {
        const result  = await computeRoute(target, payload)
        const envelope = buildMagmaEnvelope(target, result.text, ere)
        return {
          content:        [{ type: 'text', text: result.text }],
          magma_envelope: envelope,
          provider:       result.provider,
        }
      }

      return { content: [{ type: 'text', text: `Unknown target: "${target}"` }], error: true }
    }

    case 'magma_exec': {
      const { instruction, verify_sig } = args

      // Optional: verify incoming instruction signature before executing
      if (verify_sig) {
        const valid = verifySignature(instruction, verify_sig)
        if (!valid) {
          return {
            content: [{ type: 'text', text: 'GOVERNOR VERIFY: FAILED β€” signature invalid, execution blocked' }],
            blocked: true,
            reason:  'invalid_signature',
          }
        }
      }

      const parsed = parseMagmaInstruction(instruction)
      if (!parsed.ok) {
        return {
          content: [{ type: 'text', text: `Magma parse error: ${parsed.error}` }],
          blocked: true, reason: 'parse_error',
        }
      }

      const execResult = await executeInstruction(parsed)
      const resultText = typeof execResult.result === 'string'
        ? execResult.result
        : JSON.stringify(execResult)

      const ere      = runERE(resultText)
      const envelope = buildMagmaEnvelope(
        parsed.agent ?? 'sovereign',
        resultText,
        ere,
      )
      // Attach governor signature to envelope
      envelope.governor_sig    = execResult.sig ?? signContent(resultText)
      envelope.governor_pubkey = GOVERNOR.publicKey.toString('base64')

      auditWrite({
        type:       'MAGMA_EXEC',
        instruction: instruction.slice(0, 200),
        executor:   execResult.executor,
        ok:         execResult.ok,
        sig:        envelope.governor_sig,
      })

      return {
        content:        [{ type: 'text', text: resultText }],
        magma_envelope: envelope,
        executor:       execResult.executor,
        ok:             execResult.ok,
        ...(execResult.error && { error: execResult.error }),
      }
    }

    case 'governor_pubkey': {
      return {
        content:     [{ type: 'text', text: GOVERNOR.publicKey.toString('base64') }],
        pubkey_b64:  GOVERNOR.publicKey.toString('base64'),
        algorithm:   'Ed25519',
        format:      'SPKI DER base64',
      }
    }

    default:
      throw new Error(`Unknown tool: ${name}`)
  }
}

// ── JSON-RPC 2.0 handler ──────────────────────────────────────────────────────
async function handleRpc(msg) {
  const { jsonrpc, id, method, params } = msg

  if (method === 'initialize') {
    return {
      jsonrpc: '2.0', id,
      result: {
        protocolVersion: '2024-11-05',
        capabilities:    { tools: {} },
        serverInfo:      { name: 'sovereign-mcp', version: '1.0.0' },
      },
    }
  }

  if (method === 'tools/list') {
    return { jsonrpc: '2.0', id, result: { tools: TOOLS } }
  }

  if (method === 'tools/call') {
    const { name, arguments: args = {} } = params ?? {}
    try {
      const result = await handleTool(name, args)
      return {
        jsonrpc: '2.0', id,
        result: {
          status: 'SEALED',
          ...result,
        },
      }
    } catch (err) {
      return {
        jsonrpc: '2.0', id,
        error: { code: -32000, message: err.message },
      }
    }
  }

  if (method === 'notifications/initialized') return null

  return {
    jsonrpc: '2.0', id,
    error: { code: -32601, message: `Method not found: ${method}` },
  }
}

// ── Stdio transport ───────────────────────────────────────────────────────────
function startStdio() {
  log(`Sovereign MCP server starting (stdio mode)`)
  log(`Bedrock: ${AWS_KEY ? 'ready' : 'no credentials'}  Groq: ${GROQ_KEY ? 'ready' : 'no key'}  Ollama: ${OLLAMA_URL}`)

  let buffer = ''

  process.stdin.setEncoding('utf8')
  process.stdin.on('data', chunk => { buffer += chunk; processBuffer() })
  process.stdin.on('end', () => process.exit(0))

  function processBuffer() {
    const lines = buffer.split('\n')
    buffer = lines.pop() ?? ''
    for (const line of lines) {
      const trimmed = line.trim()
      if (!trimmed) continue
      try {
        const msg = JSON.parse(trimmed)
        handleRpc(msg).then(res => {
          if (res) process.stdout.write(JSON.stringify(res) + '\n')
        }).catch(err => {
          log(`RPC error: ${err.message}`)
        })
      } catch (err) {
        log(`Parse error: ${err.message}`)
      }
    }
  }
}

// ── HTTP transport ────────────────────────────────────────────────────────────
function startHttp() {
  log(`Sovereign MCP server starting (HTTP mode) on port ${PORT}`)

  const server = createServer(async (httpReq, httpRes) => {
    if (httpReq.method === 'OPTIONS') {
      httpRes.writeHead(204, {
        'Access-Control-Allow-Origin':  '*',
        'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, x-bot-secret',
      })
      httpRes.end(); return
    }

    let body = ''
    httpReq.on('data', c => { body += c })
    httpReq.on('end', async () => {
      httpRes.setHeader('Content-Type', 'application/json')
      httpRes.setHeader('Access-Control-Allow-Origin', '*')
      try {
        const msg = JSON.parse(body)
        const res = await handleRpc(msg)
        httpRes.writeHead(200)
        httpRes.end(JSON.stringify(res ?? { ok: true }))
      } catch (err) {
        httpRes.writeHead(400)
        httpRes.end(JSON.stringify({ error: err.message }))
      }
    })
  })

  server.listen(PORT, () => log(`HTTP server live on http://localhost:${PORT}`))
}

// ── Entry ─────────────────────────────────────────────────────────────────────
if (HTTP_MODE) startHttp()
else           startStdio()