diff --git a/scripts/check-syntax.cjs b/scripts/check-syntax.cjs deleted file mode 100644 index f08990b..0000000 --- a/scripts/check-syntax.cjs +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env node -"use strict"; - -const fs = require("fs"); -const path = require("path"); -const { spawnSync } = require("child_process"); - -const repoRoot = path.resolve(__dirname, ".."); -const files = []; - -collect(path.join(repoRoot, "src")); - -for (const file of files) { - const result = spawnSync(process.execPath, ["--check", file], { - cwd: repoRoot, - encoding: "utf8", - }); - if (result.stdout) process.stdout.write(result.stdout); - if (result.stderr) process.stderr.write(result.stderr); - if (result.status !== 0) process.exit(result.status); -} - -console.log(`Checked ${files.length} CommonJS files.`); - -function collect(directory) { - for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { - const fullPath = path.join(directory, entry.name); - if (entry.isDirectory()) { - collect(fullPath); - } else if (entry.isFile() && entry.name.endsWith(".cjs")) { - files.push(fullPath); - } - } -} diff --git a/src/odin-coordinator.cjs b/src/odin-coordinator.cjs deleted file mode 100644 index 66b4ec4..0000000 --- a/src/odin-coordinator.cjs +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/env node -"use strict"; - -const fs = require("fs"); -const path = require("path"); - -const { buildConfig, loadCultRuntime } = require("./odin/config.cjs"); -const { createCultMeshRudpDocumentServer } = require("./odin/cultnet-rudp.cjs"); -const { defineOdinDocuments } = require("./odin/documents.cjs"); -const { createInterfaceDiscovery } = require("./odin/interfaces.cjs"); -const { createIdunnRudpHealthPublisher, publishIdunnRudpHealth } = require("./odin/idunn-rudp.cjs"); -const { createLayoutStore } = require("./odin/layout.cjs"); -const { createLiveProviderRegistry } = require("./odin/provider-ingress.cjs"); -const { createStateBuilder } = require("./odin/state.cjs"); - -const config = buildConfig(process.argv.slice(2)); -fs.mkdirSync(config.stateDir, { recursive: true }); -const idunnRudpHealthPublisher = createIdunnRudpHealthPublisher(config.idunnRudpHealth); - -const cultRuntime = loadCultRuntime(); -if (cultRuntime.error) { - console.error("CultMesh runtime unavailable; durable mesh catalog disabled:", cultRuntime.error.message); -} - -const documents = defineOdinDocuments(cultRuntime.defineDocumentType); -const allDocumentDefinitions = Object.values(documents).filter(Boolean); -const layoutStore = createLayoutStore({ - definition: documents.interfaceLayoutDefinition, - getNode: async () => meshNodePromise ? await meshNodePromise : null, - layoutPath: config.layoutPath, -}); -const liveProviderRegistry = createLiveProviderRegistry(); -const interfaceDiscovery = createInterfaceDiscovery({ - CultMesh: cultRuntime.CultMesh, - documents, - interfaceBindingStores: config.interfaceBindingStores, - liveProviderRegistry, -}); -const stateBuilder = createStateBuilder({ - cachePath: config.cachePath, - gamecultTextDocumentStorePath: config.gamecultTextDocumentStorePath, - interfaceDiscovery, - layoutStore, - stonksBurstSize: config.stonksBurstSize, -}); - -let meshNodePromise = null; -let cultMeshRudpDocumentServer = null; -let currentState = stateBuilder.buildPendingState("Coordinator starting"); -let lastRefresh = { - completedAt: null, - durationMs: null, - error: null, - startedAt: null, -}; -let lastIdunnRudpHealthPublishedAt = null; -let observedRudpDocuments = 0; - -main().catch((error) => { - console.error(error); - process.exitCode = 1; -}); - -async function main() { - if (cultRuntime.CultMesh && documents.surfaceDefinition) { - meshNodePromise = createDurableSurfaceNode(); - } - if (config.cultnetRudpBind) { - cultMeshRudpDocumentServer = createCultMeshRudpDocumentServer({ - CultMesh: cultRuntime.CultMesh, - bind: config.cultnetRudpBind, - documents, - getCache: async () => { - if (!meshNodePromise) { - throw new Error("CultMesh runtime is unavailable; Odin cannot serve a CultMesh/RUDP document catalog."); - } - return (await meshNodePromise).cache; - }, - onDocumentPutRaw: async (document) => { - if (observedRudpDocuments < 40) { - observedRudpDocuments += 1; - console.error( - `Odin RUDP document #${observedRudpDocuments} schema=${document.schemaId} key=${document.recordKey} source=${document.sourceRuntimeId || "unknown"} remote=${document.remote?.address}:${document.remote?.port}`, - ); - } - liveProviderRegistry.ingestDocument(document, document.remote); - await persistRudpDocumentPut(document); - }, - }); - await cultMeshRudpDocumentServer.start(); - console.log(`CultMesh/RUDP document catalog: ${config.cultnetRudpBind}`); - } - - console.log(`Durable surface cache: ${config.cachePath}`); - - await refresh(); - scheduleRefresh(); -} - -async function persistRudpDocumentPut(document) { - if (!meshNodePromise || !document?.schemaId || !document?.recordKey) return; - const definition = documentDefinitionForSchema(document.schemaId); - if (!definition) return; - const node = await meshNodePromise; - await node.put(definition, document.recordKey, normalizeRudpPayload(document.payload)); -} - -function documentDefinitionForSchema(schemaId) { - return allDocumentDefinitions.find((definition) => - definition?.schemaId === schemaId - || definition?.schemaVersion === schemaId - || definition?.schemaName === schemaId - || definition?.type === schemaId - ); -} - -function normalizeRudpPayload(payload) { - if (Array.isArray(payload) && payload.length === 1 && payload[0] && typeof payload[0] === "object" && !Array.isArray(payload[0])) { - return payload[0]; - } - return payload; -} - -function scheduleRefresh() { - setTimeout(() => { - refresh() - .catch((error) => console.error("refresh failed:", error)) - .finally(() => scheduleRefresh()); - }, config.intervalMs); -} - -async function createDurableSurfaceNode() { - try { - return await cultRuntime.CultMesh.createNode(config.cachePath, { documents: allDocumentDefinitions }); - } catch (error) { - if (!fs.existsSync(config.cachePath)) { - throw error; - } - - const corruptPath = `${config.cachePath}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`; - fs.renameSync(config.cachePath, corruptPath); - console.error(`CultMesh surface cache was unreadable and has been quarantined: ${corruptPath}`); - console.error(`CultMesh surface cache read error: ${error.message}`); - return cultRuntime.CultMesh.createNode(config.cachePath, { documents: allDocumentDefinitions }); - } -} - -async function refresh() { - const started = Date.now(); - lastRefresh = { - completedAt: null, - durationMs: null, - error: null, - startedAt: new Date(started).toISOString(), - }; - try { - currentState = await stateBuilder.buildState(); - await persistState(currentState); - lastRefresh = { - completedAt: new Date().toISOString(), - durationMs: Date.now() - started, - error: null, - startedAt: new Date(started).toISOString(), - }; - await publishOdinHealth("active", `Odin provider catalog refreshed in ${lastRefresh.durationMs}ms`); - } catch (error) { - lastRefresh = { - completedAt: new Date().toISOString(), - durationMs: Date.now() - started, - error: error.message, - startedAt: new Date(started).toISOString(), - }; - await publishOdinHealth("failed", `Odin provider refresh failed: ${error.message}`); - throw error; - } -} - -async function publishOdinHealth(state, detail) { - if (!idunnRudpHealthPublisher) return; - try { - await publishIdunnRudpHealth(idunnRudpHealthPublisher, { - state, - detail, - observedAt: new Date().toISOString(), - }); - lastIdunnRudpHealthPublishedAt = Date.now(); - } catch (error) { - const lastPublishedAgeMs = lastIdunnRudpHealthPublishedAt === null - ? Number.POSITIVE_INFINITY - : Date.now() - lastIdunnRudpHealthPublishedAt; - if (lastPublishedAgeMs > Math.max(60_000, config.intervalMs * 4)) { - console.error("Idunn RUDP health publish failed:", error.message); - } - } -} - -async function persistState(state) { - if (config.writeDebugSurfaceJson) { - fs.writeFileSync(path.join(config.stateDir, "latest-surface.json"), JSON.stringify(state, null, 2), "utf8"); - } - if (!meshNodePromise || !documents.surfaceDefinition) { - return; - } - - try { - const node = await meshNodePromise; - await node.put(documents.surfaceDefinition, config.surfaceKey, state); - await node.flush?.(true); - } catch (error) { - console.error("CultMesh snapshot write failed:", error.message); - } -} diff --git a/src/odin/config.cjs b/src/odin/config.cjs deleted file mode 100644 index e9df2b4..0000000 --- a/src/odin/config.cjs +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; - -const Module = require("module"); -const path = require("path"); -const { parseArgs } = require("./utils.cjs"); - -const repoRoot = path.resolve(__dirname, "..", ".."); - -process.env.NODE_PATH = [ - path.resolve(repoRoot, "..", "CultLib", "packages"), - process.env.NODE_PATH || "", -].filter(Boolean).join(path.delimiter); -Module._initPaths(); - -function buildConfig(argv) { - const args = parseArgs(argv); - const cultnetRudpBind = args["cultnet-rudp-bind"] ? String(args["cultnet-rudp-bind"]) : ""; - const intervalMs = Number(args.intervalMs || 5000); - const stateDir = args.stateDir || path.join(repoRoot, "scratch", "odin"); - const cachePath = args.cachePath || path.join(stateDir, "odin.ccmp"); - const layoutPath = args.layoutPath || path.join(stateDir, "interface-layout.json"); - const writeDebugSurfaceJson = Boolean(args.writeDebugSurfaceJson || args["write-debug-surface-json"] || process.env.ODIN_WRITE_DEBUG_SURFACE_JSON === "1"); - if (args.observationLogPath || args.observationFreshSeconds) { - throw new Error("Odin no longer tails Mimir observation logs. Publish observation records through CultMesh/Odin provider discovery instead."); - } - const gamecultTextDocumentStorePath = args.gamecultTextDocumentStorePath || path.join(repoRoot, "..", "VoidBot", ".voidbot", "private", "gamecult-text-documents.cc"); - const stonksBurstSize = Math.max(1, Number(args.stonksBurstSize || 8)); - const idunnRudpHealth = args["idunn-rudp-health"] ? { - endpoint: String(args["idunn-rudp-health"]), - daemonId: String(args["idunn-daemon"] || "odin"), - healthContract: String(args["idunn-health-contract"] || "odin.cultnet-rudp-provider-health"), - privateKeyPath: args["idunn-health-private-key"] - ? String(args["idunn-health-private-key"]) - : "", - sourceRuntimeId: String(args["idunn-source-runtime"] || "odin-coordinator"), - } : null; - const interfaceBindingStores = String( - args.interfaceBindingStore || - process.env.ODIN_INTERFACE_BINDING_STORES || - "", - ) - .split(",") - .map((entry) => entry.trim()) - .filter(Boolean); - - return { - args, - cachePath, - cultnetRudpBind, - gamecultTextDocumentStorePath, - interfaceBindingStores, - idunnRudpHealth, - intervalMs, - layoutPath, - repoRoot, - stateDir, - stonksBurstSize, - surfaceKey: "surface:gamecult.network.status", - writeDebugSurfaceJson, - }; -} - -function loadCultRuntime() { - try { - const { CultMesh } = require("cultmesh-ts"); - const { defineDocumentType } = require("cultcache-ts"); - return { CultMesh, defineDocumentType, error: null }; - } catch (error) { - return { CultMesh: null, defineDocumentType: null, error }; - } -} - -module.exports = { buildConfig, loadCultRuntime, repoRoot }; diff --git a/src/odin/cultnet-rudp.cjs b/src/odin/cultnet-rudp.cjs deleted file mode 100644 index 05b290e..0000000 --- a/src/odin/cultnet-rudp.cjs +++ /dev/null @@ -1,115 +0,0 @@ -"use strict"; - -const path = require("path"); -const { createRequire } = require("module"); -const { createSocket } = require("dgram"); - -const requireCultNet = createRequire(path.resolve( - __dirname, - "..", - "..", - "..", - "CultLib", - "packages", - "cultnet-ts", - "package.json", -)); - -const { - CultNetDocumentRegistry, - decodeRudpPacket, - defineCultNetDocumentBinding, -} = requireCultNet("./dist/index.js"); - -const ODIN_RUDP_CONNECTION_ID = 0x0d1d0002; - -function createCultMeshRudpDocumentServer(options) { - if (!options?.bind) return null; - if (!options.CultMesh?.createRudpDocumentServer) { - throw new Error("Odin requires a CultMesh runtime with createRudpDocumentServer."); - } - if (!options.documents?.surfaceDefinition) { - throw new Error("Odin CultMesh/RUDP document server requires a surface document definition."); - } - if (typeof options.getCache !== "function") { - throw new Error("Odin CultMesh/RUDP document server requires an async getCache function."); - } - - const bind = parseEndpoint(options.bind); - const socket = createSocket(bind.host.includes(":") ? "udp6" : "udp4"); - let observedPackets = 0; - socket.on("message", (wire, remote) => { - if (observedPackets >= 20) return; - observedPackets += 1; - try { - const packet = decodeRudpPacket(wire); - console.error( - `Odin RUDP observed packet #${observedPackets} ${packet.packetType} connection=${packet.connectionId.toString(16)} channel=${packet.channelId} from ${remote.address}:${remote.port} bytes=${wire.length}`, - ); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - console.error( - `Odin RUDP observed undecodable packet #${observedPackets} from ${remote.address}:${remote.port} bytes=${wire.length}: ${message}`, - ); - } - }); - const registry = new CultNetDocumentRegistry( - Object.values(options.documents) - .filter(Boolean) - .map((definition) => defineCultNetDocumentBinding({ definition })), - ); - const server = options.CultMesh.createRudpDocumentServer( - "odin-cultmesh-catalog", - ODIN_RUDP_CONNECTION_ID, - { - bindHost: bind.host, - bindPort: bind.port, - documents: registry, - socket, - getCache: options.getCache, - onError: (error) => { - const message = error instanceof Error ? error.message : String(error); - if (typeof options.logError === "function") { - options.logError(`CultMesh/RUDP document server error: ${message}`); - return; - } - console.error(`CultMesh/RUDP document server error: ${message}`); - }, - onDocumentPutRaw: (document) => { - if (typeof options.onDocumentPutRaw === "function") { - return options.onDocumentPutRaw(document); - } - return undefined; - }, - }, - ); - - return { - bind, - start: () => server.start(), - close: () => server.close(), - }; -} - -function parseEndpoint(value) { - const text = String(value || "").trim(); - const ipv6 = text.match(/^\[([^\]]+)\]:(\d+)$/); - if (ipv6) return { host: ipv6[1], port: parsePort(ipv6[2]) }; - const index = text.lastIndexOf(":"); - if (index <= 0) { - throw new Error(`CultMesh/RUDP bind must be host:port, got "${value}".`); - } - return { host: text.slice(0, index), port: parsePort(text.slice(index + 1)) }; -} - -function parsePort(value) { - const port = Number(value); - if (!Number.isInteger(port) || port <= 0 || port > 65535) { - throw new Error(`CultMesh/RUDP port is invalid: ${value}`); - } - return port; -} - -module.exports = { - createCultMeshRudpDocumentServer, -}; diff --git a/src/odin/documents.cjs b/src/odin/documents.cjs deleted file mode 100644 index 4cf9cfa..0000000 --- a/src/odin/documents.cjs +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; - -// The swarm document-type catalog, as Odin consumes it. -// -// The 45 definitions used to live here. Almost none of them are Odin's: they -// describe documents that cross service boundaries, and every service that -// decodes another's documents needs the same ones. They lived here because Odin -// was written first. They now live in CultLib as cultcache-ts's -// defineSwarmDocuments, beside the defineDocumentType that builds them, so -// Hermodr can leave without forking a second definition of one wire format. - -const path = require("path"); -const { createRequire } = require("module"); - -const cultLibRoot = process.env.CULTLIB_ROOT - ? path.resolve(process.env.CULTLIB_ROOT) - : path.resolve(__dirname, "..", "..", "..", "CultLib"); - -const requireCultCache = createRequire(path.resolve(cultLibRoot, "packages", "cultcache-ts", "package.json")); - -const { defineSwarmDocuments } = requireCultCache("./dist/index.js"); - -// Odin's consumers know this name. The catalog is not Odin's, but the call is. -const defineOdinDocuments = defineSwarmDocuments; - -module.exports = { defineOdinDocuments, defineSwarmDocuments }; diff --git a/src/odin/idunn-rudp.cjs b/src/odin/idunn-rudp.cjs deleted file mode 100644 index 180d46f..0000000 --- a/src/odin/idunn-rudp.cjs +++ /dev/null @@ -1,65 +0,0 @@ -"use strict"; - -// Idunn health publication, as Odin consumes it. -// -// The transport used to live here: 300-odd lines of socket handling, RUDP -// handshaking, Ed25519 signing, and packet receipt, of which almost nothing was -// about Idunn. That is generic CultNet client work and now lives in CultLib as -// cultnet-ts's signed-daemon-health module. -// -// What remains is what Odin actually needs to know: Idunn's wire contract, and -// the shape of the calls its consumers already make. The constants are defined -// by Idunn in docs/signed-daemon-health-authority.md. They are declared here, -// not decided here; if they change, that document changes first. - -const path = require("path"); -const { createRequire } = require("module"); - -const cultLibRoot = process.env.CULTLIB_ROOT - ? path.resolve(process.env.CULTLIB_ROOT) - : path.resolve(__dirname, "..", "..", "..", "CultLib"); - -const requireCultNet = createRequire(path.resolve(cultLibRoot, "packages", "cultnet-ts", "package.json")); - -const { - CULTNET_RUDP_PROTOCOL_ID, - createSignedDaemonHealthPublisher, - publishSignedDaemonHealth, - signedDaemonHealthPayload, - signedDaemonHealthSigningMessage, -} = requireCultNet("./dist/index.js"); - -// Idunn's contract. Owner: GameCult/Idunn, docs/signed-daemon-health-authority.md. -const IDUNN_HEALTH_CONTRACT = Object.freeze({ - connectionId: 0x1d0d0001, - signedSchemaId: "idunn.signed_daemon_health.v1", - unsignedSchemaId: "idunn.daemon_health", - messageIdPrefix: "odin-health", -}); - -function createIdunnRudpHealthPublisher(options) { - if (!options) return null; - return createSignedDaemonHealthPublisher({ - sourceRuntimeId: "odin-coordinator", - ...options, - contract: IDUNN_HEALTH_CONTRACT, - }); -} - -const publishIdunnRudpHealth = publishSignedDaemonHealth; -const signedHealthPayload = signedDaemonHealthPayload; - -// The signing purpose is Idunn's signed schema id, so a statement signed for -// Idunn cannot verify as another service's health. -function signingMessage(payload) { - return signedDaemonHealthSigningMessage(IDUNN_HEALTH_CONTRACT.signedSchemaId, payload); -} - -module.exports = { - CULTNET_RUDP_PROTOCOL_ID, - IDUNN_HEALTH_CONTRACT, - createIdunnRudpHealthPublisher, - publishIdunnRudpHealth, - signedHealthPayload, - signingMessage, -}; diff --git a/src/odin/interfaces.cjs b/src/odin/interfaces.cjs deleted file mode 100644 index 43ffabd..0000000 --- a/src/odin/interfaces.cjs +++ /dev/null @@ -1,1179 +0,0 @@ -"use strict"; - -const fs = require("fs"); -const { createRequire } = require("module"); -const path = require("path"); -const { fileURLToPath } = require("url"); -const { stableId } = require("./utils.cjs"); - -const requireCultCacheInspection = createRequire( - path.resolve(__dirname, "..", "..", "..", "CultLib", "packages", "cultcache-ts", "package.json"), -); -const { inspectCultCacheBytes } = requireCultCacheInspection("./dist/cult-cache-inspector.js"); - -function createInterfaceDiscovery({ - CultMesh, - documents, - interfaceBindingStores, - liveProviderRegistry, -}) { - async function discoverInterfaces() { - const { interfaces } = await discoverAll(); - return interfaces; - } - - async function discoverProviderAdvertisements() { - const { providerAdvertisements } = await discoverAll(); - return providerAdvertisements; - } - - async function discoverAll() { - const { interfaces: cultMeshInterfaces, providerAdvertisements } = await discoverCultMeshEntries(); - const liveAnnouncements = liveProviderRegistry?.snapshot?.() || { - interfaces: [], - providerAdvertisements: [], - }; - - const interfaces = []; - for (const entry of [...cultMeshInterfaces, ...liveAnnouncements.interfaces]) { - const existingIndex = interfaces.findIndex((candidate) => candidate.providerId === entry.providerId); - if (existingIndex >= 0) { - interfaces[existingIndex] = entry; - } else { - interfaces.push(entry); - } - } - interfaces.sort((left, right) => left.providerId.localeCompare(right.providerId)); - const allProviderAdvertisements = [...providerAdvertisements, ...liveAnnouncements.providerAdvertisements]; - const providersById = new Map(); - for (const provider of allProviderAdvertisements) { - if (provider?.id) { - const existing = providersById.get(String(provider.id)); - providersById.set(String(provider.id), mergeProviderAdvertisement(existing, provider)); - } - } - return { - interfaces, - providerAdvertisements: [...providersById.values()].sort((left, right) => String(left.id).localeCompare(String(right.id))), - }; - } - - function cultMeshDocumentsAvailable() { - const { - interfaceBindingDefinition, - idunnCommandBoundaryDefinition, - idunnDaemonHealthDefinition, - idunnTransportProfileDefinition, - muninnCaptureStreamDefinition, - muninnCommandBoundaryDefinition, - muninnMoveControllerStateDefinition, - muninnMoveIdentityDefinition, - muninnMoveLightCommandDefinition, - muninnMoveMarkerCandidateDefinition, - muninnObsStreamCatalogDefinition, - muninnQuestAccessDefinition, - muninnTelemetrySurfaceDefinition, - muninnTransportProfileDefinition, - operatorStateDefinition, - providerAdvertisementDefinition, - voidbotProviderCatalogDefinition, - stonksCommandBoundaryDefinition, - stonksMarketSnapshotDefinition, - stonksRequestEventDefinition, - stonksTransportProfileDefinition, - streamPixelsCommandBoundaryDefinition, - streamPixelsTransportProfileDefinition, - surfaceDefinition, - viliCommandBoundaryDefinition, - viliTransportProfileDefinition, - weksaCommandBoundaryDefinition, - weksaOperatorStateDefinition, - weksaTransportProfileDefinition, - voidbotSwarmSnapshotDefinition, - } = documents; - return Boolean( - CultMesh && - interfaceBindingDefinition && - idunnCommandBoundaryDefinition && - idunnDaemonHealthDefinition && - idunnTransportProfileDefinition && - muninnCaptureStreamDefinition && - muninnCommandBoundaryDefinition && - muninnMoveControllerStateDefinition && - muninnMoveIdentityDefinition && - muninnMoveLightCommandDefinition && - muninnMoveMarkerCandidateDefinition && - muninnObsStreamCatalogDefinition && - muninnQuestAccessDefinition && - muninnTelemetrySurfaceDefinition && - muninnTransportProfileDefinition && - operatorStateDefinition && - providerAdvertisementDefinition && - voidbotProviderCatalogDefinition && - stonksCommandBoundaryDefinition && - stonksMarketSnapshotDefinition && - stonksRequestEventDefinition && - stonksTransportProfileDefinition && - streamPixelsCommandBoundaryDefinition && - streamPixelsTransportProfileDefinition && - surfaceDefinition && - viliCommandBoundaryDefinition && - viliTransportProfileDefinition && - weksaCommandBoundaryDefinition && - weksaOperatorStateDefinition && - weksaTransportProfileDefinition && - voidbotSwarmSnapshotDefinition - ); - } - - async function discoverCultMeshEntries() { - const { - interfaceBindingDefinition, - idunnCommandBoundaryDefinition, - idunnDaemonHealthDefinition, - idunnTransportProfileDefinition, - muninnCaptureStreamDefinition, - muninnCommandBoundaryDefinition, - muninnMoveControllerStateDefinition, - muninnMoveIdentityDefinition, - muninnMoveLightCommandDefinition, - muninnMoveMarkerCandidateDefinition, - muninnObsStreamCatalogDefinition, - muninnQuestAccessDefinition, - muninnTelemetrySurfaceDefinition, - muninnTransportProfileDefinition, - operatorStateDefinition, - providerAdvertisementDefinition, - voidbotProviderCatalogDefinition, - stonksCommandBoundaryDefinition, - stonksMarketSnapshotDefinition, - stonksRequestEventDefinition, - stonksTransportProfileDefinition, - streamPixelsCommandBoundaryDefinition, - streamPixelsTransportProfileDefinition, - surfaceDefinition, - viliCommandBoundaryDefinition, - viliTransportProfileDefinition, - weksaCommandBoundaryDefinition, - weksaOperatorStateDefinition, - weksaTransportProfileDefinition, - voidbotSwarmSnapshotDefinition, - } = documents; - if (!cultMeshDocumentsAvailable()) { - return { interfaces: [], providerAdvertisements: [] }; - } - - const nodeDocuments = [ - voidbotSwarmSnapshotDefinition, - stonksRequestEventDefinition, - stonksMarketSnapshotDefinition, - providerAdvertisementDefinition, - voidbotProviderCatalogDefinition, - interfaceBindingDefinition, - surfaceDefinition, - idunnCommandBoundaryDefinition, - idunnTransportProfileDefinition, - stonksCommandBoundaryDefinition, - stonksTransportProfileDefinition, - streamPixelsCommandBoundaryDefinition, - streamPixelsTransportProfileDefinition, - idunnDaemonHealthDefinition, - muninnCaptureStreamDefinition, - muninnCommandBoundaryDefinition, - muninnMoveControllerStateDefinition, - muninnMoveIdentityDefinition, - muninnMoveLightCommandDefinition, - muninnMoveMarkerCandidateDefinition, - muninnObsStreamCatalogDefinition, - muninnQuestAccessDefinition, - muninnTelemetrySurfaceDefinition, - muninnTransportProfileDefinition, - operatorStateDefinition, - viliCommandBoundaryDefinition, - viliTransportProfileDefinition, - weksaOperatorStateDefinition, - weksaCommandBoundaryDefinition, - weksaTransportProfileDefinition, - ]; - - const storeEntries = await Promise.all(interfaceBindingStores.map(async (storeSpec) => { - let resolvedStore = null; - try { - resolvedStore = resolveInterfaceBindingStore(storeSpec); - if (!resolvedStore) { - return { interfaces: [], providerAdvertisements: [] }; - } - const { localPath: storePath, sourceId } = resolvedStore; - if (!fs.existsSync(storePath)) { - return { interfaces: [], providerAdvertisements: [] }; - } - const node = await CultMesh.createNode(storePath, { documents: nodeDocuments }); - const typed = inspectCultMeshStore({ - documents, - interfaceBindingDefinition, - muninnTelemetrySurfaceDefinition, - node, - providerAdvertisementDefinition, - sourceId, - storePath, - }); - const inspected = inspectCultMeshStoreBytes(storePath, sourceId); - return { - interfaces: mergeInterfaces([...typed.interfaces, ...inspected.interfaces]), - providerAdvertisements: mergeProviderAdvertisements([ - ...typed.providerAdvertisements, - ...inspected.providerAdvertisements, - ]), - }; - } catch (error) { - const interfaces = []; - const providerAdvertisements = []; - if (resolvedStore?.localPath && fs.existsSync(resolvedStore.localPath)) { - try { - const inspected = inspectCultMeshStoreBytes(resolvedStore.localPath, resolvedStore.sourceId); - interfaces.push(...inspected.interfaces); - providerAdvertisements.push(...inspected.providerAdvertisements); - } catch (fallbackError) { - if (fallbackError?.code !== "ENOENT") { - throw fallbackError; - } - } - } - if (interfaces.length === 0) { - interfaces.push(dashboardUnavailable(`cultmesh:${storeSpec}`, `cultmesh:${storeSpec}`, error.message)); - } - return { interfaces, providerAdvertisements }; - } finally { - resolvedStore?.cleanup?.(); - } - })); - - return { - interfaces: storeEntries.flatMap((entry) => entry.interfaces), - providerAdvertisements: storeEntries.flatMap((entry) => entry.providerAdvertisements), - }; - } - - return { - discoverAll, - discoverProviderAdvertisements, - discoverInterfaces, - }; -} - -function cultMeshProviderInterface({ - advertisement, - state, - storePath, - operatorState = null, - commandBoundary = null, - transportProfile = null, -}) { - const surface = state.surface || null; - const providerId = advertisement.providerId || advertisement.provider?.id || advertisement.id || "unknown-provider"; - const title = state.title || advertisement.title || advertisement.provider?.title || providerId; - const endpoints = sanitizeProviderEndpoints(advertisement.endpoints); - const routes = sanitizeProviderEndpoints(advertisement.routes); - return { - providerId, - title, - state: "active", - detail: `${surface?.root?.kind || surface?.root?.type || "surface"} ${countSurfaceNodes(surface, state)} nodes via provider advertisement`, - version: state.version || 0, - updatedAt: state.updatedAt || advertisement.updatedAt || new Date().toISOString(), - source: `cultmesh:${storePath}`, - manifest: { - ...advertisement, - endpoints, - routes, - }, - canonicalService: advertisement.canonicalService || null, - locatedService: advertisement.locatedService || null, - cultMeshAddress: advertisement.cultMeshAddress || null, - endpoints, - routes, - operatorState, - commandBoundary, - transportProfile, - surface, - }; -} - -function inspectCultMeshStore({ - documents, - interfaceBindingDefinition, - muninnTelemetrySurfaceDefinition, - node, - providerAdvertisementDefinition, - sourceId, -}) { - const { - idunnCommandBoundaryDefinition, - idunnTransportProfileDefinition, - operatorStateDefinition, - stonksCommandBoundaryDefinition, - stonksTransportProfileDefinition, - streamPixelsCommandBoundaryDefinition, - streamPixelsTransportProfileDefinition, - surfaceDefinition, - viliCommandBoundaryDefinition, - viliTransportProfileDefinition, - weksaCommandBoundaryDefinition, - weksaOperatorStateDefinition, - weksaTransportProfileDefinition, - muninnCommandBoundaryDefinition, - muninnTransportProfileDefinition, - } = documents; - - const providerAdvertisements = []; - const interfaces = []; - const advertisements = typeof node.cache?.getAll === "function" - ? node.cache.getAll(providerAdvertisementDefinition).map(unwrapDocumentRecord) - : []; - - for (const advertisement of advertisements) { - const providerId = advertisement?.providerId || advertisement?.provider?.id || advertisement?.id; - if (!providerId) { - continue; - } - const endpoints = sanitizeProviderEndpoints(advertisement.endpoints); - const routes = sanitizeProviderEndpoints(advertisement.routes); - const providerEndpoint = advertisement.cultMeshAddress - || providerTypedEndpoint(routes) - || providerTypedEndpoint(endpoints) - || typedProviderEndpoint(advertisement.provider?.endpoint) - || `cultmesh:${sourceId}`; - providerAdvertisements.push({ - id: providerId, - title: advertisement.title || advertisement.provider?.title || providerId, - description: advertisement.description || "Provider-owned CultMesh advertisement.", - version: String(advertisement.version || 0), - endpoint: providerEndpoint, - canonicalService: advertisement.canonicalService || null, - locatedService: advertisement.locatedService || null, - cultMeshAddress: advertisement.cultMeshAddress || null, - endpoints, - routes, - inputStreams: Array.isArray(advertisement.inputStreams) ? advertisement.inputStreams : [], - activeStreams: Array.isArray(advertisement.activeStreams) ? advertisement.activeStreams : [], - availableSources: Array.isArray(advertisement.availableSources) ? advertisement.availableSources : [], - transportEndpoint: providerTypedEndpoint(routes) - || typedProviderEndpoint(advertisement.provider?.endpoint) - || providerEndpoint, - capabilities: advertisement.provider?.capabilities || advertisement.capabilities || [], - operatorState: providerRecord(node, [ - operatorStateDefinition, - weksaOperatorStateDefinition, - ], advertisement) || null, - commandBoundary: providerRecord(node, [ - idunnCommandBoundaryDefinition, - muninnCommandBoundaryDefinition, - viliCommandBoundaryDefinition, - weksaCommandBoundaryDefinition, - stonksCommandBoundaryDefinition, - streamPixelsCommandBoundaryDefinition, - ], advertisement) || null, - transportProfile: providerRecord(node, [ - idunnTransportProfileDefinition, - muninnTransportProfileDefinition, - viliTransportProfileDefinition, - weksaTransportProfileDefinition, - stonksTransportProfileDefinition, - streamPixelsTransportProfileDefinition, - ], advertisement) || null, - usesCultMesh: true, - transport: advertisement.provider?.transport || "CultMesh provider advertisement", - status: advertisement.status || "unknown", - updatedAt: advertisement.updatedAt || new Date().toISOString(), - source: `cultmesh:${sourceId}`, - commandSurface: advertisement.commandSurface || null, - }); - - const state = providerSurfaceState( - node, - advertisement, - surfaceDefinition, - muninnTelemetrySurfaceDefinition, - ); - if (state?.surface?.root) { - interfaces.push(cultMeshProviderInterface({ - advertisement, - state, - storePath: sourceId, - operatorState: providerRecord(node, [ - operatorStateDefinition, - weksaOperatorStateDefinition, - ], advertisement) || null, - commandBoundary: providerRecord(node, [ - idunnCommandBoundaryDefinition, - muninnCommandBoundaryDefinition, - viliCommandBoundaryDefinition, - weksaCommandBoundaryDefinition, - stonksCommandBoundaryDefinition, - streamPixelsCommandBoundaryDefinition, - ], advertisement) || null, - transportProfile: providerRecord(node, [ - idunnTransportProfileDefinition, - muninnTransportProfileDefinition, - viliTransportProfileDefinition, - weksaTransportProfileDefinition, - stonksTransportProfileDefinition, - streamPixelsTransportProfileDefinition, - ], advertisement) || null, - })); - } - } - - const bindings = typeof node.cache?.getAll === "function" - ? node.cache.getAll(interfaceBindingDefinition).map(unwrapDocumentRecord) - : [unwrapDocumentRecord(node.get(interfaceBindingDefinition, "voidbot.swarm"))].filter(Boolean); - for (const binding of bindings) { - if (!binding?.providerId) { - continue; - } - const state = unwrapDocumentRecord(node.get(surfaceDefinition, binding.providerId)); - const surface = state?.surface || binding.surface || null; - interfaces.push({ - providerId: binding.providerId, - title: binding.title || state?.title || binding.providerId, - state: "active", - detail: `${surface?.root?.kind || binding.kind || "surface"} ${countSurfaceNodes(surface, state)} nodes via CultMesh`, - version: state?.version || 0, - updatedAt: state?.updatedAt || binding.updatedAt || new Date().toISOString(), - source: `cultmesh:${sourceId}`, - manifest: binding.provider || null, - canonicalService: binding.provider?.canonicalService || null, - locatedService: binding.provider?.locatedService || null, - cultMeshAddress: binding.provider?.cultMeshAddress || binding.provider?.endpoint || null, - endpoints: sanitizeProviderEndpoints(binding.provider?.endpoints), - routes: sanitizeProviderEndpoints(binding.provider?.routes), - surface, - }); - } - - return { interfaces, providerAdvertisements }; -} - -function providerSurfaceState(node, advertisement, surfaceDefinition, muninnTelemetrySurfaceDefinition) { - const surfaceKeys = [ - advertisement.surfaceId, - advertisement.surface_id, - advertisement.providerId, - advertisement.provider?.id, - ].filter(Boolean); - for (const surfaceKey of [...new Set(surfaceKeys.map(String))]) { - const surfaceState = unwrapDocumentRecord(node.get?.(surfaceDefinition, surfaceKey)); - const providerId = surfaceState?.providerId || surfaceState?.provider_id; - const updatedAt = surfaceState?.updatedAt || surfaceState?.updated_at; - if (surfaceState?.surface?.root) { - return { - providerId: providerId || advertisement.providerId || advertisement.provider?.id || "unknown-provider", - title: surfaceState.title || advertisement.title || advertisement.provider?.title || advertisement.providerId || "unknown-provider", - version: Number(surfaceState.version || 0), - updatedAt: updatedAt || advertisement.updatedAt || new Date().toISOString(), - surface: surfaceState.surface, - }; - } - } - - const telemetryState = providerTelemetrySurfaceState(node, advertisement, muninnTelemetrySurfaceDefinition); - if (telemetryState) { - return telemetryState; - } - return null; -} - -function providerTelemetrySurfaceState(node, advertisement, muninnTelemetrySurfaceDefinition) { - if (!muninnTelemetrySurfaceDefinition) { - return null; - } - const keys = [ - advertisement.surfaceId, - advertisement.surface_id, - "latest", - ].filter(Boolean); - for (const key of keys) { - const record = unwrapDocumentRecord(node.get?.(muninnTelemetrySurfaceDefinition, key)); - const telemetryState = muninnTelemetryStateFromRecord(record, advertisement); - if (telemetryState) { - return telemetryState; - } - } - return null; -} - -function providerRecord(node, definitions, advertisement) { - const keys = providerRecordKeys(advertisement); - for (const definition of definitions) { - if (!definition) continue; - for (const key of keys) { - const record = unwrapDocumentRecord(node.get?.(definition, key)); - if (record) return record; - } - } - return null; -} - -function unwrapDocumentRecord(record) { - if (Array.isArray(record) && record.length === 1 && record[0] && typeof record[0] === "object") { - return record[0]; - } - return record; -} - -function providerRecordKeys(advertisement) { - const keys = [ - advertisement?.commandSurface?.commandBoundaryId, - advertisement?.commandSurface?.transportProfileId, - advertisement?.providerId, - advertisement?.daemonId, - advertisement?.daemon_id, - advertisement?.serviceId, - advertisement?.service_id, - advertisement?.provider?.id, - advertisement?.canonicalService, - advertisement?.locatedService, - ]; - if (advertisement?.providerId === "vili.animation") keys.push("vili"); - if (advertisement?.providerId === "weksa.intent.service") keys.push("weksa"); - if (advertisement?.providerId === "stonks.market") keys.push("stonks"); - if (advertisement?.provider?.id === "streampixels.service") keys.push("streampixels", "yggdrasil-streampixels"); - return [...new Set(keys.filter(Boolean).map(String))]; -} - -function inspectProviderAdvertisementsFromStore(storePath, sourceId) { - const inspection = inspectCultCacheBytes(storePath, fs.readFileSync(storePath)); - const records = inspection.records || []; - return records - .filter((record) => record.schemaName === "gamecult.eve.provider_advertisement") - .map((record) => buildInspectedProviderAdvertisement(record, records, sourceId)) - .filter(Boolean); -} - -function buildInspectedProviderAdvertisement(record, records, sourceId) { - const advertisement = normalizeInspectedProviderAdvertisement(record?.payloadPreview); - const providerId = advertisement?.providerId; - if (!providerId) { - return null; - } - const commandBoundary = inspectProviderCommandBoundary(providerId, records); - const transportProfile = inspectProviderTransportProfile(providerId, records); - const endpoints = sanitizeProviderEndpoints(advertisement.endpoints); - const routes = sanitizeProviderEndpoints(normalizeInspectedRoutes(advertisement)); - return { - id: providerId, - title: advertisement.title || providerId, - description: advertisement.description || "Provider-owned CultMesh advertisement.", - version: String(advertisement.version || 0), - endpoint: advertisement.cultMeshAddress || providerTypedEndpoint(endpoints) || `cultmesh:${sourceId}`, - canonicalService: advertisement.canonicalService || null, - locatedService: advertisement.locatedService || null, - cultMeshAddress: advertisement.cultMeshAddress || null, - endpoints, - routes, - inputStreams: Array.isArray(advertisement.inputStreams) ? advertisement.inputStreams : [], - activeStreams: Array.isArray(advertisement.activeStreams) ? advertisement.activeStreams : [], - availableSources: Array.isArray(advertisement.availableSources) ? advertisement.availableSources : [], - transportEndpoint: advertisement.cultMeshAddress || providerTypedEndpoint(routes) || providerTypedEndpoint(endpoints) || `cultmesh:${sourceId}`, - capabilities: advertisement.capabilities || [], - operatorState: null, - commandBoundary, - transportProfile, - usesCultMesh: true, - transport: "CultMesh provider advertisement", - status: advertisement.status || "unknown", - updatedAt: advertisement.updatedAt || new Date().toISOString(), - source: `cultmesh:${sourceId}`, - commandSurface: advertisement.commandSurface || null, - }; -} - -function inspectCultMeshInterfacesFromStore(storePath, sourceId) { - const inspection = inspectCultCacheBytes(storePath, fs.readFileSync(storePath)); - const records = inspection.records || []; - const providersById = new Map( - records - .filter((record) => record.schemaName === "gamecult.eve.provider_advertisement") - .map((record) => buildInspectedProviderAdvertisement(record, records, sourceId)) - .filter(Boolean) - .map((provider) => [provider.id, provider]), - ); - const surfaceInterfaces = records - .filter((record) => record.schemaName === "gamecult.eve.surface_state") - .map((record) => buildInspectedInterfaceFromSurfaceRecord( - record, - providersById, - sourceId, - records, - )) - .filter(Boolean); - const telemetryInterfaces = records - .filter((record) => record.schemaName === "muninn.telemetry_surface") - .map((record) => buildInspectedInterfaceFromTelemetryRecord( - record, - providersById, - sourceId, - records, - )) - .filter(Boolean); - return [...surfaceInterfaces, ...telemetryInterfaces]; -} - -function inspectCultMeshStoreBytes(storePath, sourceId) { - return { - interfaces: inspectCultMeshInterfacesFromStore(storePath, sourceId), - providerAdvertisements: inspectProviderAdvertisementsFromStore(storePath, sourceId), - }; -} - -function mergeInterfaces(entries) { - const byProvider = new Map(); - for (const entry of entries) { - if (!entry?.providerId) continue; - const existing = byProvider.get(String(entry.providerId)); - if (!existing || (!existing.surface?.root && entry.surface?.root)) { - byProvider.set(String(entry.providerId), entry); - } - } - return [...byProvider.values()]; -} - -function mergeProviderAdvertisements(entries) { - const byProvider = new Map(); - for (const entry of entries) { - if (!entry?.id) continue; - const existing = byProvider.get(String(entry.id)); - byProvider.set(String(entry.id), mergeProviderAdvertisement(existing, entry)); - } - return [...byProvider.values()]; -} - -function mergeProviderAdvertisement(existing, entry) { - if (!existing) return entry; - return { - ...existing, - ...entry, - endpoints: preferNonEmptyArray(entry.endpoints, existing.endpoints), - routes: preferNonEmptyArray(entry.routes, existing.routes), - inputStreams: preferNonEmptyArray(entry.inputStreams, existing.inputStreams), - activeStreams: preferNonEmptyArray(entry.activeStreams, existing.activeStreams), - availableSources: preferNonEmptyArray(entry.availableSources, existing.availableSources), - capabilities: preferNonEmptyArray(entry.capabilities, existing.capabilities), - }; -} - -function preferNonEmptyArray(candidate, fallback) { - return Array.isArray(candidate) && candidate.length > 0 - ? candidate - : (Array.isArray(fallback) ? fallback : []); -} - -function buildInspectedInterfaceFromSurfaceRecord(record, providersById, sourceId, records) { - const state = normalizeInspectedSurfaceState(record?.payloadPreview); - if (!state?.providerId || !state.surface?.root) { - return null; - } - const provider = providersById.get(state.providerId) || null; - return { - providerId: state.providerId, - title: state.title || provider?.title || state.providerId, - state: "active", - detail: `${state.surface.root.kind || "surface"} ${countSurfaceNodes(state.surface)} nodes via CultMesh witness inspection`, - version: state.version || 0, - updatedAt: state.updatedAt || provider?.updatedAt || new Date().toISOString(), - source: `cultmesh:${sourceId}`, - manifest: provider ? { - providerId: provider.id, - title: provider.title, - description: provider.description, - canonicalService: provider.canonicalService, - locatedService: provider.locatedService, - cultMeshAddress: provider.cultMeshAddress, - endpoints: sanitizeProviderEndpoints(provider.endpoints), - routes: sanitizeProviderEndpoints(provider.routes), - } : null, - canonicalService: provider?.canonicalService || null, - locatedService: provider?.locatedService || null, - cultMeshAddress: provider?.cultMeshAddress || null, - endpoints: sanitizeProviderEndpoints(provider?.endpoints), - routes: sanitizeProviderEndpoints(provider?.routes), - operatorState: null, - commandBoundary: provider?.commandBoundary || inspectProviderCommandBoundary(state.providerId, records), - transportProfile: provider?.transportProfile || inspectProviderTransportProfile(state.providerId, records), - surface: state.surface, - }; -} - -function buildInspectedInterfaceFromTelemetryRecord(record, providersById, sourceId, records) { - const telemetry = normalizeInspectedMuninnTelemetrySurfaceRecord(record?.payloadPreview); - if (!telemetry?.hostId) { - return null; - } - const providerId = `muninn.telemetry.${telemetry.hostId}`; - const provider = providersById.get(providerId) || null; - const state = muninnTelemetryStateFromRecord(telemetry, provider); - if (!state?.surface?.root) { - return null; - } - return { - providerId: state.providerId, - title: state.title, - state: "active", - detail: `${state.surface.root.kind || "surface"} ${countSurfaceNodes(state.surface)} nodes via Muninn telemetry surface`, - version: state.version || 0, - updatedAt: state.updatedAt || provider?.updatedAt || new Date().toISOString(), - source: `cultmesh:${sourceId}`, - manifest: provider ? { - providerId: provider.id, - title: provider.title, - description: provider.description, - canonicalService: provider.canonicalService, - locatedService: provider.locatedService, - cultMeshAddress: provider.cultMeshAddress, - endpoints: sanitizeProviderEndpoints(provider.endpoints), - routes: sanitizeProviderEndpoints(provider.routes), - } : null, - canonicalService: provider?.canonicalService || null, - locatedService: provider?.locatedService || null, - cultMeshAddress: provider?.cultMeshAddress || null, - endpoints: sanitizeProviderEndpoints(provider?.endpoints), - routes: sanitizeProviderEndpoints(provider?.routes), - operatorState: null, - commandBoundary: provider?.commandBoundary || null, - transportProfile: provider?.transportProfile || null, - surface: state.surface, - }; -} - -function muninnTelemetryStateFromRecord(record, advertisement = null) { - const telemetry = normalizeMuninnTelemetrySurfaceRecord(record); - if (!telemetry?.hostId) { - return null; - } - const providerId = advertisement?.providerId || advertisement?.id || `muninn.telemetry.${telemetry.hostId}`; - const title = advertisement?.title || advertisement?.provider?.title || `Muninn ${titleCase(telemetry.hostId)} Telemetry`; - const updatedAt = telemetry.updatedAt || advertisement?.updatedAt || new Date().toISOString(); - const parsedVersion = Date.parse(updatedAt); - return { - providerId, - title, - version: Number.isFinite(parsedVersion) ? parsedVersion : 0, - updatedAt, - surface: buildMuninnTelemetrySurfaceDocument(providerId, title, telemetry), - }; -} - -function normalizeMuninnTelemetrySurfaceRecord(record) { - if (!record) { - return null; - } - if (!Array.isArray(record) && typeof record === "object") { - return { - surfaceId: record.surface_id || record.surfaceId || null, - hostId: record.host_id || record.hostId || null, - state: record.state || "unknown", - availableSources: Array.isArray(record.available_sources || record.availableSources) - ? (record.available_sources || record.availableSources) - : [], - streamAffordances: Array.isArray(record.stream_affordances || record.streamAffordances) - ? (record.stream_affordances || record.streamAffordances) - : [], - activeStreams: Array.isArray(record.active_streams || record.activeStreams) - ? (record.active_streams || record.activeStreams) - : [], - activationAuthority: record.activation_authority || record.activationAuthority || "", - detail: record.detail || "", - updatedAt: record.updated_at || record.updatedAt || null, - }; - } - return normalizeInspectedMuninnTelemetrySurfaceRecord(record); -} - -function normalizeInspectedMuninnTelemetrySurfaceRecord(preview) { - if (Array.isArray(preview) && preview.length === 1 && preview[0] && typeof preview[0] === "object" && !Array.isArray(preview[0])) { - return normalizeMuninnTelemetrySurfaceRecord(preview[0]); - } - if (!Array.isArray(preview) || preview.length < 9) { - return null; - } - return { - surfaceId: preview[0] || null, - hostId: preview[1] || null, - state: preview[2] || "unknown", - availableSources: Array.isArray(preview[3]) ? preview[3] : [], - streamAffordances: Array.isArray(preview[4]) ? preview[4] : [], - activeStreams: Array.isArray(preview[5]) ? preview[5] : [], - activationAuthority: preview[6] || "", - detail: preview[7] || "", - updatedAt: preview[8] || null, - }; -} - -function buildMuninnTelemetrySurfaceDocument(providerId, title, telemetry) { - const sourceSummary = telemetry.availableSources.length ? telemetry.availableSources.join(", ") : "none"; - const activeSummary = telemetry.activeStreams.length ? telemetry.activeStreams.join(", ") : "none"; - const affordanceSummary = telemetry.streamAffordances.length ? telemetry.streamAffordances.join(", ") : "none"; - return { - schema: "gamecult.eve.surface.v1", - id: telemetry.surfaceId || `${providerId}.surface`, - title, - root: { - id: `${providerId}.root`, - kind: "dashboard", - props: { - title, - summary: telemetry.detail || `${telemetry.state} on ${telemetry.hostId}`, - status: telemetry.state || "unknown", - }, - children: [ - { - id: `${providerId}.runtime`, - kind: "card", - props: { title: "Runtime" }, - children: [ - textElement(`${providerId}.state`, `state: ${telemetry.state || "unknown"}`), - textElement(`${providerId}.host`, `host: ${telemetry.hostId}`), - textElement(`${providerId}.authority`, `activation: ${telemetry.activationAuthority || "unknown"}`), - textElement(`${providerId}.updated`, `updated: ${telemetry.updatedAt || "unknown"}`), - ], - }, - { - id: `${providerId}.sources`, - kind: "card", - props: { title: "Sources" }, - children: [ - textElement(`${providerId}.available-sources`, `available: ${sourceSummary}`), - textElement(`${providerId}.affordances`, `affordances: ${affordanceSummary}`), - ], - }, - { - id: `${providerId}.streams`, - kind: "card", - props: { title: "Streams" }, - children: [ - textElement(`${providerId}.active-streams`, `active: ${activeSummary}`), - textElement(`${providerId}.detail`, telemetry.detail || "detail: none"), - ], - }, - ], - }, - assets: [], - }; -} - -function normalizeInspectedProviderAdvertisement(preview) { - if (Array.isArray(preview) && preview.length === 1 && preview[0] && typeof preview[0] === "object" && !Array.isArray(preview[0])) { - const value = preview[0]; - return { - providerId: value.providerId || value.ProviderId || null, - title: value.title || value.Title || null, - description: value.description || value.Description || null, - canonicalService: value.canonicalService || value.CanonicalService || null, - locatedService: value.locatedService || value.LocatedService || null, - cultMeshAddress: value.cultMeshAddress || value.CultMeshAddress || null, - status: value.status || value.Status || null, - updatedAt: value.updatedAt || value.UpdatedAt || null, - capabilities: value.capabilities || value.CapabilityIds || [], - endpoints: value.endpoints || value.Endpoints || [], - commandSurface: value.commandSurface || value.CommandSurface || null, - }; - } - if (!Array.isArray(preview) || preview.length < 11) { - return null; - } - return { - providerId: preview[1] || null, - serviceId: preview[2] || null, - verseId: preview[3] || null, - title: preview[4] || null, - description: preview[5] || null, - canonicalService: preview[6] || null, - locatedService: preview[7] || null, - cultMeshAddress: preview[8] || null, - status: preview[9] || null, - updatedAt: preview[10] || null, - capabilities: Array.isArray(preview[11]) ? preview[11] : [], - endpoints: Array.isArray(preview[12]) ? preview[12] : [], - schemas: Array.isArray(preview[13]) ? preview[13] : [], - witnesses: Array.isArray(preview[14]) ? preview[14] : [], - surfaces: Array.isArray(preview[15]) ? preview[15] : [], - }; -} - -function normalizeInspectedSurfaceState(preview) { - if (Array.isArray(preview) && preview.length === 1 && preview[0] && typeof preview[0] === "object" && !Array.isArray(preview[0])) { - const value = preview[0]; - return { - providerId: value.providerId || value.ProviderId || null, - title: value.title || value.Title || null, - version: Number(value.version || value.Version || 0), - updatedAt: value.updatedAt || value.UpdatedAt || null, - surface: normalizeInspectedSurface(value.surface || value.Surface || null), - }; - } - if (!Array.isArray(preview) || preview.length < 5) { - return null; - } - if (preview.length >= 6) { - return { - providerId: preview[1] || null, - title: preview[2] || null, - version: Number(preview[3] || 0), - updatedAt: preview[4] || null, - surface: normalizeInspectedSurface(preview[5]), - }; - } - return { - providerId: preview[0] || null, - title: preview[1] || null, - version: Number(preview[2] || 0), - updatedAt: preview[3] || null, - surface: normalizeInspectedSurface(preview[4]), - }; -} - -function normalizeInspectedSurface(preview) { - if (!preview) { - return null; - } - if (!Array.isArray(preview) && typeof preview === "object") { - return { - ...preview, - root: normalizeInspectedSurfaceNode(preview.root), - assets: Array.isArray(preview.assets) ? preview.assets : [], - }; - } - if (!Array.isArray(preview) || preview.length < 4) { - return null; - } - return { - schema: preview[0] || "gamecult.eve.surface.v1", - id: preview[1] || "surface", - title: preview[2] || "", - root: normalizeInspectedSurfaceNode(preview[3]), - assets: Array.isArray(preview[4]) ? preview[4] : [], - }; -} - -function normalizeInspectedSurfaceNode(preview) { - if (!preview) { - return null; - } - if (!Array.isArray(preview) && typeof preview === "object") { - return { - ...preview, - props: normalizeInspectedSurfaceProps(preview.props), - children: Array.isArray(preview.children) - ? preview.children.map((child) => normalizeInspectedSurfaceNode(child)).filter(Boolean) - : [], - }; - } - if (!Array.isArray(preview) || preview.length < 3) { - return null; - } - return { - id: preview[0] || "node", - kind: preview[1] || "group", - props: normalizeInspectedSurfaceProps(preview[2]), - children: Array.isArray(preview[3]) - ? preview[3].map((child) => normalizeInspectedSurfaceNode(child)).filter(Boolean) - : [], - }; -} - -function normalizeInspectedSurfaceProps(preview) { - if (!preview) { - return {}; - } - if (!Array.isArray(preview) && typeof preview === "object") { - return preview; - } - if (!Array.isArray(preview)) { - return {}; - } - return { - title: preview[0] || "", - text: preview[1] || "", - label: preview[2] || "", - value: preview[3] || "", - status: preview[4] || "", - summary: preview[5] || "", - detail: preview[6] || "", - }; -} - -function inspectProviderCommandBoundary(providerId, records) { - if (providerId !== "nightwing-gjallar") { - return null; - } - const record = records.find((entry) => entry.schemaName === "gjallar.command_boundary"); - if (!record || !Array.isArray(record.payloadPreview)) { - return null; - } - return { - boundary_id: record.payloadPreview[0] || null, - daemon_id: record.payloadPreview[1] || null, - owner: record.payloadPreview[2] || null, - lifecycle_authority: record.payloadPreview[5] || null, - updated_at: record.payloadPreview[8] || null, - }; -} - -function inspectProviderTransportProfile(providerId, records) { - if (providerId !== "nightwing-gjallar") { - return null; - } - const record = records.find((entry) => entry.schemaName === "gjallar.transport_profile"); - if (!record || !Array.isArray(record.payloadPreview)) { - return null; - } - return { - profile_id: record.payloadPreview[0] || null, - daemon_id: record.payloadPreview[1] || null, - state: record.payloadPreview[2] || null, - debug_transport: record.payloadPreview[3] || null, - current_transport: record.payloadPreview[4] || null, - health_contract: record.payloadPreview[5] || null, - cut_line: record.payloadPreview[9] || null, - updated_at: record.payloadPreview[10] || null, - }; -} - -function normalizeInspectedEndpoints(endpoints) { - if (!Array.isArray(endpoints)) { - return []; - } - return endpoints.map((entry) => { - if (entry && typeof entry === "object" && !Array.isArray(entry)) { - return entry; - } - return { - transport: "witness", - address: String(entry || ""), - }; - }); -} - -function sanitizeProviderEndpoints(endpoints) { - return normalizeInspectedEndpoints(endpoints).filter((entry) => { - const transport = String(entry?.transport || "").toLowerCase(); - const address = String(entry?.address || "").trim(); - if (address.startsWith("cultmesh:")) { - return true; - } - if (transport.includes("cultmesh") || transport.includes("cultcache")) { - return true; - } - return false; - }); -} - -function providerTypedEndpoint(endpoints) { - const normalized = sanitizeProviderEndpoints(endpoints); - return normalized.find((entry) => { - const address = String(entry?.address || ""); - return address.startsWith("cultmesh:"); - })?.address || null; -} - -function typedProviderEndpoint(endpoint) { - const value = typeof endpoint === "string" ? endpoint.trim() : ""; - if (!value) { - return null; - } - return value.startsWith("cultmesh:") ? value : null; -} - -function normalizeInspectedRoutes(advertisement) { - if (Array.isArray(advertisement?.routes)) { - return advertisement.routes; - } - if (Array.isArray(advertisement?.endpoints)) { - return normalizeInspectedEndpoints(advertisement.endpoints); - } - return []; -} - -function resolveInterfaceBindingStore(storeSpec) { - if (typeof storeSpec !== "string" || !storeSpec.trim()) { - return null; - } - const text = storeSpec.trim(); - if (text.startsWith("cultmesh-store:file://")) { - const localPath = fileURLToPath(text.slice("cultmesh-store:".length)); - return { - localPath, - sourceId: text, - cleanup: () => {}, - }; - } - if (text.startsWith("cultmesh://")) { - throw new Error(`CultMesh rendezvous URI ${text} must announce through Odin; static interface store imports are not the rendezvous owner.`); - } - if (text.startsWith("sftp://") || text.startsWith("http://") || text.startsWith("https://") || text.startsWith("rudp://")) { - throw new Error(`network interface binding stores are no longer supported by Odin discovery: ${text}`); - } - - throw new Error(`raw interface binding store paths are no longer supported by Odin discovery: ${text}. Use CultMesh announcement through Odin, or an explicit cultmesh-store:file:// URI for a local debug import.`); -} - -function dashboardUnavailable(providerId, source, detail) { - return { - providerId, - title: providerId, - state: "unavailable", - detail, - version: 0, - updatedAt: new Date().toISOString(), - source, - manifest: null, - surface: null, - }; -} - -function countSurfaceNodes(surface, state = null) { - if (Array.isArray(state?.nodes)) { - return state.nodes.length; - } - if (!surface?.root) { - return 0; - } - - let count = 0; - const stack = [surface.root]; - while (stack.length > 0) { - const node = stack.pop(); - if (!node || typeof node !== "object") { - continue; - } - count += 1; - if (Array.isArray(node.children)) { - for (const child of node.children) { - stack.push(child); - } - } - } - return count; -} - -function textElement(id, text) { - return { - id: String(id), - kind: "text", - props: { text: String(text) }, - children: [], - }; -} - -function titleCase(value) { - return String(value || "") - .split(/[^a-zA-Z0-9]+/) - .filter(Boolean) - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(" "); -} - -module.exports = { - createInterfaceDiscovery, - dashboardUnavailable, -}; diff --git a/src/odin/layout.cjs b/src/odin/layout.cjs deleted file mode 100644 index 66db6fd..0000000 --- a/src/odin/layout.cjs +++ /dev/null @@ -1,279 +0,0 @@ -"use strict"; - -const fs = require("fs"); -const { clampNumber, positiveNumber, stableId } = require("./utils.cjs"); - -const DEFAULT_LAYOUT_ID = "odin.providers"; - -function createLayoutStore({ definition, getNode, layoutPath } = {}) { - let cachedLayout = null; - let attemptedMigration = false; - - return { - async readLayout() { - const meshLayout = await readCultMeshLayout(); - if (meshLayout) return meshLayout; - if (!attemptedMigration) { - attemptedMigration = true; - const migrated = readJsonMigrationLayout(layoutPath); - if (migrated) { - cachedLayout = migrated; - await this.writeLayout(migrated).catch(() => undefined); - return normalizeLayout(migrated); - } - } - return cachedLayout || defaultLayout(); - }, - - async writeLayout(layout) { - const normalized = normalizeLayout(layout); - cachedLayout = normalized; - const node = await layoutNode(); - if (!node || !definition) { - throw new Error("Odin CultMesh layout store unavailable; refusing to write layout sidecar fallback."); - } - await node.put(definition, DEFAULT_LAYOUT_ID, normalized); - await node.flush?.(true); - }, - - async applyClientCommand(command) { - if (!command || command.type !== "odin-layout-intent" || !command.providerId) return; - const layout = await this.readLayout(); - layout.updatedAt = new Date().toISOString(); - layout.tiles ||= {}; - const current = layout.tiles[command.providerId] || defaultLayoutFor({ providerId: command.providerId }, []); - const next = { ...current }; - if (command.action === "focus") { - Object.assign(next, fullscreenLayoutIntent(command.providerId, -100)); - } else if (command.action === "resize") { - next.w = clampNumber((next.w || 1) + Number(command.dw || 0), 1, 4); - next.h = clampNumber((next.h || 1) + Number(command.dh || 0), 1, 4); - } else if (command.action === "move") { - next.x = clampNumber((next.x || 0) + Number(command.dx || 0), 0, 12); - next.y = clampNumber((next.y || 0) + Number(command.dy || 0), 0, 12); - } else if (command.action === "toggle") { - next.visible = !next.visible; - } else { - return; - } - layout.tiles[command.providerId] = next; - await this.writeLayout(layout); - }, - }; - - async function readCultMeshLayout() { - const node = await layoutNode(); - if (!node || !definition) return null; - const record = await node.get(definition, DEFAULT_LAYOUT_ID); - const normalized = record ? normalizeLayout(record) : null; - if (normalized) cachedLayout = normalized; - return normalized; - } - - async function layoutNode() { - return typeof getNode === "function" ? await getNode() : null; - } -} - -function defaultLayout() { - return { schema: "odin.interface_layout.v1", layoutId: DEFAULT_LAYOUT_ID, tiles: {} }; -} - -function normalizeLayout(layout) { - return { - ...defaultLayout(), - ...(layout && typeof layout === "object" ? layout : {}), - schema: "odin.interface_layout.v1", - layoutId: DEFAULT_LAYOUT_ID, - tiles: layout && typeof layout.tiles === "object" && layout.tiles ? layout.tiles : {}, - }; -} - -function readJsonMigrationLayout(layoutPath) { - if (!layoutPath) return null; - try { - return normalizeLayout(JSON.parse(fs.readFileSync(layoutPath, "utf8"))); - } catch { - return null; - } -} - -function defaultLayoutFor(entry, interfaces) { - const index = Math.max(0, interfaces.findIndex((candidate) => candidate.providerId === entry.providerId)); - const intent = surfaceLayoutIntent(entry); - const preferredHeight = positiveNumber(intent.preferredHeight, entry.providerId === "voidbot.swarm" ? 18 : 12); - const minHeight = positiveNumber(intent.minHeight, 6); - const preferredWidth = positiveNumber(intent.preferredWidth, 72); - const minWidth = positiveNumber(intent.minWidth, 36); - const priority = Number.isFinite(intent.priority) ? intent.priority : index; - return { - tileId: stableId(entry.providerId || "interface"), - visible: true, - priority, - x: index % 2, - y: Math.floor(index / 2), - w: 1, - h: Math.max(1, Math.ceil(preferredHeight / 12)), - minWidth, - minHeight, - preferredWidth, - preferredHeight, - density: intent.density || "dense", - viewportMode: intent.viewportMode || "nested-scroll", - signalWeight: intent.signalWeight || 1, - tree: intent.tree || null, - }; -} - -function fullscreenLayoutIntent(tileId, priority = -100) { - return { - tileId: stableId(tileId || "fullscreen"), - visible: true, - priority, - x: 0, - y: 0, - w: 4, - h: 4, - minWidth: 96, - minHeight: 36, - preferredWidth: 192, - preferredHeight: 48, - density: "comfortable", - viewportMode: "fullscreen", - }; -} - -function mergeLayoutIntent(existing, entry, interfaces) { - const base = existing && typeof existing === "object" - ? { ...existing } - : defaultLayoutFor(entry, interfaces); - const intent = surfaceLayoutIntent(entry); - const fallback = defaultLayoutFor(entry, interfaces); - const denseTree = isDenseLayoutStrategy(intent.layoutStrategy); - const minWidth = positiveNumber(intent.minWidth, positiveNumber(base.minWidth, fallback.minWidth)); - const minHeight = positiveNumber(intent.minHeight, positiveNumber(base.minHeight, fallback.minHeight)); - const preferredWidth = positiveNumber(intent.preferredWidth, positiveNumber(base.preferredWidth, fallback.preferredWidth)); - const preferredHeight = positiveNumber(intent.preferredHeight, positiveNumber(base.preferredHeight, fallback.preferredHeight)); - const desiredW = Math.max(1, Math.min(4, Math.ceil(preferredWidth / 72))); - const desiredH = Math.max(1, Math.min(4, Math.ceil(preferredHeight / 12))); - return { - ...base, - minWidth, - minHeight, - preferredWidth, - preferredHeight, - h: denseTree && intent.viewportMode !== "fullscreen" ? desiredH : Math.max(positiveNumber(base.h, fallback.h), desiredH), - w: denseTree && intent.viewportMode !== "fullscreen" ? desiredW : Math.max(positiveNumber(base.w, fallback.w), desiredW), - priority: Number.isFinite(intent.priority) ? Math.min(Number(base.priority ?? intent.priority), intent.priority) : base.priority, - density: intent.density || base.density || fallback.density, - viewportMode: intent.viewportMode || base.viewportMode || fallback.viewportMode, - layoutStrategy: intent.layoutStrategy || base.layoutStrategy || fallback.layoutStrategy, - signalWeight: intent.signalWeight || base.signalWeight || fallback.signalWeight || 1, - tree: intent.tree || base.tree || fallback.tree || null, - }; -} - -function surfaceLayoutIntent(entry) { - const root = entry?.surface?.root; - if (!root || typeof root !== "object") return {}; - const layout = root.layout && typeof root.layout === "object" ? root.layout : {}; - const props = root.props && typeof root.props === "object" ? root.props : {}; - const propLayout = props.layout && typeof props.layout === "object" ? props.layout : {}; - const tree = analyzeElementTree(root); - const derived = denseTreeLayoutIntent(tree); - return normalizeDenseSurfaceIntent({ ...derived, ...propLayout, ...layout, tree }, derived); -} - -function analyzeElementTree(root) { - const stats = { - elementCount: 0, - leafCount: 0, - branchCount: 0, - maxDepth: 0, - textCells: 0, - listLikeBranchCount: 0, - kindCounts: {}, - }; - - visit(root, 1); - stats.signalWeight = Math.max(1, stats.branchCount * 2 + stats.leafCount + Math.ceil(stats.textCells / 48)); - return stats; - - function visit(element, depth) { - if (!element || typeof element !== "object") return; - stats.elementCount += 1; - stats.maxDepth = Math.max(stats.maxDepth, depth); - const kind = String(element.kind || "unknown"); - stats.kindCounts[kind] = (stats.kindCounts[kind] || 0) + 1; - const text = textValue(element); - stats.textCells += text.length + Math.max(0, text.split(/\r?\n/).length - 1) * 8; - const children = Array.isArray(element.children) ? element.children.filter((child) => child && typeof child === "object") : []; - if (!children.length) { - stats.leafCount += 1; - return; - } - stats.branchCount += 1; - if (children.length >= 4 && children.every((child) => String(child.kind || "") === "text" && !(Array.isArray(child.children) && child.children.length))) { - stats.listLikeBranchCount += 1; - } - for (const child of children) visit(child, depth + 1); - } -} - -function denseTreeLayoutIntent(tree) { - const signal = Math.max(1, tree.signalWeight || 1); - const depthPressure = Math.max(0, tree.maxDepth - 2); - const textPressure = Math.sqrt(Math.max(1, tree.textCells) / 18); - const branchPressure = Math.sqrt(Math.max(1, tree.branchCount)); - return { - minWidth: Math.min(72, 28 + depthPressure * 7), - minHeight: Math.min(18, 5 + depthPressure * 2), - preferredWidth: Math.min(144, 44 + Math.sqrt(signal) * 7 + depthPressure * 5), - preferredHeight: Math.min(36, 8 + textPressure + branchPressure * 3 + tree.listLikeBranchCount * 2), - density: "dense", - viewportMode: "nested-scroll", - layoutStrategy: "dense-tree", - signalWeight: signal, - }; -} - -function normalizeDenseSurfaceIntent(intent, derived) { - const viewportMode = intent.viewportMode || derived.viewportMode; - if (viewportMode === "fullscreen") { - return intent; - } - return { - ...intent, - minWidth: Math.min(72, positiveNumber(intent.minWidth, derived.minWidth)), - minHeight: Math.min(18, positiveNumber(intent.minHeight, derived.minHeight)), - preferredWidth: Math.min(144, positiveNumber(intent.preferredWidth, derived.preferredWidth)), - preferredHeight: Math.min(36, positiveNumber(intent.preferredHeight, derived.preferredHeight)), - density: intent.density || derived.density || "dense", - viewportMode, - layoutStrategy: intent.layoutStrategy || derived.layoutStrategy || "dense-tree", - signalWeight: intent.signalWeight || derived.signalWeight || 1, - }; -} - -function isDenseLayoutStrategy(strategy) { - const value = String(strategy || ""); - return value === "dense-tree" || value.startsWith("dense-"); -} - -function textValue(element) { - if (typeof element.text === "string") return element.text; - const props = element.props && typeof element.props === "object" ? element.props : {}; - if (typeof props.text === "string") return props.text; - if (typeof props.title === "string") return props.title; - return ""; -} - -module.exports = { - analyzeElementTree, - createLayoutStore, - defaultLayoutFor, - denseTreeLayoutIntent, - fullscreenLayoutIntent, - mergeLayoutIntent, - surfaceLayoutIntent, -}; diff --git a/src/odin/marquee.cjs b/src/odin/marquee.cjs deleted file mode 100644 index 375954f..0000000 --- a/src/odin/marquee.cjs +++ /dev/null @@ -1,111 +0,0 @@ -"use strict"; - -const fs = require("fs"); -const { - CultCache, - SingleFileMessagePackBackingStore, - defineDocumentRegistry, - defineDocumentType, -} = require("cultcache-ts"); - -const textDocumentSetDefinition = defineDocumentType({ - type: "gamecult.text_document_set", - global: true, - schema: { - parse(value) { - if (!value || typeof value !== "object") { - throw new Error("gamecult.text_document_set must be an object"); - } - return value; - }, - }, -}); - -async function buildMarqueeText({ interfaces, textDocumentStorePath, stonksBurstSize = 8 }) { - const [securities, stanzas] = await Promise.all([ - Promise.resolve(stonksSegments({ interfaces })), - poetryStanzas(textDocumentStorePath), - ]); - return stanzaBurstTape(stanzas, securities, stonksBurstSize).join(" / "); -} - -function stonksSegments({ interfaces }) { - return stonksSegmentsFromInterfaces(interfaces); -} - -function stonksSegmentsFromInterfaces(interfaces) { - const stonks = interfaces.find((entry) => String(entry.providerId || "").toLowerCase() === "stonks.market"); - const explicit = String(stonks?.surface?.root?.props?.marqueeText || "").trim(); - return splitSegments(explicit).slice(0, 16); -} - -async function poetryStanzas(textDocumentStorePath) { - if (!textDocumentStorePath || !fs.existsSync(textDocumentStorePath)) return []; - try { - const cache = CultCache.builder() - .withRegistry(defineDocumentRegistry(textDocumentSetDefinition)) - .withGenericStore(new SingleFileMessagePackBackingStore(textDocumentStorePath)) - .build(); - await cache.pullAllBackingStores(); - const documentSet = cache.getGlobal(textDocumentSetDefinition); - return array(documentSet?.documents).flatMap(documentStanzas); - } catch { - return []; - } -} - -function documentStanzas(document) { - const stanzas = []; - let stanza = []; - for (const line of array(document?.lines)) { - if (isStanzaMarker(line)) { - pushStanza(stanzas, stanza); - stanza = []; - continue; - } - - const text = array(line).join(" / ").replace(/\s+/g, " ").trim(); - if (text) stanza.push(text); - } - pushStanza(stanzas, stanza); - return stanzas; -} - -function pushStanza(stanzas, stanza) { - if (stanza.length) stanzas.push(stanza.join(" / ")); -} - -function stanzaBurstTape(stanzas, securities, burstSize) { - const output = []; - const stonkBurstSize = Math.max(1, Number(burstSize) || 8); - const stanzaList = stanzas.length ? stanzas : []; - const securityList = securities.length ? securities : []; - const cycles = Math.max(stanzaList.length, securityList.length ? Math.ceil(securityList.length / stonkBurstSize) : 0); - for (let index = 0; index < cycles; index += 1) { - if (stanzaList.length) output.push(stanzaList[index % stanzaList.length]); - for (let offset = 0; offset < stonkBurstSize && securityList.length; offset += 1) { - output.push(securityList[(index * stonkBurstSize + offset) % securityList.length]); - } - } - return output; -} - -function splitSegments(text) { - return String(text || "") - .split(/\s+\/\s+/) - .map((segment) => segment.replace(/\s+/g, " ").trim()) - .filter(Boolean); -} - -function isStanzaMarker(line) { - const parts = array(line); - return parts.length === 1 && String(parts[0]).trim().toLowerCase() === "[stanza]"; -} - -function array(value) { - return Array.isArray(value) ? value : []; -} - -module.exports = { - buildMarqueeText, -}; diff --git a/src/odin/probes.cjs b/src/odin/probes.cjs deleted file mode 100644 index 7e4c5b5..0000000 --- a/src/odin/probes.cjs +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; - -const fs = require("fs"); -const path = require("path"); -const { execFile } = require("child_process"); -const { promisify } = require("util"); - -const execFileAsync = promisify(execFile); - -async function dockerSnapshot() { - try { - const { stdout } = await execFileAsync("docker", ["ps", "--format", "{{json .}}"], { timeout: 3000 }); - const containers = stdout.split(/\r?\n/) - .filter(Boolean) - .map((line) => JSON.parse(line)) - .map((item) => ({ - name: item.Names, - image: item.Image, - status: item.Status, - ports: item.Ports, - })); - return { state: "ok", containers, error: "" }; - } catch (error) { - return { state: "error", containers: [], error: error.message }; - } -} - -async function adbSnapshot() { - const adb = path.join(process.env.LOCALAPPDATA || "", "Android", "Sdk", "platform-tools", "adb.exe"); - if (!fs.existsSync(adb)) { - return { state: "missing", devices: [], error: `missing ${adb}` }; - } - try { - const { stdout } = await execFileAsync(adb, ["devices"], { timeout: 3000 }); - const devices = stdout.split(/\r?\n/) - .map((line) => line.match(/^(\S+)\s+(device|offline|unauthorized)$/)) - .filter(Boolean) - .map((match) => ({ serial: match[1], state: match[2] })); - return { state: "ok", devices, error: "" }; - } catch (error) { - return { state: "error", devices: [], error: error.message }; - } -} - -module.exports = { - adbSnapshot, - dockerSnapshot, -}; diff --git a/src/odin/provider-ingress.cjs b/src/odin/provider-ingress.cjs deleted file mode 100644 index 4a35711..0000000 --- a/src/odin/provider-ingress.cjs +++ /dev/null @@ -1,278 +0,0 @@ -"use strict"; - -function createLiveProviderRegistry(options = {}) { - const maxAgeMs = Math.max(1_000, Number(options.maxAgeMs || 120_000)); - const records = new Map(); - - function ingestDocument(document, source = {}) { - if (!document?.schemaId || !document?.recordKey) { - return; - } - const now = Date.now(); - records.set(`${document.schemaId}:${document.recordKey}`, { - ...document, - receivedAtMs: now, - source, - }); - prune(now); - } - - function snapshot() { - const now = Date.now(); - prune(now); - - const advertisements = new Map(); - const surfaces = new Map(); - const commandBoundaries = new Map(); - const transportProfiles = new Map(); - - for (const record of records.values()) { - const payload = normalizeDocumentPayload(record); - switch (record.schemaId) { - case "gamecult.eve.provider_advertisement": - case "gamecult.eve.provider_advertisement.v1": - if (payload?.providerId) { - advertisements.set(String(payload.providerId), { ...record, payload }); - } - break; - case "gamecult.eve.surface_state": - case "gamecult.eve.surface_state.v0": - case "gamecult.eve.surface_state.v1": - if (surfaceProviderId(payload)) { - surfaces.set(String(surfaceProviderId(payload)), { ...record, payload }); - } - break; - default: { - const providerId = payload.provider_id || payload.providerId; - if (!providerId) break; - if (String(record.schemaId).endsWith(".command_boundary")) { - commandBoundaries.set(String(providerId), payload); - } else if (String(record.schemaId).endsWith(".transport_profile")) { - transportProfiles.set(String(providerId), payload); - } - break; - } - } - } - - const providerAdvertisements = [...advertisements.values()] - .map((record) => normalizeProviderAdvertisementRecord(record, commandBoundaries, transportProfiles)) - .filter(Boolean) - .sort((left, right) => String(left.id).localeCompare(String(right.id))); - - const interfaces = providerAdvertisements - .map((provider) => { - const surfaceRecord = surfaces.get(String(provider.id)); - if (!surfaceRecord?.payload?.surface?.root) { - return null; - } - return liveProviderInterface(provider, surfaceRecord.payload, surfaceRecord.source); - }) - .filter(Boolean) - .sort((left, right) => String(left.providerId).localeCompare(String(right.providerId))); - - return { interfaces, providerAdvertisements }; - } - - function prune(now = Date.now()) { - for (const [key, record] of records) { - if (now - record.receivedAtMs > maxAgeMs) { - records.delete(key); - } - } - } - - return { - ingestDocument, - snapshot, - }; -} - -function normalizeDocumentPayload(record) { - const payload = record?.payload; - switch (record?.schemaId) { - case "gamecult.eve.surface_state": - case "gamecult.eve.surface_state.v0": - case "gamecult.eve.surface_state.v1": - if (Array.isArray(payload) && payload.length >= 5) { - return { - provider_id: payload[0], - title: payload[1], - version: payload[2], - updated_at: payload[3], - surface: payload[4], - }; - } - break; - default: - break; - } - let normalized = payload; - for (let depth = 0; depth < 4; depth += 1) { - if (Array.isArray(normalized) && normalized.length === 1 && normalized[0] && typeof normalized[0] === "object") { - normalized = normalized[0]; - continue; - } - if (normalized?.value && typeof normalized.value === "object" && !Array.isArray(normalized.value)) { - normalized = normalized.value; - continue; - } - break; - } - return normalized || {}; -} - -function surfaceProviderId(surfaceState) { - return surfaceState?.providerId || surfaceState?.provider_id || null; -} - -function surfaceTitle(surfaceState) { - return surfaceState?.title || surfaceState?.Title || null; -} - -function surfaceVersion(surfaceState) { - return surfaceState?.version || surfaceState?.Version || 0; -} - -function surfaceUpdatedAt(surfaceState) { - return surfaceState?.updatedAt || surfaceState?.updated_at || surfaceState?.UpdatedAt || null; -} - -function normalizeProviderAdvertisementRecord(record, commandBoundaries, transportProfiles) { - const advertisement = record.payload; - const providerId = advertisement?.providerId || advertisement?.provider?.id || advertisement?.id; - if (!providerId) { - return null; - } - const endpoints = sanitizeProviderEndpoints(advertisement.endpoints); - const routes = sanitizeProviderEndpoints(advertisement.routes); - const providerEndpoint = advertisement.cultMeshAddress - || providerTypedEndpoint(routes) - || providerTypedEndpoint(endpoints) - || typedProviderEndpoint(advertisement.provider?.endpoint) - || `cultmesh:live:${providerId}`; - return { - id: providerId, - title: advertisement.title || advertisement.provider?.title || providerId, - description: advertisement.description || "Provider-owned CultNet/RUDP advertisement.", - version: String(advertisement.version || 0), - endpoint: providerEndpoint, - canonicalService: advertisement.canonicalService || null, - locatedService: advertisement.locatedService || null, - cultMeshAddress: advertisement.cultMeshAddress || null, - endpoints, - routes, - inputStreams: Array.isArray(advertisement.inputStreams) ? advertisement.inputStreams : [], - activeStreams: Array.isArray(advertisement.activeStreams) ? advertisement.activeStreams : [], - availableSources: Array.isArray(advertisement.availableSources) ? advertisement.availableSources : [], - transportEndpoint: providerTypedEndpoint(routes) - || typedProviderEndpoint(advertisement.provider?.endpoint) - || providerEndpoint, - capabilities: advertisement.provider?.capabilities || advertisement.capabilities || [], - operatorState: null, - commandBoundary: commandBoundaries.get(String(providerId)) || null, - transportProfile: transportProfiles.get(String(providerId)) || null, - usesCultMesh: false, - transport: "CultNet/RUDP provider advertisement", - status: advertisement.status || "unknown", - updatedAt: advertisement.updatedAt || record.storedAt || new Date(record.receivedAtMs).toISOString(), - source: sourceLabel(record.source), - commandSurface: advertisement.commandSurface || null, - }; -} - -function typedProviderEndpoint(endpoint) { - const value = typeof endpoint === "string" ? endpoint.trim() : ""; - if (!value) { - return null; - } - return value.startsWith("cultmesh:") ? value : null; -} - -function normalizeProviderEndpoints(endpoints) { - if (!Array.isArray(endpoints)) { - return []; - } - return endpoints.map((entry) => { - if (entry && typeof entry === "object" && !Array.isArray(entry)) { - return entry; - } - return { - transport: "witness", - address: String(entry || ""), - }; - }); -} - -function sanitizeProviderEndpoints(endpoints) { - return normalizeProviderEndpoints(endpoints).filter((entry) => { - const transport = String(entry?.transport || "").toLowerCase(); - const address = String(entry?.address || "").trim(); - if (address.startsWith("cultmesh:")) { - return true; - } - if (transport.includes("cultmesh") || transport.includes("cultcache")) { - return true; - } - return false; - }); -} - -function providerTypedEndpoint(endpoints) { - return sanitizeProviderEndpoints(endpoints).find((entry) => - String(entry?.address || "").startsWith("cultmesh:") - )?.address || null; -} - -function liveProviderInterface(provider, surfaceState, source) { - const surface = surfaceState.surface || null; - return { - providerId: provider.id, - title: surfaceTitle(surfaceState) || provider.title || provider.id, - state: "active", - detail: `${surface?.root?.kind || surface?.root?.type || "surface"} ${countSurfaceNodes(surface, surfaceState)} nodes via live CultNet/RUDP announcement`, - version: surfaceVersion(surfaceState), - updatedAt: surfaceUpdatedAt(surfaceState) || provider.updatedAt || new Date().toISOString(), - source: sourceLabel(source), - manifest: provider, - canonicalService: provider.canonicalService || null, - locatedService: provider.locatedService || null, - cultMeshAddress: provider.cultMeshAddress || null, - endpoints: sanitizeProviderEndpoints(provider.endpoints), - routes: sanitizeProviderEndpoints(provider.routes), - commandBoundary: provider.commandBoundary || null, - transportProfile: provider.transportProfile || null, - surface, - }; -} - -function countSurfaceNodes(surface, state = null) { - if (Array.isArray(state?.nodes)) { - return state.nodes.length; - } - if (!surface?.root) { - return 0; - } - let count = 0; - const stack = [surface.root]; - while (stack.length > 0) { - const node = stack.pop(); - if (!node || typeof node !== "object") continue; - count += 1; - if (Array.isArray(node.children)) { - for (const child of node.children) stack.push(child); - } - } - return count; -} - -function sourceLabel(source) { - if (!source?.address) { - return "cultnet-rudp:unknown"; - } - return `cultnet-rudp://${source.address}:${source.port}`; -} - -module.exports = { - createLiveProviderRegistry, -}; diff --git a/src/odin/state.cjs b/src/odin/state.cjs deleted file mode 100644 index cbcb5ea..0000000 --- a/src/odin/state.cjs +++ /dev/null @@ -1,216 +0,0 @@ -"use strict"; - -const fs = require("fs"); -const { dashboardUnavailable } = require("./interfaces.cjs"); -const { - adbSnapshot, - dockerSnapshot, -} = require("./probes.cjs"); -const { buildMarqueeText } = require("./marquee.cjs"); -const { buildPendingSurface, buildSurface } = require("./surface.cjs"); -const { stableId } = require("./utils.cjs"); - -function createStateBuilder({ cachePath, gamecultTextDocumentStorePath, interfaceDiscovery, layoutStore, stonksBurstSize }) { - let version = 0; - - function buildPendingState(message) { - return { - type: "dashboard-state", - schema: "mimir.eve_dashboard_state.v1", - providerId: "odin.providers", - title: "Odin Provider Catalog", - version, - updatedAt: new Date().toISOString(), - selectedNodeId: "coordinator-starting", - lutPreset: "terminal", - nodes: [], - providerCatalog: [], - surface: buildPendingSurface(message), - }; - } - - async function buildState() { - version += 1; - const observedAt = new Date().toISOString(); - const [ - docker, - adb, - discovery, - ] = await Promise.all([ - dockerSnapshot(), - adbSnapshot(), - interfaceDiscovery.discoverAll(), - ]); - const discoveredInterfaces = discovery.interfaces; - const providerAdvertisements = discovery.providerAdvertisements; - const interfaceById = new Map(discoveredInterfaces.map((entry) => [entry.providerId, entry])); - const interfaces = [...interfaceById.values()]; - const marqueeText = await buildMarqueeText({ interfaces, textDocumentStorePath: gamecultTextDocumentStorePath, stonksBurstSize }); - const interfaceSummary = interfaces.map((entry) => `${entry.providerId}:${entry.state}`).join(", "); - const layout = await layoutStore.readLayout(); - const verseEvidence = [...providerAdvertisements, ...interfaces]; - const voidBotDashboard = interfaceById.get("voidbot.swarm") || dashboardUnavailable("voidbot.swarm", "discovery", "not discovered"); - const mimirLiveStats = interfaceById.get("mimir.live.stats") || dashboardUnavailable("mimir.live.stats", "discovery", "not discovered"); - const periwinkleServices = [ - ...adbFaultServices(adb), - ]; - - const verses = [ - verse("starfire.local", "Starfire", "coordinator", "active", ["docker", "adb", "eve-provider"], [ - service("odin", "Odin all-seer", "active", "asgard.starfire.odin/eve/tui"), - service("docker", "Docker", docker.state === "ok" ? "active" : "warn", `${docker.containers.length} running`), - service("adb", "ADB transport", adbState(adb), adbDetail(adb)), - service("cultcache", "Odin CultCache", fs.existsSync(cachePath) ? "active" : "waiting", require("path").basename(cachePath)), - service("interfaces", "Eve interfaces", interfaces.some((entry) => entry.surface?.root) ? "active" : "waiting", interfaceSummary || "no provider surfaces"), - service("voidbot-swarm", "VoidBot Swarm", voidBotDashboard.state, voidBotDashboard.detail), - service("mimir-live-stats", "Mimir Live Stats", mimirLiveStats.state, mimirLiveStats.detail), - ...docker.containers.map((container) => service(`docker-${container.name}`, container.name, "active", container.image)), - ]), - verse("nightwing.local", "Nightwing", "dashboard-renderer", bodyStatus(verseEvidence, "nightwing"), ["eve-tui", "gpu-worker"], bodyServices(verseEvidence, "nightwing")), - verse("eve.ipad", "EVE", "ios-client", bodyStatus(verseEvidence, "eve"), ["native-eve"], bodyServices(verseEvidence, "eve")), - periwinkleServices.length ? verse("periwinkle.android", "Periwinkle", "android-client", periwinkleStatus(periwinkleServices), ["sensor-edge", "adb-transport"], periwinkleServices) : null, - verse("raven.local", "Raven", "local-peer", bodyStatus(verseEvidence, "raven"), ["cultmesh-provider"], bodyServices(verseEvidence, "raven")), - verse("yggdrasil.ops", "Yggdrasil", "ops-host", bodyStatus(verseEvidence, "yggdrasil"), ["cultmesh-provider"], bodyServices(verseEvidence, "yggdrasil")), - ].filter(Boolean); - - return { - type: "dashboard-state", - schema: "mimir.eve_dashboard_state.v1", - providerId: "odin.providers", - title: "Odin Provider Catalog", - version, - updatedAt: observedAt, - selectedNodeId: "verse-starfire.local", - lutPreset: "terminal", - nodes: verses.map((entry, index) => ({ - id: `verse-${entry.verseId}`, - label: `${entry.name}\n${entry.role}`, - kind: "cultmesh-verse", - visible: true, - x: -0.8 + (index % 3) * 0.8, - y: -0.45 + Math.floor(index / 3) * 0.55, - z: 0, - rotation: 0, - scale: 1, - width: 0.42, - height: 0.2, - health: entry.status, - detail: entry.capabilities.join(", "), - })), - providerCatalog: providerAdvertisements, - surface: buildSurface({ observedAt, docker, adb, verses, interfaces, layout, marqueeText }), - }; - } - - return { buildPendingState, buildState }; -} - -function verse(verseId, name, role, status, capabilities, services = []) { - return { verseId, name, role, status, capabilities, services }; -} - -function service(id, name, state, detail = "") { - return { id: stableId(id), name, state, detail: String(detail || "") }; -} - -function bodyStatus(entries, body) { - const matches = bodyEntries(entries, body); - if (!matches.length) return "waiting"; - if (matches.some((entry) => providerState(entry) === "active")) return "active"; - if (matches.some((entry) => providerState(entry) === "warn")) return "warn"; - return "waiting"; -} - -function bodyServices(entries, body) { - const matches = bodyEntries(entries, body); - if (!matches.length) { - return [service(`${body}-cultmesh-witnesses`, `${titleCase(body)} CultMesh witnesses`, "waiting", "no provider advertisement or interface discovered")]; - } - - return matches - .slice(0, 8) - .map((entry) => service( - `${body}-${entry.providerId || entry.id || entry.title || "provider"}`, - entry.title || entry.providerId || entry.id || `${titleCase(body)} provider`, - providerState(entry), - providerDetail(entry), - )); -} - -function bodyEntries(entries, body) { - const token = String(body).toLowerCase(); - return entries.filter((entry) => providerBodyText(entry).includes(token)); -} - -function providerBodyText(entry) { - return [ - entry.providerId, - entry.id, - entry.title, - entry.canonicalService, - entry.locatedService, - entry.cultMeshAddress, - entry.verseId, - entry.source, - ].filter(Boolean).join(" ").toLowerCase(); -} - -function providerState(entry) { - const state = String(entry.state || entry.status || "").toLowerCase(); - if (["active", "ok", "ready", "running", "published"].includes(state)) return "active"; - if (["warn", "warning", "degraded"].includes(state)) return "warn"; - if (["failed", "error", "offline"].includes(state)) return "warn"; - return entry.surface?.root ? "active" : "waiting"; -} - -function providerDetail(entry) { - return [ - entry.detail, - entry.cultMeshAddress, - entry.locatedService, - entry.source, - ].filter(Boolean).join(" / ") || "provider-owned CultMesh discovery"; -} - -function titleCase(value) { - const text = String(value || ""); - return text ? text[0].toUpperCase() + text.slice(1) : ""; -} - -function adbState(adb) { - if (adb.state !== "ok") return adb.state; - return adbFaultDevices(adb).length ? "warn" : "ok"; -} - -function adbDetail(adb) { - if (adb.error) return adb.error; - if (adb.devices.length === 0) return "no devices"; - return adb.devices.map((device) => `${device.serial}:${device.state}`).join(", "); -} - -function adbFaultDevices(adb) { - return adb.devices.filter((device) => device.state !== "device"); -} - -function adbFaultServices(adb) { - if (adb.state !== "ok") { - return [service("adb-transport", "ADB transport", adb.state, adbDetail(adb))]; - } - - return adbFaultDevices(adb).map((device) => - service(`adb-${device.serial}`, "ADB device fault", device.state, `${device.serial}:${device.state}`), - ); -} - -function periwinkleStatus(services) { - if (services.some((entry) => entry.state === "active")) return "active"; - if (services.some((entry) => entry.state === "stale")) return "stale"; - if (services.some((entry) => entry.state === "offline" || entry.state === "unauthorized" || entry.state === "error" || entry.state === "missing")) return "warn"; - return "waiting"; -} - -module.exports = { - createStateBuilder, - service, - verse, -}; diff --git a/src/odin/surface.cjs b/src/odin/surface.cjs deleted file mode 100644 index b03dbae..0000000 --- a/src/odin/surface.cjs +++ /dev/null @@ -1,212 +0,0 @@ -"use strict"; - -const { analyzeElementTree, fullscreenLayoutIntent, mergeLayoutIntent } = require("./layout.cjs"); -const { stableId } = require("./utils.cjs"); - -function buildSurface({ observedAt, docker, adb, verses, interfaces, layout, marqueeText = "" }) { - const activeInterfaces = interfaces.filter((entry) => entry?.surface?.root); - return { - schema: "gamecult.eve.surface.v1", - id: "gamecult.network.status.surface", - title: "Odin", - root: { - id: "network-root", - kind: "dashboard", - props: { - title: "Odin Provider Catalog", - observedAt, - summary: `${activeInterfaces.length} Eve surfaces`, - marqueeText, - layout: fullscreenLayoutIntent("odin.providers", -100), - presentation: { - theme: "bifrost-pride", - frame: "animated-rainbow", - dividerMotion: "bifrost-rainbow-dance", - intent: "Odin preserves provider-owned surfaces for catalog/proxy access; Gjallar owns Nightwing overview composition and lowering.", - }, - }, - children: [ - ...activeInterfaces.map((entry) => { - const tree = analyzeElementTree(entry.surface.root); - return { - id: `interface-${stableId(entry.providerId)}`, - kind: "interface", - props: { - title: entry.title || entry.providerId, - verseUri: verseUri(entry), - canonicalService: entry.canonicalService || "", - locatedService: entry.locatedService || "", - cultMeshAddress: entry.cultMeshAddress || "", - endpoints: entry.endpoints || [], - routes: entry.routes || [], - providerId: entry.providerId, - source: entry.source, - status: entry.state, - detail: entry.detail, - overviewSignal: hasOverviewSignal(entry), - version: entry.version, - updatedAt: entry.updatedAt, - layout: mergeLayoutIntent(layout.tiles?.[entry.providerId], entry, interfaces), - tree, - packing: { - strategy: "nested-dense-signal", - flattening: "forbidden-when-surface-root-has-children", - listPolicy: "group-or-tree; never render provider signal as a single log/list blob", - }, - }, - children: [entry.surface.root], - }; - }), - ], - }, - assets: [], - }; -} - -function hasOverviewSignal(entry) { - const root = entry?.surface?.root; - if (!root) return false; - - const providerId = String(entry.providerId || "").toLowerCase(); - const explicit = root.props?.overview || entry.manifest?.overview; - if (explicit?.visible === false) return false; - if (explicit?.visible === true || explicit?.signal === "live-ops") return true; - - const text = surfaceText(root); - if (providerId.includes("voidbot.swarm")) return /\bctb\b|\bs[0-9.]+\s+h[0-9.]+/i.test(text); - if (providerId.includes("stonks.market")) return stonksHasOverviewSignal(root, text); - if (providerId.includes("mimir.stream.layout")) return false; - if (providerId.includes("spotiverse")) return spotiverseHasOverviewSignal(root, text); - if (providerId.includes("streampixels")) return streamPixelsHasOverviewSignal(root, text); - if (providerId.includes("mimir.live.stats")) return mimirHasOverviewSignal(root, text); - - if (/\b(rate limit|playing:\s*none|queue:\s*empty|unavailable|not discovered)\b/i.test(text)) return false; - return hasMetricElement(root) || /\b(users?|viewers?|events?|traffic|ingest|throughput|latency|dropout|queue|pressure|saturation|error|fault|warning)\b/i.test(text); -} - -function stonksHasOverviewSignal(root, text) { - if (root.props?.overview?.visible === true) return true; - return /\b(Market pulse|BITCOIN|ETHEREUM|SOLANA|DOGECOIN|equities|crypto|vol|request traffic|source health)\b/i.test(text); -} - -function spotiverseHasOverviewSignal(root, text) { - const status = String(root.props?.status || "").toLowerCase(); - if (status === "warn" && /\brate limit\b/i.test(text)) return false; - if (/\bplaying:\s*none\b/i.test(text)) return false; - if (/\bqueue:\s*empty|queue:\s*empty or unavailable\b/i.test(text)) return false; - return /\bplaying:\s*(?!none\b).+|\bqueue:\s*(?!empty\b|0\b).+|\brequests?:\s*[1-9]|\bvolume:\s*[1-9]/i.test(text); -} - -function streamPixelsHasOverviewSignal(root, text) { - return [ - /\b(live\s*)?(users?|viewers?)\s*[:=]?\s*[1-9]/i, - /\bevents?(\s*traffic|\s*\/\s*s|\s*per\s*sec)?\s*[:=]?\s*[1-9]/i, - /\bingest\b.*\b(saturation|pressure|traffic|throughput|[1-9][0-9]*(\.[0-9]+)?)\b/i, - /\b(queue|backlog|pressure)\s*[:=]?\s*[1-9]/i, - /\b(errors?|dropped|5xx)\s*[:=]?\s*[1-9]/i, - /\bthroughput\s*[:=]?\s*[1-9]/i, - ].some((pattern) => pattern.test(text)); -} - -function mimirHasOverviewSignal(root, text) { - return [ - /\bdropout\b.*\b[1-9]/i, - /\bstale\s+streams?\s*[:=]?\s*[1-9]/i, - /\blatency\b.*\b([2-9][0-9]{2,}|[1-9]\d+\.\d+ms)\b/i, - /\bconfidence\b.*\b0\.[0-4]/i, - ].some((pattern) => pattern.test(text)); -} - -function surfaceText(root) { - const parts = []; - visitSurface(root, (node) => { - const props = node.props || {}; - for (const key of ["title", "label", "text", "status", "detail", "summary", "value"]) { - if (props[key] !== undefined && props[key] !== null) parts.push(String(props[key])); - } - }); - return parts.join("\n"); -} - -function hasMetricElement(root) { - let found = false; - visitSurface(root, (node) => { - if (node.kind === "metric") found = true; - }); - return found; -} - -function visitSurface(node, visitor) { - if (!node || typeof node !== "object") return; - visitor(node); - for (const child of Array.isArray(node.children) ? node.children : []) { - visitSurface(child, visitor); - } -} - -function buildPendingSurface(message) { - return { - schema: "gamecult.eve.surface.v1", - id: "gamecult.network.status.surface", - title: "Odin", - root: stack("root", [pane("Coordinator", [text("status", message)])]), - assets: [], - }; -} - -function stack(id, children) { - return { id, kind: "stack", props: {}, children }; -} - -function pane(title, children) { - return { id: stableId(`pane-${title}`), kind: "pane", props: { title }, children }; -} - -function card(id, children, tone = "default") { - return { id, kind: "card", props: { title: id }, style: { tone }, children }; -} - -function text(id, value) { - return { id, kind: "text", props: { text: value }, children: [] }; -} - -function metric(id, label, value, tone) { - return { id, kind: "metric", props: { label, text: `${label}: ${value}`, value, tone }, children: [] }; -} - -function verseUri(entry) { - if (entry.cultMeshAddress) return String(entry.cultMeshAddress); - if (entry.locatedService) return String(entry.locatedService); - const providerId = String(entry.providerId || "").trim(); - if (hasBodyPrefix(providerId)) return providerId; - const body = sourceBody(entry.source); - if (!body || providerId.startsWith(`${body}.`)) return providerId; - return `${body}.${providerId}`; -} - -function hasBodyPrefix(providerId) { - return ["starfire", "yggdrasil", "nightwing", "eve", "periwinkle", "raven"].some((body) => providerId.startsWith(`${body}.`)); -} - -function sourceBody(source) { - const value = String(source || ""); - if (value.startsWith("cultmesh:")) return "starfire"; - - return ""; -} - -function adbTone(adb) { - if (adb.state !== "ok") return "warn"; - return adb.devices.some((device) => device.state !== "device") ? "warn" : "ok"; -} - -module.exports = { - buildPendingSurface, - buildSurface, - card, - hasOverviewSignal, - metric, - pane, - stack, - text, -}; diff --git a/test/ghostlight-discovery-documents.test.cjs b/test/ghostlight-discovery-documents.test.cjs deleted file mode 100644 index 5c96e9e..0000000 --- a/test/ghostlight-discovery-documents.test.cjs +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); - -const { defineOdinDocuments } = require("../src/odin/documents.cjs"); - -test("Odin persists Ghostlight's public schema catalog envelope", () => { - const documents = defineOdinDocuments((definition) => definition); - const catalog = documents.ghostlightSchemaCatalogDefinition; - - assert.equal(catalog.type, "ghostlight.schema_catalog"); - assert.equal(catalog.schemaId, "ghostlight.schema_catalog.v1"); - assert.equal(catalog.schemaVersion, "ghostlight.schema_catalog.v1"); - assert.equal(catalog.name({ providerId: "gamecult.ghostlight.dungeon" }), "gamecult.ghostlight.dungeon"); -}); - -test("Odin's unavailable-runtime projection includes the Ghostlight catalog slot", () => { - const documents = defineOdinDocuments(null); - assert.equal(documents.ghostlightSchemaCatalogDefinition, null); -}); diff --git a/test/heimdall-discovery-documents.test.cjs b/test/heimdall-discovery-documents.test.cjs deleted file mode 100644 index f4f6e47..0000000 --- a/test/heimdall-discovery-documents.test.cjs +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); - -const { defineOdinDocuments } = require("../src/odin/documents.cjs"); - -test("Odin registers the typed Heimdall access discovery documents", () => { - const documents = defineOdinDocuments((definition) => definition); - - assert.equal( - documents.evePluginAdvertisementDefinition.schemaId, - "gamecult.eve.plugin_advertisement.v1", - ); - assert.equal( - documents.heimdallCommandBoundaryDefinition.schemaId, - "heimdall.command_boundary.v1", - ); - assert.equal( - documents.heimdallTransportProfileDefinition.schemaId, - "heimdall.transport_profile.v1", - ); -}); diff --git a/test/idunn-signed-health.test.cjs b/test/idunn-signed-health.test.cjs deleted file mode 100644 index 75b86a0..0000000 --- a/test/idunn-signed-health.test.cjs +++ /dev/null @@ -1,67 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const crypto = require("node:crypto"); -const test = require("node:test"); - -const { - IDUNN_HEALTH_CONTRACT, - signedHealthPayload, - signingMessage, -} = require("../src/odin/idunn-rudp.cjs"); - -test("Odin signs the complete canonical provider-health statement", () => { - const { privateKey, publicKey } = crypto.generateKeyPairSync("ed25519"); - const publicDer = publicKey.export({ type: "spki", format: "der" }); - const rawPublicKey = Buffer.from(publicDer.subarray(publicDer.length - 32)); - const signerIdentityId = crypto - .createHash("sha256") - .update(Buffer.from("gamecult.provider-health.identity.v1\0")) - .update(rawPublicKey) - .digest("hex"); - const publisher = { - daemonId: "yggdrasil-odin", - healthContract: "odin.cultnet-rudp-provider-health", - privateKey, - publisherIncarnationId: "24e0dc7f-6a92-4aa8-9f56-fb513d265e13", - publisherSequence: 0, - signerIdentityId, - sourceRuntimeId: "odin-yggdrasil", - contract: IDUNN_HEALTH_CONTRACT, - }; - - const signed = signedHealthPayload( - publisher, - { state: "active", detail: "catalog current" }, - "2026-08-21T12:34:56.789Z", - ); - - assert.equal(signed.statement[0], "idunn.signed_daemon_health.v1"); - assert.equal(signed.statement[1], "yggdrasil-odin"); - assert.equal(signed.statement[2], "odin.cultnet-rudp-provider-health"); - assert.equal(signed.statement[3], "odin-yggdrasil"); - assert.equal(signed.statement[8], 1); - assert.equal(signed.statement[9], 1787315696789); - assert.equal(signed.statement[15].byteLength, 64); - assert.equal( - crypto.verify( - null, - signingMessage(signed.unsignedPayload), - publicKey, - Buffer.from(signed.statement[15]), - ), - true, - ); - - const tampered = Buffer.from(signed.unsignedPayload); - tampered[tampered.length - 1] ^= 1; - assert.equal( - crypto.verify( - null, - signingMessage(tampered), - publicKey, - Buffer.from(signed.statement[15]), - ), - false, - ); -}); diff --git a/test/provider-ingress.test.cjs b/test/provider-ingress.test.cjs deleted file mode 100644 index 076831c..0000000 --- a/test/provider-ingress.test.cjs +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); - -const { createLiveProviderRegistry } = require("../src/odin/provider-ingress.cjs"); - -test("live provider registry unwraps Rust compatibility records", () => { - const registry = createLiveProviderRegistry(); - registry.ingestDocument({ - schemaId: "gamecult.eve.provider_advertisement.v1", - recordKey: "muninn.telemetry.nightwing", - payload: [{ - value: { - providerId: "muninn.telemetry.nightwing", - title: "Muninn Nightwing Telemetry", - status: "active", - cultMeshAddress: "asgard.nightwing.muninn/telemetry", - capabilities: ["muninn.move_evidence_stream"], - }, - }], - }, { address: "10.77.0.3", port: 40000 }); - - const snapshot = registry.snapshot(); - assert.equal(snapshot.providerAdvertisements.length, 1); - assert.equal(snapshot.providerAdvertisements[0].id, "muninn.telemetry.nightwing"); - assert.deepEqual(snapshot.providerAdvertisements[0].capabilities, ["muninn.move_evidence_stream"]); - assert.equal(snapshot.providerAdvertisements[0].source, "cultnet-rudp://10.77.0.3:40000"); -});