snapkitty
hardware
erlang
File size: 11,311 Bytes
b8a03fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env node
import { readdirSync, statSync, mkdirSync, readFileSync } from 'node:fs'
import { createServer } from 'node:net'
import { createHash } from 'node:crypto'
import { join, relative, dirname, basename, extname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { createRequire } from 'node:module'

import { verifyOnce } from './icp-verifier.mjs'
import { run as runMetrics } from './metric-stream.mjs'
import { run as runBifrost } from './bifrost-translator.mjs'
import { run as runWatermark } from './watermark.mjs'
import { sealEvent } from './worm-chain.mjs'

const __dir = dirname(fileURLToPath(import.meta.url))
const ROOT = join(__dir, '..')
const PAGES = join(ROOT, 'pages')
const OUT = join(ROOT, 'bifrost-out')
const PUBLIC = join(ROOT, 'public')
const GOVERNANCE = join(ROOT, 'governance', 'shadow-orchestrator.pl')
const DAY_MS = 24 * 60 * 60 * 1000
const require = createRequire(import.meta.url)
const pl = require('tau-prolog')

let tick = 0
let running = false
const relaySockets = new Set()

function parseArgs() {
  const args = process.argv.slice(2)
  const intervalIdx = args.indexOf('--interval')
  return {
    once: args.includes('--once'),
    interval: intervalIdx >= 0 ? parseInt(args[intervalIdx + 1], 10) : parseInt(process.env.ORCHESTRATE_INTERVAL_MS || '30000', 10),
  }
}

function walk(dir, match, files = []) {
  const stack = [dir]
  while (stack.length) {
    const current = stack.pop()
    let entries = []
    try { entries = readdirSync(current) } catch { continue }
    for (const entry of entries) {
      const full = join(current, entry)
      let stat
      try { stat = statSync(full) } catch { continue }
      if (stat.isDirectory()) stack.push(full)
      else if (match(full, stat)) files.push(full)
    }
  }
  return files
}

function recentPageSources() {
  const cutoff = Date.now() - DAY_MS
  return walk(PAGES, (file, stat) => extname(file) === '.ts' && stat.mtimeMs >= cutoff)
}

function outFiles() {
  return new Set(walk(OUT, file => true).map(file => relative(OUT, file)))
}

function prefixForSource(source) {
  const rel = relative(PAGES, source)
  const parts = rel.split(/[\\/]/).filter(Boolean)
  const stem = basename(source).replace(/\.[^.]+$/, '')
  const scope = parts.length > 1 ? parts.slice(0, -1).join('-') : 'page'
  return stem === 'index' ? `${scope}-` : `${scope}-`
}

async function quiet(fn) {
  const out = console.log
  const err = console.error
  console.log = (...args) => err(...args)
  console.error = (...args) => err(...args)
  try { return await fn() }
  finally {
    console.log = out
    console.error = err
  }
}

function prologAtom(value) {
  return `'${String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`
}

function queryGovernance(goal) {
  const program = readFileSync(GOVERNANCE, 'utf8')
  return new Promise((resolve, reject) => {
    const session = pl.create(1000)
    session.consult(program, {
      success: () => {
        session.query(goal, {
          success: () => {
            session.answer(answer => resolve(answer !== false))
          },
          error: reject,
        })
      },
      error: reject,
    })
  })
}

async function agentAllowed(name, phase) {
  return queryGovernance(`agent_allowed(${prologAtom(name)}, ${prologAtom(phase)}).`)
}

async function statusAllowed(name, status) {
  return queryGovernance(`status_verdict(${prologAtom(name)}, ${prologAtom(status)}, 'ALLOW').`)
}

async function dispatchGate(type) {
  const allowed = await queryGovernance(`dispatch_verdict(${prologAtom(type)}, 'resurrect', 'ACCEPTED').`)
  return { allowed, agent: 'resurrect', status: allowed ? 'ACCEPTED' : 'REJECTED' }
}

async function sealed(name, status, payload = {}) {
  const allowed = await statusAllowed(name, status)
  const finalStatus = allowed ? status : 'REJECTED'
  const governance = allowed ? 'tau-prolog:allow' : 'tau-prolog:reject'
  const { seal } = sealEvent(name, 'agent-result', { status: finalStatus, governance, ...payload })
  return { name, status: finalStatus, seal, governance }
}

async function requireAgent(name, phase) {
  if (await agentAllowed(name, phase)) return
  throw new Error(`tau_prolog_denied:${phase}:${name}`)
}

function writeJsonLine(message) {
  const line = JSON.stringify(message) + '\n'
  process.stdout.write(line)
  for (const socket of relaySockets) {
    if (!socket.destroyed) socket.write(encodeWsFrame(JSON.stringify(message)))
  }
}

async function runTick() {
  if (running) return
  running = true
  tick += 1
  const ts = new Date().toISOString()
  const agents = []

  try {
    mkdirSync(PUBLIC, { recursive: true })
    mkdirSync(OUT, { recursive: true })

    await requireAgent('icp-verifier', 'tick')
    const icp = await quiet(() => verifyOnce({}))
    if (icp.status === 'DRIFT_DETECTED') {
      const incident = sealEvent('ORCHESTRATOR', 'icp-drift-incident', { tick, ts, icp })
      agents.push(await sealed('icp-verifier', 'DRIFT_DETECTED', { internalSeal: incident.seal }))
      writeJsonLine({ tick, ts, agents })
      return
    }
    agents.push(await sealed('icp-verifier', icp.status || 'VERIFIED', { internalSeal: icp.seal }))

    await requireAgent('metric-stream', 'tick')
    const metrics = await quiet(() => runMetrics({
      repoPath: ROOT,
      outPath: join(PUBLIC, 'metrics.json'),
    }))
    agents.push(await sealed('metric-stream', 'UPDATED', { internalSeal: metrics.wormSeal }))

    await requireAgent('bifrost-translator', 'tick')
    const before = outFiles()
    const sources = recentPageSources()
    const translations = []
    for (const sourcePath of sources) {
      const result = await quiet(() => runBifrost({
        sourcePath,
        targets: ['rust', 'lean4'],
        outDir: OUT,
        namePrefix: prefixForSource(sourcePath),
      }))
      translations.push(result)
    }
    agents.push(await sealed('bifrost-translator', sources.length ? 'TRANSLATED' : 'IDLE', {
      files: sources.length,
      internalSeals: translations.map(r => r.seal).filter(Boolean),
    }))

    await requireAgent('watermark', 'tick')
    const after = outFiles()
    const newFiles = [...after].filter(file => !before.has(file))
    const watermark = await quiet(() => runWatermark({ target: OUT }))
    agents.push(await sealed('watermark', watermark.marks.length ? 'WATERMARKED' : 'IDLE', {
      files: newFiles,
      filesMarked: watermark.marks.length,
      internalSeal: watermark.seal,
    }))

    writeJsonLine({ tick, ts, agents })
  } catch (error) {
    const incident = sealEvent('ORCHESTRATOR', 'tick-error', { tick, ts, message: error.message })
    agents.push(await sealed('orchestrator', 'ERROR', { internalSeal: incident.seal, message: error.message }))
    writeJsonLine({ tick, ts, agents })
  } finally {
    running = false
  }
}

function encodeWsFrame(text) {
  const body = Buffer.from(text)
  if (body.length < 126) return Buffer.concat([Buffer.from([0x81, body.length]), body])
  if (body.length <= 0xffff) {
    const header = Buffer.alloc(4)
    header[0] = 0x81
    header[1] = 126
    header.writeUInt16BE(body.length, 2)
    return Buffer.concat([header, body])
  }
  const header = Buffer.alloc(10)
  header[0] = 0x81
  header[1] = 127
  header.writeBigUInt64BE(BigInt(body.length), 2)
  return Buffer.concat([header, body])
}

function decodeWsFrame(buffer) {
  if (buffer.length < 2) return null
  const opcode = buffer[0] & 0x0f
  if (opcode === 0x8) return { close: true }
  const masked = (buffer[1] & 0x80) !== 0
  let len = buffer[1] & 0x7f
  let offset = 2
  if (len === 126) {
    if (buffer.length < 4) return null
    len = buffer.readUInt16BE(2)
    offset = 4
  } else if (len === 127) {
    if (buffer.length < 10) return null
    len = Number(buffer.readBigUInt64BE(2))
    offset = 10
  }
  const maskOffset = offset
  if (masked) offset += 4
  if (buffer.length < offset + len) return null
  const payload = Buffer.from(buffer.slice(offset, offset + len))
  if (masked) {
    const mask = buffer.slice(maskOffset, maskOffset + 4)
    for (let i = 0; i < payload.length; i += 1) payload[i] ^= mask[i % 4]
  }
  return { text: payload.toString('utf8') }
}

function acceptHandshake(socket, request) {
  const key = request.match(/Sec-WebSocket-Key:\s*(.+)\r?\n/i)?.[1]?.trim()
  if (!key) {
    socket.destroy()
    return false
  }
  const accept = createHash('sha1')
    .update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
    .digest('base64')
  socket.write(
    'HTTP/1.1 101 Switching Protocols\r\n' +
    'Upgrade: websocket\r\n' +
    'Connection: Upgrade\r\n' +
    `Sec-WebSocket-Accept: ${accept}\r\n\r\n`
  )
  relaySockets.add(socket)
  socket.once('close', () => relaySockets.delete(socket))
  socket.once('error', () => relaySockets.delete(socket))
  return true
}

async function handleRelayMessage(text) {
  let message
  try { message = JSON.parse(text) } catch { return }
  if (typeof message.type !== 'string' || !message.type.endsWith(':dispatch')) return

  tick += 1
  const ts = new Date().toISOString()
  const gate = await dispatchGate(message.type)
  if (!gate.allowed) {
    const rejected = await sealed(gate.agent, gate.status, {
      repo: message.repo,
      dryRun: Boolean(message.dryRun),
      reason: 'tau_prolog_dispatch_denied',
    })
    writeJsonLine({
      tick,
      ts,
      type: 'ransom_worm:rejected',
      repo: message.repo,
      dryRun: Boolean(message.dryRun),
      agents: [rejected],
    })
    return
  }

  const accepted = await sealed(gate.agent, gate.status, {
    repo: message.repo,
    dryRun: Boolean(message.dryRun),
  })
  writeJsonLine({
    tick,
    ts,
    type: 'ransom_worm:accepted',
    repo: message.repo,
    dryRun: Boolean(message.dryRun),
    agents: [accepted],
  })
}

function startRelay(port) {
  const server = createServer(socket => {
    let handshaken = false
    let pending = Buffer.alloc(0)

    socket.on('data', chunk => {
      if (!handshaken) {
        const request = chunk.toString('utf8')
        if (!request.includes('\r\n\r\n')) return
        handshaken = acceptHandshake(socket, request)
        return
      }

      pending = Buffer.concat([pending, chunk])
      const frame = decodeWsFrame(pending)
      if (!frame) return
      pending = Buffer.alloc(0)
      if (frame.close) {
        socket.end()
        return
      }
      handleRelayMessage(frame.text).catch(error => {
        const incident = sealEvent('ORCHESTRATOR', 'relay-error', { message: error.message })
        writeJsonLine({
          tick,
          ts: new Date().toISOString(),
          type: 'relay:error',
          message: error.message,
          seal: incident.seal,
        })
      })
    })
  })

  server.listen(port, '127.0.0.1', () => {
    const address = server.address()
    const boundPort = typeof address === 'object' && address ? address.port : port
    writeJsonLine({ type: 'relay:ready', port: boundPort })
  })
  server.on('error', error => {
    writeJsonLine({ type: 'relay:error', message: error.message })
  })
}

function start() {
  const args = parseArgs()
  const relayPort = Number.parseInt(process.env.ORCHESTRATE_WS_PORT || '', 10)
  if (Number.isInteger(relayPort)) startRelay(relayPort)
  runTick()
  if (!args.once) setInterval(runTick, args.interval)
}

start()