Delete the retired Node coordinator, its tests and npm entry points
src/odin-coordinator.cjs and src/odin/* (probes.cjs docker/adb host probes, state.cjs, provider-ingress.cjs with its 120 s TTL) were retired when the Rust odin-daemon became the deployed body (state/map.yaml: the Node coordinator that held 17871 is retired). The recipe builds only odin-daemon; nothing in the Rust crate graph loads a .cjs file. The live Yggdrasil hermodr container runs from the immutable release /srv/odin/current, not from this tree. Removes src/, test/ (4 test files for that JS), scripts/check-syntax.cjs (the JS syntax gate), and the package.json scripts start, check, test, muninn:build, muninn:start (the last two named a crate that is not in the workspace). gjallar:persona and rust:test stay. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6aba9a8801
commit
06282c47d8
17 changed files with 0 additions and 2988 deletions
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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 };
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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 };
|
||||
|
|
@ -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,
|
||||
};
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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);
|
||||
});
|
||||
|
|
@ -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",
|
||||
);
|
||||
});
|
||||
|
|
@ -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,
|
||||
);
|
||||
});
|
||||
|
|
@ -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");
|
||||
});
|
||||
Loading…
Reference in a new issue